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."),
57 static cl::opt<bool> GenerateDwarfPubNamesSection("generate-dwarf-pubnames",
58 cl::Hidden, cl::init(false),
59 cl::desc("Generate DWARF pubnames section"));
63 Default, Enable, Disable
67 static cl::opt<DefaultOnOff> DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
68 cl::desc("Output prototype dwarf accelerator tables."),
70 clEnumVal(Default, "Default for platform"),
71 clEnumVal(Enable, "Enabled"),
72 clEnumVal(Disable, "Disabled"),
76 static cl::opt<DefaultOnOff> DarwinGDBCompat("darwin-gdb-compat", cl::Hidden,
77 cl::desc("Compatibility with Darwin gdb."),
79 clEnumVal(Default, "Default for platform"),
80 clEnumVal(Enable, "Enabled"),
81 clEnumVal(Disable, "Disabled"),
85 static cl::opt<DefaultOnOff> SplitDwarf("split-dwarf", cl::Hidden,
86 cl::desc("Output prototype dwarf split debug info."),
88 clEnumVal(Default, "Default for platform"),
89 clEnumVal(Enable, "Enabled"),
90 clEnumVal(Disable, "Disabled"),
95 const char *DWARFGroupName = "DWARF Emission";
96 const char *DbgTimerName = "DWARF Debug Writer";
99 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
100 return lhs.first < rhs.first;
103 } // end anonymous namespace
105 //===----------------------------------------------------------------------===//
107 // Configuration values for initial hash set sizes (log2).
109 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
113 DIType DbgVariable::getType() const {
114 DIType Ty = Var.getType();
115 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
116 // addresses instead.
117 if (Var.isBlockByrefVariable()) {
118 /* Byref variables, in Blocks, are declared by the programmer as
119 "SomeType VarName;", but the compiler creates a
120 __Block_byref_x_VarName struct, and gives the variable VarName
121 either the struct, or a pointer to the struct, as its type. This
122 is necessary for various behind-the-scenes things the compiler
123 needs to do with by-reference variables in blocks.
125 However, as far as the original *programmer* is concerned, the
126 variable should still have type 'SomeType', as originally declared.
128 The following function dives into the __Block_byref_x_VarName
129 struct to find the original type of the variable. This will be
130 passed back to the code generating the type for the Debug
131 Information Entry for the variable 'VarName'. 'VarName' will then
132 have the original type 'SomeType' in its debug information.
134 The original type 'SomeType' will be the type of the field named
135 'VarName' inside the __Block_byref_x_VarName struct.
137 NOTE: In order for this to not completely fail on the debugger
138 side, the Debug Information Entry for the variable VarName needs to
139 have a DW_AT_location that tells the debugger how to unwind through
140 the pointers and __Block_byref_x_VarName struct to find the actual
141 value of the variable. The function addBlockByrefType does this. */
143 unsigned tag = Ty.getTag();
145 if (tag == dwarf::DW_TAG_pointer_type) {
146 DIDerivedType DTy = DIDerivedType(Ty);
147 subType = DTy.getTypeDerivedFrom();
150 DICompositeType blockStruct = DICompositeType(subType);
151 DIArray Elements = blockStruct.getTypeArray();
153 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
154 DIDescriptor Element = Elements.getElement(i);
155 DIDerivedType DT = DIDerivedType(Element);
156 if (getName() == DT.getName())
157 return (DT.getTypeDerivedFrom());
163 } // end llvm namespace
165 /// Return Dwarf Version by checking module flags.
166 static unsigned getDwarfVersionFromModule(const Module *M) {
167 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
168 M->getModuleFlagsMetadata(ModuleFlags);
169 for (unsigned I = 0, E = ModuleFlags.size(); I < E; ++I) {
170 const Module::ModuleFlagEntry &MFE = ModuleFlags[I];
171 StringRef Key = MFE.Key->getString();
172 Value *Val = MFE.Val;
174 if (Key == "Dwarf Version")
175 return cast<ConstantInt>(Val)->getZExtValue();
177 return dwarf::DWARF_VERSION;
180 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
181 : Asm(A), MMI(Asm->MMI), FirstCU(0),
182 AbbreviationsSet(InitAbbreviationsSetSize),
183 SourceIdMap(DIEValueAllocator),
184 PrevLabel(NULL), GlobalCUIndexCount(0),
185 InfoHolder(A, &AbbreviationsSet, &Abbreviations, "info_string",
187 SkeletonAbbrevSet(InitAbbreviationsSetSize),
188 SkeletonHolder(A, &SkeletonAbbrevSet, &SkeletonAbbrevs, "skel_string",
191 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
192 DwarfStrSectionSym = TextSectionSym = 0;
193 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
194 DwarfAddrSectionSym = 0;
195 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
196 FunctionBeginSym = FunctionEndSym = 0;
198 // Turn on accelerator tables and older gdb compatibility
200 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
201 if (DarwinGDBCompat == Default) {
203 IsDarwinGDBCompat = true;
205 IsDarwinGDBCompat = false;
207 IsDarwinGDBCompat = DarwinGDBCompat == Enable ? true : false;
209 if (DwarfAccelTables == Default) {
211 HasDwarfAccelTables = true;
213 HasDwarfAccelTables = false;
215 HasDwarfAccelTables = DwarfAccelTables == Enable ? true : false;
217 if (SplitDwarf == Default)
218 HasSplitDwarf = false;
220 HasSplitDwarf = SplitDwarf == Enable ? true : false;
222 DwarfVersion = getDwarfVersionFromModule(MMI->getModule());
225 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
229 DwarfDebug::~DwarfDebug() {
232 // Switch to the specified MCSection and emit an assembler
233 // temporary label to it if SymbolStem is specified.
234 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
235 const char *SymbolStem = 0) {
236 Asm->OutStreamer.SwitchSection(Section);
237 if (!SymbolStem) return 0;
239 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
240 Asm->OutStreamer.EmitLabel(TmpSym);
244 MCSymbol *DwarfUnits::getStringPoolSym() {
245 return Asm->GetTempSymbol(StringPref);
248 MCSymbol *DwarfUnits::getStringPoolEntry(StringRef Str) {
249 std::pair<MCSymbol*, unsigned> &Entry =
250 StringPool.GetOrCreateValue(Str).getValue();
251 if (Entry.first) return Entry.first;
253 Entry.second = NextStringPoolNumber++;
254 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
257 unsigned DwarfUnits::getStringPoolIndex(StringRef Str) {
258 std::pair<MCSymbol*, unsigned> &Entry =
259 StringPool.GetOrCreateValue(Str).getValue();
260 if (Entry.first) return Entry.second;
262 Entry.second = NextStringPoolNumber++;
263 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
267 unsigned DwarfUnits::getAddrPoolIndex(const MCSymbol *Sym) {
268 return getAddrPoolIndex(MCSymbolRefExpr::Create(Sym, Asm->OutContext));
271 unsigned DwarfUnits::getAddrPoolIndex(const MCExpr *Sym) {
272 std::pair<DenseMap<const MCExpr *, unsigned>::iterator, bool> P =
273 AddressPool.insert(std::make_pair(Sym, NextAddrPoolNumber));
275 ++NextAddrPoolNumber;
276 return P.first->second;
279 // Define a unique number for the abbreviation.
281 void DwarfUnits::assignAbbrevNumber(DIEAbbrev &Abbrev) {
282 // Check the set for priors.
283 DIEAbbrev *InSet = AbbreviationsSet->GetOrInsertNode(&Abbrev);
285 // If it's newly added.
286 if (InSet == &Abbrev) {
287 // Add to abbreviation list.
288 Abbreviations->push_back(&Abbrev);
290 // Assign the vector position + 1 as its number.
291 Abbrev.setNumber(Abbreviations->size());
293 // Assign existing abbreviation number.
294 Abbrev.setNumber(InSet->getNumber());
298 static bool isObjCClass(StringRef Name) {
299 return Name.startswith("+") || Name.startswith("-");
302 static bool hasObjCCategory(StringRef Name) {
303 if (!isObjCClass(Name)) return false;
305 size_t pos = Name.find(')');
306 if (pos != std::string::npos) {
307 if (Name[pos+1] != ' ') return false;
313 static void getObjCClassCategory(StringRef In, StringRef &Class,
314 StringRef &Category) {
315 if (!hasObjCCategory(In)) {
316 Class = In.slice(In.find('[') + 1, In.find(' '));
321 Class = In.slice(In.find('[') + 1, In.find('('));
322 Category = In.slice(In.find('[') + 1, In.find(' '));
326 static StringRef getObjCMethodName(StringRef In) {
327 return In.slice(In.find(' ') + 1, In.find(']'));
330 // Add the various names to the Dwarf accelerator table names.
331 static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
333 if (!SP.isDefinition()) return;
335 TheCU->addAccelName(SP.getName(), Die);
337 // If the linkage name is different than the name, go ahead and output
338 // that as well into the name table.
339 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
340 TheCU->addAccelName(SP.getLinkageName(), Die);
342 // If this is an Objective-C selector name add it to the ObjC accelerator
344 if (isObjCClass(SP.getName())) {
345 StringRef Class, Category;
346 getObjCClassCategory(SP.getName(), Class, Category);
347 TheCU->addAccelObjC(Class, Die);
349 TheCU->addAccelObjC(Category, Die);
350 // Also add the base method name to the name table.
351 TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
355 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
356 // and DW_AT_high_pc attributes. If there are global variables in this
357 // scope then create and insert DIEs for these variables.
358 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
359 const MDNode *SPNode) {
360 DIE *SPDie = SPCU->getDIE(SPNode);
362 assert(SPDie && "Unable to find subprogram DIE!");
363 DISubprogram SP(SPNode);
365 // If we're updating an abstract DIE, then we will be adding the children and
366 // object pointer later on. But what we don't want to do is process the
367 // concrete DIE twice.
368 DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode);
370 bool InSameCU = (AbsSPDIE->getCompileUnit() == SPCU->getCUDie());
371 // Pick up abstract subprogram DIE.
372 SPDie = new DIE(dwarf::DW_TAG_subprogram);
373 // If AbsSPDIE belongs to a different CU, use DW_FORM_ref_addr instead of
375 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
376 InSameCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
380 DISubprogram SPDecl = SP.getFunctionDeclaration();
381 if (!SPDecl.isSubprogram()) {
382 // There is not any need to generate specification DIE for a function
383 // defined at compile unit level. If a function is defined inside another
384 // function then gdb prefers the definition at top level and but does not
385 // expect specification DIE in parent function. So avoid creating
386 // specification DIE for a function defined inside a function.
387 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
388 !SP.getContext().isFile() &&
389 !isSubprogramContext(SP.getContext())) {
390 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
393 DICompositeType SPTy = SP.getType();
394 DIArray Args = SPTy.getTypeArray();
395 unsigned SPTag = SPTy.getTag();
396 if (SPTag == dwarf::DW_TAG_subroutine_type)
397 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
398 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
399 DIType ATy = DIType(Args.getElement(i));
400 SPCU->addType(Arg, ATy);
401 if (ATy.isArtificial())
402 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
403 if (ATy.isObjectPointer())
404 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer,
405 dwarf::DW_FORM_ref4, Arg);
406 SPDie->addChild(Arg);
408 DIE *SPDeclDie = SPDie;
409 SPDie = new DIE(dwarf::DW_TAG_subprogram);
410 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification,
411 dwarf::DW_FORM_ref4, SPDeclDie);
417 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc,
418 Asm->GetTempSymbol("func_begin",
419 Asm->getFunctionNumber()));
420 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc,
421 Asm->GetTempSymbol("func_end",
422 Asm->getFunctionNumber()));
423 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
424 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
425 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
427 // Add name to the name table, we do this here because we're guaranteed
428 // to have concrete versions of our DW_TAG_subprogram nodes.
429 addSubprogramNames(SPCU, SP, SPDie);
434 // Construct new DW_TAG_lexical_block for this scope and attach
435 // DW_AT_low_pc/DW_AT_high_pc labels.
436 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
437 LexicalScope *Scope) {
438 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
439 if (Scope->isAbstractScope())
442 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
446 // If we have multiple ranges, emit them into the range section.
447 if (Ranges.size() > 1) {
448 // .debug_range section has not been laid out yet. Emit offset in
449 // .debug_range as a uint, size 4, for now. emitDIE will handle
450 // DW_AT_ranges appropriately.
451 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
452 DebugRangeSymbols.size()
453 * Asm->getDataLayout().getPointerSize());
454 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
455 RE = Ranges.end(); RI != RE; ++RI) {
456 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
457 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
460 // Terminate the range list.
461 DebugRangeSymbols.push_back(NULL);
462 DebugRangeSymbols.push_back(NULL);
466 // Construct the address range for this DIE.
467 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
468 MCSymbol *Start = getLabelBeforeInsn(RI->first);
469 MCSymbol *End = getLabelAfterInsn(RI->second);
471 if (End == 0) return 0;
473 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
474 assert(End->isDefined() && "Invalid end label for an inlined scope!");
476 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
477 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
482 // This scope represents inlined body of a function. Construct DIE to
483 // represent this concrete inlined copy of the function.
484 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
485 LexicalScope *Scope) {
486 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
487 assert(Ranges.empty() == false &&
488 "LexicalScope does not have instruction markers!");
490 if (!Scope->getScopeNode())
492 DIScope DS(Scope->getScopeNode());
493 DISubprogram InlinedSP = getDISubprogram(DS);
494 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
496 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
500 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
501 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
502 dwarf::DW_FORM_ref4, OriginDIE);
504 if (Ranges.size() > 1) {
505 // .debug_range section has not been laid out yet. Emit offset in
506 // .debug_range as a uint, size 4, for now. emitDIE will handle
507 // DW_AT_ranges appropriately.
508 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
509 DebugRangeSymbols.size()
510 * Asm->getDataLayout().getPointerSize());
511 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
512 RE = Ranges.end(); RI != RE; ++RI) {
513 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
514 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
516 DebugRangeSymbols.push_back(NULL);
517 DebugRangeSymbols.push_back(NULL);
519 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
520 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
521 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
523 if (StartLabel == 0 || EndLabel == 0)
524 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
526 assert(StartLabel->isDefined() &&
527 "Invalid starting label for an inlined scope!");
528 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
530 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
531 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
534 InlinedSubprogramDIEs.insert(OriginDIE);
536 // Add the call site information to the DIE.
537 DILocation DL(Scope->getInlinedAt());
538 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
539 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
540 TheCU->getUniqueID()));
541 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
543 // Track the start label for this inlined function.
544 //.debug_inlined section specification does not clearly state how
545 // to emit inlined scopes that are split into multiple instruction ranges.
546 // For now, use the first instruction range and emit low_pc/high_pc pair and
547 // corresponding the .debug_inlined section entry for this pair.
548 if (Asm->MAI->doesDwarfUseInlineInfoSection()) {
549 MCSymbol *StartLabel = getLabelBeforeInsn(Ranges.begin()->first);
550 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator I =
551 InlineInfo.find(InlinedSP);
553 if (I == InlineInfo.end()) {
554 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
555 InlinedSPNodes.push_back(InlinedSP);
557 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
560 // Add name to the name table, we do this here because we're guaranteed
561 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
562 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
567 // Construct a DIE for this scope.
568 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
569 if (!Scope || !Scope->getScopeNode())
572 DIScope DS(Scope->getScopeNode());
573 // Early return to avoid creating dangling variable|scope DIEs.
574 if (!Scope->getInlinedAt() && DS.isSubprogram() && Scope->isAbstractScope() &&
578 SmallVector<DIE *, 8> Children;
579 DIE *ObjectPointer = NULL;
581 // Collect arguments for current function.
582 if (LScopes.isCurrentFunctionScope(Scope))
583 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
584 if (DbgVariable *ArgDV = CurrentFnArguments[i])
586 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope())) {
587 Children.push_back(Arg);
588 if (ArgDV->isObjectPointer()) ObjectPointer = Arg;
591 // Collect lexical scope children first.
592 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
593 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
595 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope())) {
596 Children.push_back(Variable);
597 if (Variables[i]->isObjectPointer()) ObjectPointer = Variable;
599 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
600 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
601 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
602 Children.push_back(Nested);
603 DIE *ScopeDIE = NULL;
604 if (Scope->getInlinedAt())
605 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
606 else if (DS.isSubprogram()) {
607 ProcessedSPNodes.insert(DS);
608 if (Scope->isAbstractScope()) {
609 ScopeDIE = TheCU->getDIE(DS);
610 // Note down abstract DIE.
612 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
615 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
618 // There is no need to emit empty lexical block DIE.
619 std::pair<ImportedEntityMap::const_iterator,
620 ImportedEntityMap::const_iterator> Range = std::equal_range(
621 ScopesWithImportedEntities.begin(), ScopesWithImportedEntities.end(),
622 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode*)0),
624 if (Children.empty() && Range.first == Range.second)
626 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
627 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
629 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
632 if (!ScopeDIE) return NULL;
635 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
636 E = Children.end(); I != E; ++I)
637 ScopeDIE->addChild(*I);
639 if (DS.isSubprogram() && ObjectPointer != NULL)
640 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer,
641 dwarf::DW_FORM_ref4, ObjectPointer);
643 if (DS.isSubprogram())
644 TheCU->addPubTypes(DISubprogram(DS));
649 // Look up the source id with the given directory and source file names.
650 // If none currently exists, create a new id and insert it in the
651 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
653 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName,
654 StringRef DirName, unsigned CUID) {
655 // If we use .loc in assembly, we can't separate .file entries according to
656 // compile units. Thus all files will belong to the default compile unit.
657 if (Asm->TM.hasMCUseLoc() &&
658 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer)
661 // If FE did not provide a file name, then assume stdin.
662 if (FileName.empty())
663 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
665 // TODO: this might not belong here. See if we can factor this better.
666 if (DirName == CompilationDir)
669 // FileIDCUMap stores the current ID for the given compile unit.
670 unsigned SrcId = FileIDCUMap[CUID] + 1;
672 // We look up the CUID/file/dir by concatenating them with a zero byte.
673 SmallString<128> NamePair;
674 NamePair += utostr(CUID);
677 NamePair += '\0'; // Zero bytes are not allowed in paths.
678 NamePair += FileName;
680 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
681 if (Ent.getValue() != SrcId)
682 return Ent.getValue();
684 FileIDCUMap[CUID] = SrcId;
685 // Print out a .file directive to specify files for .loc directives.
686 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
691 // Create new CompileUnit for the given metadata node with tag
692 // DW_TAG_compile_unit.
693 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
694 DICompileUnit DIUnit(N);
695 StringRef FN = DIUnit.getFilename();
696 CompilationDir = DIUnit.getDirectory();
698 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
699 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
700 DIUnit.getLanguage(), Die, N, Asm,
703 FileIDCUMap[NewCU->getUniqueID()] = 0;
704 // Call this to emit a .file directive if it wasn't emitted for the source
705 // file this CU comes from yet.
706 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
708 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
709 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
710 DIUnit.getLanguage());
711 NewCU->addString(Die, dwarf::DW_AT_name, FN);
713 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
714 // into an entity. We're using 0 (or a NULL label) for this. For
715 // split dwarf it's in the skeleton CU so omit it here.
716 if (!useSplitDwarf())
717 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
719 // Define start line table label for each Compile Unit.
720 MCSymbol *LineTableStartSym = Asm->GetTempSymbol("line_table_start",
721 NewCU->getUniqueID());
722 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
723 NewCU->getUniqueID());
725 // Use a single line table if we are using .loc and generating assembly.
727 (Asm->TM.hasMCUseLoc() &&
728 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer) ||
729 (NewCU->getUniqueID() == 0);
731 // DW_AT_stmt_list is a offset of line number information for this
732 // compile unit in debug_line section. For split dwarf this is
733 // left in the skeleton CU and so not included.
734 // The line table entries are not always emitted in assembly, so it
735 // is not okay to use line_table_start here.
736 if (!useSplitDwarf()) {
737 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
738 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
740 Asm->GetTempSymbol("section_line") : LineTableStartSym);
741 else if (UseTheFirstCU)
742 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
744 NewCU->addDelta(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
745 LineTableStartSym, DwarfLineSectionSym);
748 // If we're using split dwarf the compilation dir is going to be in the
749 // skeleton CU and so we don't need to duplicate it here.
750 if (!useSplitDwarf() && !CompilationDir.empty())
751 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
752 if (DIUnit.isOptimized())
753 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
755 StringRef Flags = DIUnit.getFlags();
757 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
759 if (unsigned RVer = DIUnit.getRunTimeVersion())
760 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
761 dwarf::DW_FORM_data1, RVer);
766 InfoHolder.addUnit(NewCU);
768 CUMap.insert(std::make_pair(N, NewCU));
772 // Construct subprogram DIE.
773 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
775 CompileUnit *&CURef = SPMap[N];
781 if (!SP.isDefinition())
782 // This is a method declaration which will be handled while constructing
786 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
789 TheCU->insertDIE(N, SubprogramDie);
791 // Add to context owner.
792 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
794 // Expose as global, if requested.
795 if (GenerateDwarfPubNamesSection)
796 TheCU->addGlobalName(SP.getName(), SubprogramDie);
799 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
801 DIImportedEntity Module(N);
802 if (!Module.Verify())
804 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
805 constructImportedEntityDIE(TheCU, Module, D);
808 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU, const MDNode *N,
810 DIImportedEntity Module(N);
811 if (!Module.Verify())
813 return constructImportedEntityDIE(TheCU, Module, Context);
816 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
817 const DIImportedEntity &Module,
819 assert(Module.Verify() &&
820 "Use one of the MDNode * overloads to handle invalid metadata");
821 assert(Context && "Should always have a context for an imported_module");
822 DIE *IMDie = new DIE(Module.getTag());
823 TheCU->insertDIE(Module, IMDie);
825 DIDescriptor Entity = Module.getEntity();
826 if (Entity.isNameSpace())
827 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
828 else if (Entity.isSubprogram())
829 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
830 else if (Entity.isType())
831 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
833 EntityDie = TheCU->getDIE(Entity);
834 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
835 Module.getContext().getDirectory(),
836 TheCU->getUniqueID());
837 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, 0, FileID);
838 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, 0, Module.getLineNumber());
839 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, dwarf::DW_FORM_ref4,
841 StringRef Name = Module.getName();
843 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
844 Context->addChild(IMDie);
847 // Emit all Dwarf sections that should come prior to the content. Create
848 // global DIEs and emit initial debug info sections. This is invoked by
849 // the target AsmPrinter.
850 void DwarfDebug::beginModule() {
851 if (DisableDebugInfoPrinting)
854 const Module *M = MMI->getModule();
856 // If module has named metadata anchors then use them, otherwise scan the
857 // module using debug info finder to collect debug info.
858 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
862 // Emit initial sections so we can reference labels later.
865 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
866 DICompileUnit CUNode(CU_Nodes->getOperand(i));
867 CompileUnit *CU = constructCompileUnit(CUNode);
868 DIArray ImportedEntities = CUNode.getImportedEntities();
869 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
870 ScopesWithImportedEntities.push_back(std::make_pair(
871 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
872 ImportedEntities.getElement(i)));
873 std::sort(ScopesWithImportedEntities.begin(),
874 ScopesWithImportedEntities.end(), CompareFirst());
875 DIArray GVs = CUNode.getGlobalVariables();
876 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
877 CU->createGlobalVariableDIE(GVs.getElement(i));
878 DIArray SPs = CUNode.getSubprograms();
879 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
880 constructSubprogramDIE(CU, SPs.getElement(i));
881 DIArray EnumTypes = CUNode.getEnumTypes();
882 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
883 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
884 DIArray RetainedTypes = CUNode.getRetainedTypes();
885 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
886 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
887 // Emit imported_modules last so that the relevant context is already
889 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
890 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
891 // If we're splitting the dwarf out now that we've got the entire
892 // CU then construct a skeleton CU based upon it.
893 if (useSplitDwarf()) {
894 // This should be a unique identifier when we want to build .dwp files.
895 CU->addUInt(CU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
896 dwarf::DW_FORM_data8, 0);
897 // Now construct the skeleton CU associated.
898 constructSkeletonCU(CUNode);
902 // Tell MMI that we have debug info.
903 MMI->setDebugInfoAvailability(true);
905 // Prime section data.
906 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
909 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
910 void DwarfDebug::computeInlinedDIEs() {
911 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
912 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
913 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
915 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
917 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
918 AE = AbstractSPDies.end(); AI != AE; ++AI) {
919 DIE *ISP = AI->second;
920 if (InlinedSubprogramDIEs.count(ISP))
922 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
926 // Collect info for variables that were optimized out.
927 void DwarfDebug::collectDeadVariables() {
928 const Module *M = MMI->getModule();
929 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
931 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
932 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
933 DICompileUnit TheCU(CU_Nodes->getOperand(i));
934 DIArray Subprograms = TheCU.getSubprograms();
935 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
936 DISubprogram SP(Subprograms.getElement(i));
937 if (ProcessedSPNodes.count(SP) != 0) continue;
938 if (!SP.Verify()) continue;
939 if (!SP.isDefinition()) continue;
940 DIArray Variables = SP.getVariables();
941 if (Variables.getNumElements() == 0) continue;
943 LexicalScope *Scope =
944 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
945 DeadFnScopeMap[SP] = Scope;
947 // Construct subprogram DIE and add variables DIEs.
948 CompileUnit *SPCU = CUMap.lookup(TheCU);
949 assert(SPCU && "Unable to find Compile Unit!");
950 constructSubprogramDIE(SPCU, SP);
951 DIE *ScopeDIE = SPCU->getDIE(SP);
952 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
953 DIVariable DV(Variables.getElement(vi));
954 if (!DV.Verify()) continue;
955 DbgVariable *NewVar = new DbgVariable(DV, NULL);
956 if (DIE *VariableDIE =
957 SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
958 ScopeDIE->addChild(VariableDIE);
963 DeleteContainerSeconds(DeadFnScopeMap);
966 void DwarfDebug::finalizeModuleInfo() {
967 // Collect info for variables that were optimized out.
968 collectDeadVariables();
970 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
971 computeInlinedDIEs();
973 // Emit DW_AT_containing_type attribute to connect types with their
974 // vtable holding type.
975 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
976 CUE = CUMap.end(); CUI != CUE; ++CUI) {
977 CompileUnit *TheCU = CUI->second;
978 TheCU->constructContainingTypeDIEs();
981 // Compute DIE offsets and sizes.
982 InfoHolder.computeSizeAndOffsets();
984 SkeletonHolder.computeSizeAndOffsets();
987 void DwarfDebug::endSections() {
988 // Standard sections final addresses.
989 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
990 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
991 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
992 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
994 // End text sections.
995 for (unsigned I = 0, E = SectionMap.size(); I != E; ++I) {
996 Asm->OutStreamer.SwitchSection(SectionMap[I]);
997 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", I+1));
1001 // Emit all Dwarf sections that should come after the content.
1002 void DwarfDebug::endModule() {
1004 if (!FirstCU) return;
1006 // End any existing sections.
1007 // TODO: Does this need to happen?
1010 // Finalize the debug info for the module.
1011 finalizeModuleInfo();
1013 if (!useSplitDwarf()) {
1014 // Emit all the DIEs into a debug info section.
1017 // Corresponding abbreviations into a abbrev section.
1018 emitAbbreviations();
1020 // Emit info into a debug loc section.
1023 // Emit info into a debug aranges section.
1026 // Emit info into a debug ranges section.
1029 // Emit info into a debug macinfo section.
1032 // Emit inline info.
1033 // TODO: When we don't need the option anymore we
1034 // can remove all of the code that this section
1036 if (useDarwinGDBCompat())
1037 emitDebugInlineInfo();
1039 // TODO: Fill this in for separated debug sections and separate
1040 // out information into new sections.
1042 // Emit the debug info section and compile units.
1046 // Corresponding abbreviations into a abbrev section.
1047 emitAbbreviations();
1048 emitDebugAbbrevDWO();
1050 // Emit info into a debug loc section.
1053 // Emit info into a debug aranges section.
1056 // Emit info into a debug ranges section.
1059 // Emit info into a debug macinfo section.
1062 // Emit DWO addresses.
1063 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1065 // Emit inline info.
1066 // TODO: When we don't need the option anymore we
1067 // can remove all of the code that this section
1069 if (useDarwinGDBCompat())
1070 emitDebugInlineInfo();
1073 // Emit info into the dwarf accelerator table sections.
1074 if (useDwarfAccelTables()) {
1077 emitAccelNamespaces();
1081 // Emit info into a debug pubnames section, if requested.
1082 if (GenerateDwarfPubNamesSection)
1083 emitDebugPubnames();
1085 // Emit info into a debug pubtypes section.
1086 // TODO: When we don't need the option anymore we can
1087 // remove all of the code that adds to the table.
1088 if (useDarwinGDBCompat())
1089 emitDebugPubTypes();
1091 // Finally emit string information into a string table.
1093 if (useSplitDwarf())
1098 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1099 E = CUMap.end(); I != E; ++I)
1102 for (SmallVectorImpl<CompileUnit *>::iterator I = SkeletonCUs.begin(),
1103 E = SkeletonCUs.end(); I != E; ++I)
1106 // Reset these for the next Module if we have one.
1110 // Find abstract variable, if any, associated with Var.
1111 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1112 DebugLoc ScopeLoc) {
1113 LLVMContext &Ctx = DV->getContext();
1114 // More then one inlined variable corresponds to one abstract variable.
1115 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1116 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1118 return AbsDbgVariable;
1120 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1124 AbsDbgVariable = new DbgVariable(Var, NULL);
1125 addScopeVariable(Scope, AbsDbgVariable);
1126 AbstractVariables[Var] = AbsDbgVariable;
1127 return AbsDbgVariable;
1130 // If Var is a current function argument then add it to CurrentFnArguments list.
1131 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1132 DbgVariable *Var, LexicalScope *Scope) {
1133 if (!LScopes.isCurrentFunctionScope(Scope))
1135 DIVariable DV = Var->getVariable();
1136 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1138 unsigned ArgNo = DV.getArgNumber();
1142 size_t Size = CurrentFnArguments.size();
1144 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1145 // llvm::Function argument size is not good indicator of how many
1146 // arguments does the function have at source level.
1148 CurrentFnArguments.resize(ArgNo * 2);
1149 CurrentFnArguments[ArgNo - 1] = Var;
1153 // Collect variable information from side table maintained by MMI.
1155 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1156 SmallPtrSet<const MDNode *, 16> &Processed) {
1157 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1158 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1159 VE = VMap.end(); VI != VE; ++VI) {
1160 const MDNode *Var = VI->first;
1162 Processed.insert(Var);
1164 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1166 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1168 // If variable scope is not found then skip this variable.
1172 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1173 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
1174 RegVar->setFrameIndex(VP.first);
1175 if (!addCurrentFnArgument(MF, RegVar, Scope))
1176 addScopeVariable(Scope, RegVar);
1178 AbsDbgVariable->setFrameIndex(VP.first);
1182 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1184 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1185 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1186 return MI->getNumOperands() == 3 &&
1187 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1188 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
1191 // Get .debug_loc entry for the instruction range starting at MI.
1192 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1193 const MCSymbol *FLabel,
1194 const MCSymbol *SLabel,
1195 const MachineInstr *MI) {
1196 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1198 assert(MI->getNumOperands() == 3);
1199 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
1200 MachineLocation MLoc;
1201 // TODO: Currently an offset of 0 in a DBG_VALUE means
1202 // we need to generate a direct register value.
1203 // There is no way to specify an indirect value with offset 0.
1204 if (MI->getOperand(1).getImm() == 0)
1205 MLoc.set(MI->getOperand(0).getReg());
1207 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1208 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1210 if (MI->getOperand(0).isImm())
1211 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1212 if (MI->getOperand(0).isFPImm())
1213 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1214 if (MI->getOperand(0).isCImm())
1215 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1217 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1220 // Find variables for each lexical scope.
1222 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1223 SmallPtrSet<const MDNode *, 16> &Processed) {
1225 // collection info from MMI table.
1226 collectVariableInfoFromMMITable(MF, Processed);
1228 for (SmallVectorImpl<const MDNode*>::const_iterator
1229 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1231 const MDNode *Var = *UVI;
1232 if (Processed.count(Var))
1235 // History contains relevant DBG_VALUE instructions for Var and instructions
1237 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1238 if (History.empty())
1240 const MachineInstr *MInsn = History.front();
1243 LexicalScope *Scope = NULL;
1244 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1245 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1246 Scope = LScopes.getCurrentFunctionScope();
1247 else if (MDNode *IA = DV.getInlinedAt())
1248 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1250 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1251 // If variable scope is not found then skip this variable.
1255 Processed.insert(DV);
1256 assert(MInsn->isDebugValue() && "History must begin with debug value");
1257 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1258 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1259 if (!addCurrentFnArgument(MF, RegVar, Scope))
1260 addScopeVariable(Scope, RegVar);
1262 AbsVar->setMInsn(MInsn);
1264 // Simplify ranges that are fully coalesced.
1265 if (History.size() <= 1 || (History.size() == 2 &&
1266 MInsn->isIdenticalTo(History.back()))) {
1267 RegVar->setMInsn(MInsn);
1271 // Handle multiple DBG_VALUE instructions describing one variable.
1272 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1274 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1275 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1276 const MachineInstr *Begin = *HI;
1277 assert(Begin->isDebugValue() && "Invalid History entry");
1279 // Check if DBG_VALUE is truncating a range.
1280 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1281 && !Begin->getOperand(0).getReg())
1284 // Compute the range for a register location.
1285 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1286 const MCSymbol *SLabel = 0;
1289 // If Begin is the last instruction in History then its value is valid
1290 // until the end of the function.
1291 SLabel = FunctionEndSym;
1293 const MachineInstr *End = HI[1];
1294 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1295 << "\t" << *Begin << "\t" << *End << "\n");
1296 if (End->isDebugValue())
1297 SLabel = getLabelBeforeInsn(End);
1299 // End is a normal instruction clobbering the range.
1300 SLabel = getLabelAfterInsn(End);
1301 assert(SLabel && "Forgot label after clobber instruction");
1306 // The value is valid until the next DBG_VALUE or clobber.
1307 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1310 DotDebugLocEntries.push_back(DotDebugLocEntry());
1313 // Collect info for variables that were optimized out.
1314 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1315 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1316 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1317 DIVariable DV(Variables.getElement(i));
1318 if (!DV || !DV.Verify() || !Processed.insert(DV))
1320 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1321 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1325 // Return Label preceding the instruction.
1326 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1327 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1328 assert(Label && "Didn't insert label before instruction");
1332 // Return Label immediately following the instruction.
1333 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1334 return LabelsAfterInsn.lookup(MI);
1337 // Process beginning of an instruction.
1338 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1339 // Check if source location changes, but ignore DBG_VALUE locations.
1340 if (!MI->isDebugValue()) {
1341 DebugLoc DL = MI->getDebugLoc();
1342 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1345 if (DL == PrologEndLoc) {
1346 Flags |= DWARF2_FLAG_PROLOGUE_END;
1347 PrologEndLoc = DebugLoc();
1349 if (PrologEndLoc.isUnknown())
1350 Flags |= DWARF2_FLAG_IS_STMT;
1352 if (!DL.isUnknown()) {
1353 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1354 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1356 recordSourceLine(0, 0, 0, 0);
1360 // Insert labels where requested.
1361 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1362 LabelsBeforeInsn.find(MI);
1365 if (I == LabelsBeforeInsn.end())
1368 // Label already assigned.
1373 PrevLabel = MMI->getContext().CreateTempSymbol();
1374 Asm->OutStreamer.EmitLabel(PrevLabel);
1376 I->second = PrevLabel;
1379 // Process end of an instruction.
1380 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1381 // Don't create a new label after DBG_VALUE instructions.
1382 // They don't generate code.
1383 if (!MI->isDebugValue())
1386 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1387 LabelsAfterInsn.find(MI);
1390 if (I == LabelsAfterInsn.end())
1393 // Label already assigned.
1397 // We need a label after this instruction.
1399 PrevLabel = MMI->getContext().CreateTempSymbol();
1400 Asm->OutStreamer.EmitLabel(PrevLabel);
1402 I->second = PrevLabel;
1405 // Each LexicalScope has first instruction and last instruction to mark
1406 // beginning and end of a scope respectively. Create an inverse map that list
1407 // scopes starts (and ends) with an instruction. One instruction may start (or
1408 // end) multiple scopes. Ignore scopes that are not reachable.
1409 void DwarfDebug::identifyScopeMarkers() {
1410 SmallVector<LexicalScope *, 4> WorkList;
1411 WorkList.push_back(LScopes.getCurrentFunctionScope());
1412 while (!WorkList.empty()) {
1413 LexicalScope *S = WorkList.pop_back_val();
1415 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1416 if (!Children.empty())
1417 for (SmallVectorImpl<LexicalScope *>::const_iterator SI = Children.begin(),
1418 SE = Children.end(); SI != SE; ++SI)
1419 WorkList.push_back(*SI);
1421 if (S->isAbstractScope())
1424 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1427 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1428 RE = Ranges.end(); RI != RE; ++RI) {
1429 assert(RI->first && "InsnRange does not have first instruction!");
1430 assert(RI->second && "InsnRange does not have second instruction!");
1431 requestLabelBeforeInsn(RI->first);
1432 requestLabelAfterInsn(RI->second);
1437 // Get MDNode for DebugLoc's scope.
1438 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1439 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1440 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1441 return DL.getScope(Ctx);
1444 // Walk up the scope chain of given debug loc and find line number info
1445 // for the function.
1446 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1447 const MDNode *Scope = getScopeNode(DL, Ctx);
1448 DISubprogram SP = getDISubprogram(Scope);
1450 // Check for number of operands since the compatibility is
1452 if (SP->getNumOperands() > 19)
1453 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1455 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1461 // Gather pre-function debug information. Assumes being called immediately
1462 // after the function entry point has been emitted.
1463 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1464 if (!MMI->hasDebugInfo()) return;
1465 LScopes.initialize(*MF);
1466 if (LScopes.empty()) return;
1467 identifyScopeMarkers();
1469 // Set DwarfCompileUnitID in MCContext to the Compile Unit this function
1471 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1472 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1473 assert(TheCU && "Unable to find compile unit!");
1474 if (Asm->TM.hasMCUseLoc() &&
1475 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer)
1476 // Use a single line table if we are using .loc and generating assembly.
1477 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1479 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1481 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1482 Asm->getFunctionNumber());
1483 // Assumes in correct section after the entry point.
1484 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1486 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1488 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1489 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1490 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1492 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1494 bool AtBlockEntry = true;
1495 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1497 const MachineInstr *MI = II;
1499 if (MI->isDebugValue()) {
1500 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1502 // Keep track of user variables.
1504 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1506 // Variable is in a register, we need to check for clobbers.
1507 if (isDbgValueInDefinedReg(MI))
1508 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1510 // Check the history of this variable.
1511 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1512 if (History.empty()) {
1513 UserVariables.push_back(Var);
1514 // The first mention of a function argument gets the FunctionBeginSym
1515 // label, so arguments are visible when breaking at function entry.
1517 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1518 DISubprogram(getDISubprogram(DV.getContext()))
1519 .describes(MF->getFunction()))
1520 LabelsBeforeInsn[MI] = FunctionBeginSym;
1522 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1523 const MachineInstr *Prev = History.back();
1524 if (Prev->isDebugValue()) {
1525 // Coalesce identical entries at the end of History.
1526 if (History.size() >= 2 &&
1527 Prev->isIdenticalTo(History[History.size() - 2])) {
1528 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1530 << "\t" << *History[History.size() - 2] << "\n");
1534 // Terminate old register assignments that don't reach MI;
1535 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1536 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1537 isDbgValueInDefinedReg(Prev)) {
1538 // Previous register assignment needs to terminate at the end of
1540 MachineBasicBlock::const_iterator LastMI =
1541 PrevMBB->getLastNonDebugInstr();
1542 if (LastMI == PrevMBB->end()) {
1543 // Drop DBG_VALUE for empty range.
1544 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1545 << "\t" << *Prev << "\n");
1547 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1548 // Terminate after LastMI.
1549 History.push_back(LastMI);
1553 History.push_back(MI);
1555 // Not a DBG_VALUE instruction.
1557 AtBlockEntry = false;
1559 // First known non-DBG_VALUE and non-frame setup location marks
1560 // the beginning of the function body.
1561 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1562 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1563 PrologEndLoc = MI->getDebugLoc();
1565 // Check if the instruction clobbers any registers with debug vars.
1566 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1567 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1568 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1570 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1571 AI.isValid(); ++AI) {
1573 const MDNode *Var = LiveUserVar[Reg];
1576 // Reg is now clobbered.
1577 LiveUserVar[Reg] = 0;
1579 // Was MD last defined by a DBG_VALUE referring to Reg?
1580 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1581 if (HistI == DbgValues.end())
1583 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1584 if (History.empty())
1586 const MachineInstr *Prev = History.back();
1587 // Sanity-check: Register assignments are terminated at the end of
1589 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1591 // Is the variable still in Reg?
1592 if (!isDbgValueInDefinedReg(Prev) ||
1593 Prev->getOperand(0).getReg() != Reg)
1595 // Var is clobbered. Make sure the next instruction gets a label.
1596 History.push_back(MI);
1603 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1605 SmallVectorImpl<const MachineInstr*> &History = I->second;
1606 if (History.empty())
1609 // Make sure the final register assignments are terminated.
1610 const MachineInstr *Prev = History.back();
1611 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1612 const MachineBasicBlock *PrevMBB = Prev->getParent();
1613 MachineBasicBlock::const_iterator LastMI =
1614 PrevMBB->getLastNonDebugInstr();
1615 if (LastMI == PrevMBB->end())
1616 // Drop DBG_VALUE for empty range.
1618 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1619 // Terminate after LastMI.
1620 History.push_back(LastMI);
1623 // Request labels for the full history.
1624 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1625 const MachineInstr *MI = History[i];
1626 if (MI->isDebugValue())
1627 requestLabelBeforeInsn(MI);
1629 requestLabelAfterInsn(MI);
1633 PrevInstLoc = DebugLoc();
1634 PrevLabel = FunctionBeginSym;
1636 // Record beginning of function.
1637 if (!PrologEndLoc.isUnknown()) {
1638 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1639 MF->getFunction()->getContext());
1640 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1641 FnStartDL.getScope(MF->getFunction()->getContext()),
1642 // We'd like to list the prologue as "not statements" but GDB behaves
1643 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1644 DWARF2_FLAG_IS_STMT);
1648 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1649 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1650 DIVariable DV = Var->getVariable();
1651 // Variables with positive arg numbers are parameters.
1652 if (unsigned ArgNum = DV.getArgNumber()) {
1653 // Keep all parameters in order at the start of the variable list to ensure
1654 // function types are correct (no out-of-order parameters)
1656 // This could be improved by only doing it for optimized builds (unoptimized
1657 // builds have the right order to begin with), searching from the back (this
1658 // would catch the unoptimized case quickly), or doing a binary search
1659 // rather than linear search.
1660 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1661 while (I != Vars.end()) {
1662 unsigned CurNum = (*I)->getVariable().getArgNumber();
1663 // A local (non-parameter) variable has been found, insert immediately
1667 // A later indexed parameter has been found, insert immediately before it.
1668 if (CurNum > ArgNum)
1672 Vars.insert(I, Var);
1676 Vars.push_back(Var);
1679 // Gather and emit post-function debug information.
1680 void DwarfDebug::endFunction(const MachineFunction *MF) {
1681 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1683 // Define end label for subprogram.
1684 FunctionEndSym = Asm->GetTempSymbol("func_end",
1685 Asm->getFunctionNumber());
1686 // Assumes in correct section after the entry point.
1687 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1688 // Set DwarfCompileUnitID in MCContext to default value.
1689 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1691 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1692 collectVariableInfo(MF, ProcessedVars);
1694 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1695 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1696 assert(TheCU && "Unable to find compile unit!");
1698 // Construct abstract scopes.
1699 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1700 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1701 LexicalScope *AScope = AList[i];
1702 DISubprogram SP(AScope->getScopeNode());
1704 // Collect info for variables that were optimized out.
1705 DIArray Variables = SP.getVariables();
1706 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1707 DIVariable DV(Variables.getElement(i));
1708 if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1710 // Check that DbgVariable for DV wasn't created earlier, when
1711 // findAbstractVariable() was called for inlined instance of DV.
1712 LLVMContext &Ctx = DV->getContext();
1713 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1714 if (AbstractVariables.lookup(CleanDV))
1716 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1717 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1720 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1721 constructScopeDIE(TheCU, AScope);
1724 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1726 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1727 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1730 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1731 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1732 DeleteContainerPointers(I->second);
1733 ScopeVariables.clear();
1734 DeleteContainerPointers(CurrentFnArguments);
1735 UserVariables.clear();
1737 AbstractVariables.clear();
1738 LabelsBeforeInsn.clear();
1739 LabelsAfterInsn.clear();
1743 // Register a source line with debug info. Returns the unique label that was
1744 // emitted and which provides correspondence to the source line list.
1745 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1751 DIDescriptor Scope(S);
1753 if (Scope.isCompileUnit()) {
1754 DICompileUnit CU(S);
1755 Fn = CU.getFilename();
1756 Dir = CU.getDirectory();
1757 } else if (Scope.isFile()) {
1759 Fn = F.getFilename();
1760 Dir = F.getDirectory();
1761 } else if (Scope.isSubprogram()) {
1763 Fn = SP.getFilename();
1764 Dir = SP.getDirectory();
1765 } else if (Scope.isLexicalBlockFile()) {
1766 DILexicalBlockFile DBF(S);
1767 Fn = DBF.getFilename();
1768 Dir = DBF.getDirectory();
1769 } else if (Scope.isLexicalBlock()) {
1770 DILexicalBlock DB(S);
1771 Fn = DB.getFilename();
1772 Dir = DB.getDirectory();
1774 llvm_unreachable("Unexpected scope info");
1776 Src = getOrCreateSourceID(Fn, Dir,
1777 Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1779 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1782 //===----------------------------------------------------------------------===//
1784 //===----------------------------------------------------------------------===//
1786 // Compute the size and offset of a DIE.
1788 DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1789 // Get the children.
1790 const std::vector<DIE *> &Children = Die->getChildren();
1792 // Record the abbreviation.
1793 assignAbbrevNumber(Die->getAbbrev());
1795 // Get the abbreviation for this DIE.
1796 unsigned AbbrevNumber = Die->getAbbrevNumber();
1797 const DIEAbbrev *Abbrev = Abbreviations->at(AbbrevNumber - 1);
1800 Die->setOffset(Offset);
1802 // Start the size with the size of abbreviation code.
1803 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1805 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1806 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1808 // Size the DIE attribute values.
1809 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1810 // Size attribute value.
1811 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1813 // Size the DIE children if any.
1814 if (!Children.empty()) {
1815 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1816 "Children flag not set");
1818 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1819 Offset = computeSizeAndOffset(Children[j], Offset);
1821 // End of children marker.
1822 Offset += sizeof(int8_t);
1825 Die->setSize(Offset - Die->getOffset());
1829 // Compute the size and offset of all the DIEs.
1830 void DwarfUnits::computeSizeAndOffsets() {
1831 // Offset from the beginning of debug info section.
1832 unsigned SecOffset = 0;
1833 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1834 E = CUs.end(); I != E; ++I) {
1835 (*I)->setDebugInfoOffset(SecOffset);
1837 sizeof(int32_t) + // Length of Compilation Unit Info
1838 sizeof(int16_t) + // DWARF version number
1839 sizeof(int32_t) + // Offset Into Abbrev. Section
1840 sizeof(int8_t); // Pointer Size (in bytes)
1842 unsigned EndOffset = computeSizeAndOffset((*I)->getCUDie(), Offset);
1843 SecOffset += EndOffset;
1847 // Emit initial Dwarf sections with a label at the start of each one.
1848 void DwarfDebug::emitSectionLabels() {
1849 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1851 // Dwarf sections base addresses.
1852 DwarfInfoSectionSym =
1853 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1854 DwarfAbbrevSectionSym =
1855 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1856 if (useSplitDwarf())
1857 DwarfAbbrevDWOSectionSym =
1858 emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
1859 "section_abbrev_dwo");
1860 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1862 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1863 emitSectionSym(Asm, MacroInfo);
1865 DwarfLineSectionSym =
1866 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1867 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1868 if (GenerateDwarfPubNamesSection)
1869 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1870 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1871 DwarfStrSectionSym =
1872 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1873 if (useSplitDwarf()) {
1874 DwarfStrDWOSectionSym =
1875 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1876 DwarfAddrSectionSym =
1877 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1879 DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1882 DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
1883 "section_debug_loc");
1885 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1886 emitSectionSym(Asm, TLOF.getDataSection());
1889 // Recursively emits a debug information entry.
1890 void DwarfDebug::emitDIE(DIE *Die, std::vector<DIEAbbrev *> *Abbrevs) {
1891 // Get the abbreviation for this DIE.
1892 unsigned AbbrevNumber = Die->getAbbrevNumber();
1893 const DIEAbbrev *Abbrev = Abbrevs->at(AbbrevNumber - 1);
1895 // Emit the code (index) for the abbreviation.
1896 if (Asm->isVerbose())
1897 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1898 Twine::utohexstr(Die->getOffset()) + ":0x" +
1899 Twine::utohexstr(Die->getSize()) + " " +
1900 dwarf::TagString(Abbrev->getTag()));
1901 Asm->EmitULEB128(AbbrevNumber);
1903 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1904 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1906 // Emit the DIE attribute values.
1907 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1908 unsigned Attr = AbbrevData[i].getAttribute();
1909 unsigned Form = AbbrevData[i].getForm();
1910 assert(Form && "Too many attributes for DIE (check abbreviation)");
1912 if (Asm->isVerbose())
1913 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1916 case dwarf::DW_AT_abstract_origin: {
1917 DIEEntry *E = cast<DIEEntry>(Values[i]);
1918 DIE *Origin = E->getEntry();
1919 unsigned Addr = Origin->getOffset();
1920 if (Form == dwarf::DW_FORM_ref_addr) {
1921 // For DW_FORM_ref_addr, output the offset from beginning of debug info
1922 // section. Origin->getOffset() returns the offset from start of the
1924 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1925 Addr += Holder.getCUOffset(Origin->getCompileUnit());
1927 Asm->OutStreamer.EmitIntValue(Addr,
1928 Form == dwarf::DW_FORM_ref_addr ? DIEEntry::getRefAddrSize(Asm) : 4);
1931 case dwarf::DW_AT_ranges: {
1932 // DW_AT_range Value encodes offset in debug_range section.
1933 DIEInteger *V = cast<DIEInteger>(Values[i]);
1935 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1936 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1940 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1942 DwarfDebugRangeSectionSym,
1947 case dwarf::DW_AT_location: {
1948 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
1949 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1950 Asm->EmitLabelReference(L->getValue(), 4);
1952 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1954 Values[i]->EmitValue(Asm, Form);
1958 case dwarf::DW_AT_accessibility: {
1959 if (Asm->isVerbose()) {
1960 DIEInteger *V = cast<DIEInteger>(Values[i]);
1961 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1963 Values[i]->EmitValue(Asm, Form);
1967 // Emit an attribute using the defined form.
1968 Values[i]->EmitValue(Asm, Form);
1973 // Emit the DIE children if any.
1974 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1975 const std::vector<DIE *> &Children = Die->getChildren();
1977 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1978 emitDIE(Children[j], Abbrevs);
1980 if (Asm->isVerbose())
1981 Asm->OutStreamer.AddComment("End Of Children Mark");
1986 // Emit the various dwarf units to the unit section USection with
1987 // the abbreviations going into ASection.
1988 void DwarfUnits::emitUnits(DwarfDebug *DD,
1989 const MCSection *USection,
1990 const MCSection *ASection,
1991 const MCSymbol *ASectionSym) {
1992 Asm->OutStreamer.SwitchSection(USection);
1993 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1994 E = CUs.end(); I != E; ++I) {
1995 CompileUnit *TheCU = *I;
1996 DIE *Die = TheCU->getCUDie();
1998 // Emit the compile units header.
2000 .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
2001 TheCU->getUniqueID()));
2003 // Emit size of content not including length itself
2004 unsigned ContentSize = Die->getSize() +
2005 sizeof(int16_t) + // DWARF version number
2006 sizeof(int32_t) + // Offset Into Abbrev. Section
2007 sizeof(int8_t); // Pointer Size (in bytes)
2009 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2010 Asm->EmitInt32(ContentSize);
2011 Asm->OutStreamer.AddComment("DWARF version number");
2012 Asm->EmitInt16(DD->getDwarfVersion());
2013 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2014 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
2016 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2017 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2019 DD->emitDIE(Die, Abbreviations);
2020 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
2021 TheCU->getUniqueID()));
2025 /// For a given compile unit DIE, returns offset from beginning of debug info.
2026 unsigned DwarfUnits::getCUOffset(DIE *Die) {
2027 assert(Die->getTag() == dwarf::DW_TAG_compile_unit &&
2028 "Input DIE should be compile unit in getCUOffset.");
2029 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
2030 E = CUs.end(); I != E; ++I) {
2031 CompileUnit *TheCU = *I;
2032 if (TheCU->getCUDie() == Die)
2033 return TheCU->getDebugInfoOffset();
2035 llvm_unreachable("The compile unit DIE should belong to CUs in DwarfUnits.");
2038 // Emit the debug info section.
2039 void DwarfDebug::emitDebugInfo() {
2040 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2042 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
2043 Asm->getObjFileLowering().getDwarfAbbrevSection(),
2044 DwarfAbbrevSectionSym);
2047 // Emit the abbreviation section.
2048 void DwarfDebug::emitAbbreviations() {
2049 if (!useSplitDwarf())
2050 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
2053 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2056 void DwarfDebug::emitAbbrevs(const MCSection *Section,
2057 std::vector<DIEAbbrev *> *Abbrevs) {
2058 // Check to see if it is worth the effort.
2059 if (!Abbrevs->empty()) {
2060 // Start the debug abbrev section.
2061 Asm->OutStreamer.SwitchSection(Section);
2063 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
2064 Asm->OutStreamer.EmitLabel(Begin);
2066 // For each abbrevation.
2067 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
2068 // Get abbreviation data
2069 const DIEAbbrev *Abbrev = Abbrevs->at(i);
2071 // Emit the abbrevations code (base 1 index.)
2072 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2074 // Emit the abbreviations data.
2078 // Mark end of abbreviations.
2079 Asm->EmitULEB128(0, "EOM(3)");
2081 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
2082 Asm->OutStreamer.EmitLabel(End);
2086 // Emit the last address of the section and the end of the line matrix.
2087 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2088 // Define last address of section.
2089 Asm->OutStreamer.AddComment("Extended Op");
2092 Asm->OutStreamer.AddComment("Op size");
2093 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2094 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2095 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2097 Asm->OutStreamer.AddComment("Section end label");
2099 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2100 Asm->getDataLayout().getPointerSize());
2102 // Mark end of matrix.
2103 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2109 // Emit visible names into a hashed accelerator table section.
2110 void DwarfDebug::emitAccelNames() {
2111 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2112 dwarf::DW_FORM_data4));
2113 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2114 E = CUMap.end(); I != E; ++I) {
2115 CompileUnit *TheCU = I->second;
2116 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
2117 for (StringMap<std::vector<DIE*> >::const_iterator
2118 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2119 StringRef Name = GI->getKey();
2120 const std::vector<DIE *> &Entities = GI->second;
2121 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2122 DE = Entities.end(); DI != DE; ++DI)
2123 AT.AddName(Name, (*DI));
2127 AT.FinalizeTable(Asm, "Names");
2128 Asm->OutStreamer.SwitchSection(
2129 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2130 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2131 Asm->OutStreamer.EmitLabel(SectionBegin);
2133 // Emit the full data.
2134 AT.Emit(Asm, SectionBegin, &InfoHolder);
2137 // Emit objective C classes and categories into a hashed accelerator table
2139 void DwarfDebug::emitAccelObjC() {
2140 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2141 dwarf::DW_FORM_data4));
2142 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2143 E = CUMap.end(); I != E; ++I) {
2144 CompileUnit *TheCU = I->second;
2145 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
2146 for (StringMap<std::vector<DIE*> >::const_iterator
2147 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2148 StringRef Name = GI->getKey();
2149 const std::vector<DIE *> &Entities = GI->second;
2150 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2151 DE = Entities.end(); DI != DE; ++DI)
2152 AT.AddName(Name, (*DI));
2156 AT.FinalizeTable(Asm, "ObjC");
2157 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2158 .getDwarfAccelObjCSection());
2159 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2160 Asm->OutStreamer.EmitLabel(SectionBegin);
2162 // Emit the full data.
2163 AT.Emit(Asm, SectionBegin, &InfoHolder);
2166 // Emit namespace dies into a hashed accelerator table.
2167 void DwarfDebug::emitAccelNamespaces() {
2168 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2169 dwarf::DW_FORM_data4));
2170 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2171 E = CUMap.end(); I != E; ++I) {
2172 CompileUnit *TheCU = I->second;
2173 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2174 for (StringMap<std::vector<DIE*> >::const_iterator
2175 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2176 StringRef Name = GI->getKey();
2177 const std::vector<DIE *> &Entities = GI->second;
2178 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2179 DE = Entities.end(); DI != DE; ++DI)
2180 AT.AddName(Name, (*DI));
2184 AT.FinalizeTable(Asm, "namespac");
2185 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2186 .getDwarfAccelNamespaceSection());
2187 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2188 Asm->OutStreamer.EmitLabel(SectionBegin);
2190 // Emit the full data.
2191 AT.Emit(Asm, SectionBegin, &InfoHolder);
2194 // Emit type dies into a hashed accelerator table.
2195 void DwarfDebug::emitAccelTypes() {
2196 std::vector<DwarfAccelTable::Atom> Atoms;
2197 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2198 dwarf::DW_FORM_data4));
2199 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
2200 dwarf::DW_FORM_data2));
2201 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
2202 dwarf::DW_FORM_data1));
2203 DwarfAccelTable AT(Atoms);
2204 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2205 E = CUMap.end(); I != E; ++I) {
2206 CompileUnit *TheCU = I->second;
2207 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2208 = TheCU->getAccelTypes();
2209 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2210 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2211 StringRef Name = GI->getKey();
2212 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2213 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2214 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2215 AT.AddName(Name, (*DI).first, (*DI).second);
2219 AT.FinalizeTable(Asm, "types");
2220 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2221 .getDwarfAccelTypesSection());
2222 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2223 Asm->OutStreamer.EmitLabel(SectionBegin);
2225 // Emit the full data.
2226 AT.Emit(Asm, SectionBegin, &InfoHolder);
2229 /// emitDebugPubnames - Emit visible names into a debug pubnames section.
2231 void DwarfDebug::emitDebugPubnames() {
2232 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2234 typedef DenseMap<const MDNode*, CompileUnit*> CUMapType;
2235 for (CUMapType::iterator I = CUMap.begin(), E = CUMap.end(); I != E; ++I) {
2236 CompileUnit *TheCU = I->second;
2237 unsigned ID = TheCU->getUniqueID();
2239 if (TheCU->getGlobalNames().empty())
2242 // Start the dwarf pubnames section.
2243 Asm->OutStreamer.SwitchSection(
2244 Asm->getObjFileLowering().getDwarfPubNamesSection());
2246 Asm->OutStreamer.AddComment("Length of Public Names Info");
2247 Asm->EmitLabelDifference(Asm->GetTempSymbol("pubnames_end", ID),
2248 Asm->GetTempSymbol("pubnames_begin", ID), 4);
2250 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", ID));
2252 Asm->OutStreamer.AddComment("DWARF Version");
2253 Asm->EmitInt16(DwarfVersion);
2255 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2256 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2257 DwarfInfoSectionSym);
2259 Asm->OutStreamer.AddComment("Compilation Unit Length");
2260 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(), ID),
2261 Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2264 const StringMap<DIE*> &Globals = TheCU->getGlobalNames();
2265 for (StringMap<DIE*>::const_iterator
2266 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2267 const char *Name = GI->getKeyData();
2268 const DIE *Entity = GI->second;
2270 Asm->OutStreamer.AddComment("DIE offset");
2271 Asm->EmitInt32(Entity->getOffset());
2273 if (Asm->isVerbose())
2274 Asm->OutStreamer.AddComment("External Name");
2275 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2278 Asm->OutStreamer.AddComment("End Mark");
2280 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", ID));
2284 void DwarfDebug::emitDebugPubTypes() {
2285 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2286 E = CUMap.end(); I != E; ++I) {
2287 CompileUnit *TheCU = I->second;
2288 // Start the dwarf pubtypes section.
2289 Asm->OutStreamer.SwitchSection(
2290 Asm->getObjFileLowering().getDwarfPubTypesSection());
2291 Asm->OutStreamer.AddComment("Length of Public Types Info");
2292 Asm->EmitLabelDifference(
2293 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2294 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2296 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2297 TheCU->getUniqueID()));
2299 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2300 Asm->EmitInt16(DwarfVersion);
2302 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2303 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2304 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(),
2305 TheCU->getUniqueID()),
2306 DwarfInfoSectionSym);
2308 Asm->OutStreamer.AddComment("Compilation Unit Length");
2309 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(),
2310 TheCU->getUniqueID()),
2311 Asm->GetTempSymbol(ISec->getLabelBeginName(),
2312 TheCU->getUniqueID()),
2315 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2316 for (StringMap<DIE*>::const_iterator
2317 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2318 const char *Name = GI->getKeyData();
2319 DIE *Entity = GI->second;
2321 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2322 Asm->EmitInt32(Entity->getOffset());
2324 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2325 // Emit the name with a terminating null byte.
2326 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2329 Asm->OutStreamer.AddComment("End Mark");
2331 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2332 TheCU->getUniqueID()));
2336 // Emit strings into a string section.
2337 void DwarfUnits::emitStrings(const MCSection *StrSection,
2338 const MCSection *OffsetSection = NULL,
2339 const MCSymbol *StrSecSym = NULL) {
2341 if (StringPool.empty()) return;
2343 // Start the dwarf str section.
2344 Asm->OutStreamer.SwitchSection(StrSection);
2346 // Get all of the string pool entries and put them in an array by their ID so
2347 // we can sort them.
2348 SmallVector<std::pair<unsigned,
2349 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2351 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2352 I = StringPool.begin(), E = StringPool.end();
2354 Entries.push_back(std::make_pair(I->second.second, &*I));
2356 array_pod_sort(Entries.begin(), Entries.end());
2358 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2359 // Emit a label for reference from debug information entries.
2360 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2362 // Emit the string itself with a terminating null byte.
2363 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2364 Entries[i].second->getKeyLength()+1));
2367 // If we've got an offset section go ahead and emit that now as well.
2368 if (OffsetSection) {
2369 Asm->OutStreamer.SwitchSection(OffsetSection);
2370 unsigned offset = 0;
2371 unsigned size = 4; // FIXME: DWARF64 is 8.
2372 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2373 Asm->OutStreamer.EmitIntValue(offset, size);
2374 offset += Entries[i].second->getKeyLength() + 1;
2379 // Emit strings into a string section.
2380 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2382 if (AddressPool.empty()) return;
2384 // Start the dwarf addr section.
2385 Asm->OutStreamer.SwitchSection(AddrSection);
2387 // Get all of the address pool entries and put them in an array by their ID so
2388 // we can sort them.
2389 SmallVector<std::pair<unsigned, const MCExpr *>, 64> Entries;
2391 for (DenseMap<const MCExpr *, unsigned>::iterator
2392 I = AddressPool.begin(),
2393 E = AddressPool.end();
2395 Entries.push_back(std::make_pair(I->second, I->first));
2397 array_pod_sort(Entries.begin(), Entries.end());
2399 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2400 // Emit an expression for reference from debug information entries.
2401 if (const MCExpr *Expr = Entries[i].second)
2402 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2404 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2409 // Emit visible names into a debug str section.
2410 void DwarfDebug::emitDebugStr() {
2411 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2412 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2415 // Emit locations into the debug loc section.
2416 void DwarfDebug::emitDebugLoc() {
2417 if (DotDebugLocEntries.empty())
2420 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2421 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2423 DotDebugLocEntry &Entry = *I;
2424 if (I + 1 != DotDebugLocEntries.end())
2428 // Start the dwarf loc section.
2429 Asm->OutStreamer.SwitchSection(
2430 Asm->getObjFileLowering().getDwarfLocSection());
2431 unsigned char Size = Asm->getDataLayout().getPointerSize();
2432 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2434 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2435 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2436 I != E; ++I, ++index) {
2437 DotDebugLocEntry &Entry = *I;
2438 if (Entry.isMerged()) continue;
2439 if (Entry.isEmpty()) {
2440 Asm->OutStreamer.EmitIntValue(0, Size);
2441 Asm->OutStreamer.EmitIntValue(0, Size);
2442 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2444 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size);
2445 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size);
2446 DIVariable DV(Entry.Variable);
2447 Asm->OutStreamer.AddComment("Loc expr size");
2448 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2449 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2450 Asm->EmitLabelDifference(end, begin, 2);
2451 Asm->OutStreamer.EmitLabel(begin);
2452 if (Entry.isInt()) {
2453 DIBasicType BTy(DV.getType());
2455 (BTy.getEncoding() == dwarf::DW_ATE_signed
2456 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2457 Asm->OutStreamer.AddComment("DW_OP_consts");
2458 Asm->EmitInt8(dwarf::DW_OP_consts);
2459 Asm->EmitSLEB128(Entry.getInt());
2461 Asm->OutStreamer.AddComment("DW_OP_constu");
2462 Asm->EmitInt8(dwarf::DW_OP_constu);
2463 Asm->EmitULEB128(Entry.getInt());
2465 } else if (Entry.isLocation()) {
2466 if (!DV.hasComplexAddress())
2468 Asm->EmitDwarfRegOp(Entry.Loc, DV.isIndirect());
2470 // Complex address entry.
2471 unsigned N = DV.getNumAddrElements();
2473 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2474 if (Entry.Loc.getOffset()) {
2476 Asm->EmitDwarfRegOp(Entry.Loc, DV.isIndirect());
2477 Asm->OutStreamer.AddComment("DW_OP_deref");
2478 Asm->EmitInt8(dwarf::DW_OP_deref);
2479 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2480 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2481 Asm->EmitSLEB128(DV.getAddrElement(1));
2483 // If first address element is OpPlus then emit
2484 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2485 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2486 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2490 Asm->EmitDwarfRegOp(Entry.Loc, DV.isIndirect());
2493 // Emit remaining complex address elements.
2494 for (; i < N; ++i) {
2495 uint64_t Element = DV.getAddrElement(i);
2496 if (Element == DIBuilder::OpPlus) {
2497 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2498 Asm->EmitULEB128(DV.getAddrElement(++i));
2499 } else if (Element == DIBuilder::OpDeref) {
2500 if (!Entry.Loc.isReg())
2501 Asm->EmitInt8(dwarf::DW_OP_deref);
2503 llvm_unreachable("unknown Opcode found in complex address");
2507 // else ... ignore constant fp. There is not any good way to
2508 // to represent them here in dwarf.
2509 Asm->OutStreamer.EmitLabel(end);
2514 // Emit visible names into a debug aranges section.
2515 void DwarfDebug::emitDebugARanges() {
2516 // Start the dwarf aranges section.
2517 Asm->OutStreamer.SwitchSection(
2518 Asm->getObjFileLowering().getDwarfARangesSection());
2521 // Emit visible names into a debug ranges section.
2522 void DwarfDebug::emitDebugRanges() {
2523 // Start the dwarf ranges section.
2524 Asm->OutStreamer.SwitchSection(
2525 Asm->getObjFileLowering().getDwarfRangesSection());
2526 unsigned char Size = Asm->getDataLayout().getPointerSize();
2527 for (SmallVectorImpl<const MCSymbol *>::iterator
2528 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2531 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size);
2533 Asm->OutStreamer.EmitIntValue(0, Size);
2537 // Emit visible names into a debug macinfo section.
2538 void DwarfDebug::emitDebugMacInfo() {
2539 if (const MCSection *LineInfo =
2540 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2541 // Start the dwarf macinfo section.
2542 Asm->OutStreamer.SwitchSection(LineInfo);
2546 // Emit inline info using following format.
2548 // 1. length of section
2549 // 2. Dwarf version number
2552 // Entries (one "entry" for each function that was inlined):
2554 // 1. offset into __debug_str section for MIPS linkage name, if exists;
2555 // otherwise offset into __debug_str for regular function name.
2556 // 2. offset into __debug_str section for regular function name.
2557 // 3. an unsigned LEB128 number indicating the number of distinct inlining
2558 // instances for the function.
2560 // The rest of the entry consists of a {die_offset, low_pc} pair for each
2561 // inlined instance; the die_offset points to the inlined_subroutine die in the
2562 // __debug_info section, and the low_pc is the starting address for the
2563 // inlining instance.
2564 void DwarfDebug::emitDebugInlineInfo() {
2565 if (!Asm->MAI->doesDwarfUseInlineInfoSection())
2571 Asm->OutStreamer.SwitchSection(
2572 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2574 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2575 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2576 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2578 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2580 Asm->OutStreamer.AddComment("Dwarf Version");
2581 Asm->EmitInt16(DwarfVersion);
2582 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2583 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2585 for (SmallVectorImpl<const MDNode *>::iterator I = InlinedSPNodes.begin(),
2586 E = InlinedSPNodes.end(); I != E; ++I) {
2588 const MDNode *Node = *I;
2589 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2590 = InlineInfo.find(Node);
2591 SmallVectorImpl<InlineInfoLabels> &Labels = II->second;
2592 DISubprogram SP(Node);
2593 StringRef LName = SP.getLinkageName();
2594 StringRef Name = SP.getName();
2596 Asm->OutStreamer.AddComment("MIPS linkage name");
2598 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2599 DwarfStrSectionSym);
2601 Asm->EmitSectionOffset(
2602 InfoHolder.getStringPoolEntry(Function::getRealLinkageName(LName)),
2603 DwarfStrSectionSym);
2605 Asm->OutStreamer.AddComment("Function name");
2606 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2607 DwarfStrSectionSym);
2608 Asm->EmitULEB128(Labels.size(), "Inline count");
2610 for (SmallVectorImpl<InlineInfoLabels>::iterator LI = Labels.begin(),
2611 LE = Labels.end(); LI != LE; ++LI) {
2612 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2613 Asm->EmitInt32(LI->second->getOffset());
2615 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2616 Asm->OutStreamer.EmitSymbolValue(LI->first,
2617 Asm->getDataLayout().getPointerSize());
2621 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2624 // DWARF5 Experimental Separate Dwarf emitters.
2626 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2627 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2628 // DW_AT_ranges_base, DW_AT_addr_base. If DW_AT_ranges is present,
2629 // DW_AT_low_pc and DW_AT_high_pc are not used, and vice versa.
2630 CompileUnit *DwarfDebug::constructSkeletonCU(const MDNode *N) {
2631 DICompileUnit DIUnit(N);
2632 CompilationDir = DIUnit.getDirectory();
2634 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2635 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
2636 DIUnit.getLanguage(), Die, N, Asm,
2637 this, &SkeletonHolder);
2639 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2640 DIUnit.getSplitDebugFilename());
2642 // This should be a unique identifier when we want to build .dwp files.
2643 NewCU->addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8, 0);
2645 // Relocate to the beginning of the addr_base section, else 0 for the
2646 // beginning of the one for this compile unit.
2647 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2648 NewCU->addLabel(Die, dwarf::DW_AT_GNU_addr_base, dwarf::DW_FORM_sec_offset,
2649 DwarfAddrSectionSym);
2651 NewCU->addUInt(Die, dwarf::DW_AT_GNU_addr_base,
2652 dwarf::DW_FORM_sec_offset, 0);
2654 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2655 // into an entity. We're using 0, or a NULL label for this.
2656 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2658 // DW_AT_stmt_list is a offset of line number information for this
2659 // compile unit in debug_line section.
2660 // FIXME: Should handle multiple compile units.
2661 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2662 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
2663 DwarfLineSectionSym);
2665 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset, 0);
2667 if (!CompilationDir.empty())
2668 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2670 SkeletonHolder.addUnit(NewCU);
2671 SkeletonCUs.push_back(NewCU);
2676 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
2677 assert(useSplitDwarf() && "No split dwarf debug info?");
2678 emitAbbrevs(Section, &SkeletonAbbrevs);
2681 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2682 // compile units that would normally be in debug_info.
2683 void DwarfDebug::emitDebugInfoDWO() {
2684 assert(useSplitDwarf() && "No split dwarf debug info?");
2685 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
2686 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2687 DwarfAbbrevDWOSectionSym);
2690 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2691 // abbreviations for the .debug_info.dwo section.
2692 void DwarfDebug::emitDebugAbbrevDWO() {
2693 assert(useSplitDwarf() && "No split dwarf?");
2694 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2698 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2699 // string section and is identical in format to traditional .debug_str
2701 void DwarfDebug::emitDebugStrDWO() {
2702 assert(useSplitDwarf() && "No split dwarf?");
2703 const MCSection *OffSec = Asm->getObjFileLowering()
2704 .getDwarfStrOffDWOSection();
2705 const MCSymbol *StrSym = DwarfStrSectionSym;
2706 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),