1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf debug info into asm files.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "dwarfdebug"
15 #include "DwarfDebug.h"
18 #include "DwarfAccelTable.h"
19 #include "DwarfCompileUnit.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/DIBuilder.h"
27 #include "llvm/DebugInfo.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCSection.h"
34 #include "llvm/MC/MCStreamer.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Dwarf.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include "llvm/Support/MD5.h"
42 #include "llvm/Support/Path.h"
43 #include "llvm/Support/Timer.h"
44 #include "llvm/Support/ValueHandle.h"
45 #include "llvm/Target/TargetFrameLowering.h"
46 #include "llvm/Target/TargetLoweringObjectFile.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Target/TargetRegisterInfo.h"
53 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
54 cl::desc("Disable debug info printing"));
56 static cl::opt<bool> UnknownLocations(
57 "use-unknown-locations", cl::Hidden,
58 cl::desc("Make an absence of debug location information explicit."),
62 GenerateODRHash("generate-odr-hash", cl::Hidden,
63 cl::desc("Add an ODR hash to external type DIEs."),
67 GenerateCUHash("generate-cu-hash", cl::Hidden,
68 cl::desc("Add the CU hash as the dwo_id."),
79 static cl::opt<DefaultOnOff>
80 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
81 cl::desc("Output prototype dwarf accelerator tables."),
82 cl::values(clEnumVal(Default, "Default for platform"),
83 clEnumVal(Enable, "Enabled"),
84 clEnumVal(Disable, "Disabled"), clEnumValEnd),
87 static cl::opt<DefaultOnOff>
88 DarwinGDBCompat("darwin-gdb-compat", cl::Hidden,
89 cl::desc("Compatibility with Darwin gdb."),
90 cl::values(clEnumVal(Default, "Default for platform"),
91 clEnumVal(Enable, "Enabled"),
92 clEnumVal(Disable, "Disabled"), clEnumValEnd),
95 static cl::opt<DefaultOnOff>
96 SplitDwarf("split-dwarf", cl::Hidden,
97 cl::desc("Output prototype dwarf split debug info."),
98 cl::values(clEnumVal(Default, "Default for platform"),
99 clEnumVal(Enable, "Enabled"),
100 clEnumVal(Disable, "Disabled"), clEnumValEnd),
103 static cl::opt<DefaultOnOff>
104 DwarfPubNames("generate-dwarf-pubnames", cl::Hidden,
105 cl::desc("Generate DWARF pubnames section"),
106 cl::values(clEnumVal(Default, "Default for platform"),
107 clEnumVal(Enable, "Enabled"),
108 clEnumVal(Disable, "Disabled"), clEnumValEnd),
112 const char *const DWARFGroupName = "DWARF Emission";
113 const char *const DbgTimerName = "DWARF Debug Writer";
115 struct CompareFirst {
116 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
117 return lhs.first < rhs.first;
120 } // end anonymous namespace
122 //===----------------------------------------------------------------------===//
124 // Configuration values for initial hash set sizes (log2).
126 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
130 DIType DbgVariable::getType() const {
131 DIType Ty = Var.getType();
132 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
133 // addresses instead.
134 if (Var.isBlockByrefVariable()) {
135 /* Byref variables, in Blocks, are declared by the programmer as
136 "SomeType VarName;", but the compiler creates a
137 __Block_byref_x_VarName struct, and gives the variable VarName
138 either the struct, or a pointer to the struct, as its type. This
139 is necessary for various behind-the-scenes things the compiler
140 needs to do with by-reference variables in blocks.
142 However, as far as the original *programmer* is concerned, the
143 variable should still have type 'SomeType', as originally declared.
145 The following function dives into the __Block_byref_x_VarName
146 struct to find the original type of the variable. This will be
147 passed back to the code generating the type for the Debug
148 Information Entry for the variable 'VarName'. 'VarName' will then
149 have the original type 'SomeType' in its debug information.
151 The original type 'SomeType' will be the type of the field named
152 'VarName' inside the __Block_byref_x_VarName struct.
154 NOTE: In order for this to not completely fail on the debugger
155 side, the Debug Information Entry for the variable VarName needs to
156 have a DW_AT_location that tells the debugger how to unwind through
157 the pointers and __Block_byref_x_VarName struct to find the actual
158 value of the variable. The function addBlockByrefType does this. */
160 uint16_t tag = Ty.getTag();
162 if (tag == dwarf::DW_TAG_pointer_type) {
163 DIDerivedType DTy = DIDerivedType(Ty);
164 subType = DTy.getTypeDerivedFrom();
167 DICompositeType blockStruct = DICompositeType(subType);
168 DIArray Elements = blockStruct.getTypeArray();
170 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
171 DIDescriptor Element = Elements.getElement(i);
172 DIDerivedType DT = DIDerivedType(Element);
173 if (getName() == DT.getName())
174 return (DT.getTypeDerivedFrom());
180 } // end llvm namespace
182 /// Return Dwarf Version by checking module flags.
183 static unsigned getDwarfVersionFromModule(const Module *M) {
184 Value *Val = M->getModuleFlag("Dwarf Version");
186 return dwarf::DWARF_VERSION;
187 return cast<ConstantInt>(Val)->getZExtValue();
190 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
191 : Asm(A), MMI(Asm->MMI), FirstCU(0),
192 AbbreviationsSet(InitAbbreviationsSetSize),
193 SourceIdMap(DIEValueAllocator),
194 PrevLabel(NULL), GlobalCUIndexCount(0),
195 InfoHolder(A, &AbbreviationsSet, &Abbreviations, "info_string",
197 SkeletonAbbrevSet(InitAbbreviationsSetSize),
198 SkeletonHolder(A, &SkeletonAbbrevSet, &SkeletonAbbrevs, "skel_string",
201 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
202 DwarfStrSectionSym = TextSectionSym = 0;
203 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
204 DwarfAddrSectionSym = 0;
205 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
206 FunctionBeginSym = FunctionEndSym = 0;
208 // Turn on accelerator tables and older gdb compatibility
209 // for Darwin by default, pubnames by default for non-Darwin,
210 // and handle split dwarf.
211 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
213 if (DarwinGDBCompat == Default)
214 IsDarwinGDBCompat = IsDarwin;
216 IsDarwinGDBCompat = DarwinGDBCompat == Enable;
218 if (DwarfAccelTables == Default)
219 HasDwarfAccelTables = IsDarwin;
221 HasDwarfAccelTables = DwarfAccelTables = Enable;
223 if (SplitDwarf == Default)
224 HasSplitDwarf = false;
226 HasSplitDwarf = SplitDwarf == Enable;
228 if (DwarfPubNames == Default)
229 HasDwarfPubNames = !IsDarwin;
231 HasDwarfPubNames = DwarfPubNames == Enable;
233 DwarfVersion = getDwarfVersionFromModule(MMI->getModule());
236 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
240 DwarfDebug::~DwarfDebug() {
243 // Switch to the specified MCSection and emit an assembler
244 // temporary label to it if SymbolStem is specified.
245 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
246 const char *SymbolStem = 0) {
247 Asm->OutStreamer.SwitchSection(Section);
248 if (!SymbolStem) return 0;
250 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
251 Asm->OutStreamer.EmitLabel(TmpSym);
255 MCSymbol *DwarfUnits::getStringPoolSym() {
256 return Asm->GetTempSymbol(StringPref);
259 MCSymbol *DwarfUnits::getStringPoolEntry(StringRef Str) {
260 std::pair<MCSymbol*, unsigned> &Entry =
261 StringPool.GetOrCreateValue(Str).getValue();
262 if (Entry.first) return Entry.first;
264 Entry.second = NextStringPoolNumber++;
265 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
268 unsigned DwarfUnits::getStringPoolIndex(StringRef Str) {
269 std::pair<MCSymbol*, unsigned> &Entry =
270 StringPool.GetOrCreateValue(Str).getValue();
271 if (Entry.first) return Entry.second;
273 Entry.second = NextStringPoolNumber++;
274 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
278 unsigned DwarfUnits::getAddrPoolIndex(const MCSymbol *Sym) {
279 return getAddrPoolIndex(MCSymbolRefExpr::Create(Sym, Asm->OutContext));
282 unsigned DwarfUnits::getAddrPoolIndex(const MCExpr *Sym) {
283 std::pair<DenseMap<const MCExpr *, unsigned>::iterator, bool> P =
284 AddressPool.insert(std::make_pair(Sym, NextAddrPoolNumber));
286 ++NextAddrPoolNumber;
287 return P.first->second;
290 // Define a unique number for the abbreviation.
292 void DwarfUnits::assignAbbrevNumber(DIEAbbrev &Abbrev) {
293 // Check the set for priors.
294 DIEAbbrev *InSet = AbbreviationsSet->GetOrInsertNode(&Abbrev);
296 // If it's newly added.
297 if (InSet == &Abbrev) {
298 // Add to abbreviation list.
299 Abbreviations->push_back(&Abbrev);
301 // Assign the vector position + 1 as its number.
302 Abbrev.setNumber(Abbreviations->size());
304 // Assign existing abbreviation number.
305 Abbrev.setNumber(InSet->getNumber());
309 static bool isObjCClass(StringRef Name) {
310 return Name.startswith("+") || Name.startswith("-");
313 static bool hasObjCCategory(StringRef Name) {
314 if (!isObjCClass(Name)) return false;
316 size_t pos = Name.find(')');
317 if (pos != std::string::npos) {
318 if (Name[pos+1] != ' ') return false;
324 static void getObjCClassCategory(StringRef In, StringRef &Class,
325 StringRef &Category) {
326 if (!hasObjCCategory(In)) {
327 Class = In.slice(In.find('[') + 1, In.find(' '));
332 Class = In.slice(In.find('[') + 1, In.find('('));
333 Category = In.slice(In.find('[') + 1, In.find(' '));
337 static StringRef getObjCMethodName(StringRef In) {
338 return In.slice(In.find(' ') + 1, In.find(']'));
341 // Add the various names to the Dwarf accelerator table names.
342 static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
344 if (!SP.isDefinition()) return;
346 TheCU->addAccelName(SP.getName(), Die);
348 // If the linkage name is different than the name, go ahead and output
349 // that as well into the name table.
350 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
351 TheCU->addAccelName(SP.getLinkageName(), Die);
353 // If this is an Objective-C selector name add it to the ObjC accelerator
355 if (isObjCClass(SP.getName())) {
356 StringRef Class, Category;
357 getObjCClassCategory(SP.getName(), Class, Category);
358 TheCU->addAccelObjC(Class, Die);
360 TheCU->addAccelObjC(Category, Die);
361 // Also add the base method name to the name table.
362 TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
366 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
367 // and DW_AT_high_pc attributes. If there are global variables in this
368 // scope then create and insert DIEs for these variables.
369 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
370 const MDNode *SPNode) {
371 DIE *SPDie = SPCU->getDIE(SPNode);
373 assert(SPDie && "Unable to find subprogram DIE!");
374 DISubprogram SP(SPNode);
376 // If we're updating an abstract DIE, then we will be adding the children and
377 // object pointer later on. But what we don't want to do is process the
378 // concrete DIE twice.
379 DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode);
381 bool InSameCU = (AbsSPDIE->getCompileUnit() == SPCU->getCUDie());
382 // Pick up abstract subprogram DIE.
383 SPDie = new DIE(dwarf::DW_TAG_subprogram);
384 // If AbsSPDIE belongs to a different CU, use DW_FORM_ref_addr instead of
386 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
387 InSameCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
391 DISubprogram SPDecl = SP.getFunctionDeclaration();
392 if (!SPDecl.isSubprogram()) {
393 // There is not any need to generate specification DIE for a function
394 // defined at compile unit level. If a function is defined inside another
395 // function then gdb prefers the definition at top level and but does not
396 // expect specification DIE in parent function. So avoid creating
397 // specification DIE for a function defined inside a function.
398 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
399 !SP.getContext().isFile() &&
400 !isSubprogramContext(SP.getContext())) {
401 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
404 DICompositeType SPTy = SP.getType();
405 DIArray Args = SPTy.getTypeArray();
406 uint16_t SPTag = SPTy.getTag();
407 if (SPTag == dwarf::DW_TAG_subroutine_type)
408 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
409 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
410 DIType ATy = DIType(Args.getElement(i));
411 SPCU->addType(Arg, ATy);
412 if (ATy.isArtificial())
413 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
414 if (ATy.isObjectPointer())
415 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer,
416 dwarf::DW_FORM_ref4, Arg);
417 SPDie->addChild(Arg);
419 DIE *SPDeclDie = SPDie;
420 SPDie = new DIE(dwarf::DW_TAG_subprogram);
421 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification,
422 dwarf::DW_FORM_ref4, SPDeclDie);
428 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc,
429 Asm->GetTempSymbol("func_begin",
430 Asm->getFunctionNumber()));
431 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc,
432 Asm->GetTempSymbol("func_end",
433 Asm->getFunctionNumber()));
434 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
435 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
436 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
438 // Add name to the name table, we do this here because we're guaranteed
439 // to have concrete versions of our DW_TAG_subprogram nodes.
440 addSubprogramNames(SPCU, SP, SPDie);
445 // Construct new DW_TAG_lexical_block for this scope and attach
446 // DW_AT_low_pc/DW_AT_high_pc labels.
447 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
448 LexicalScope *Scope) {
449 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
450 if (Scope->isAbstractScope())
453 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
457 // If we have multiple ranges, emit them into the range section.
458 if (Ranges.size() > 1) {
459 // .debug_range section has not been laid out yet. Emit offset in
460 // .debug_range as a uint, size 4, for now. emitDIE will handle
461 // DW_AT_ranges appropriately.
462 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
463 DebugRangeSymbols.size()
464 * Asm->getDataLayout().getPointerSize());
465 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
466 RE = Ranges.end(); RI != RE; ++RI) {
467 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
468 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
471 // Terminate the range list.
472 DebugRangeSymbols.push_back(NULL);
473 DebugRangeSymbols.push_back(NULL);
477 // Construct the address range for this DIE.
478 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
479 MCSymbol *Start = getLabelBeforeInsn(RI->first);
480 MCSymbol *End = getLabelAfterInsn(RI->second);
482 if (End == 0) return 0;
484 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
485 assert(End->isDefined() && "Invalid end label for an inlined scope!");
487 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
488 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
493 // This scope represents inlined body of a function. Construct DIE to
494 // represent this concrete inlined copy of the function.
495 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
496 LexicalScope *Scope) {
497 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
498 assert(Ranges.empty() == false &&
499 "LexicalScope does not have instruction markers!");
501 if (!Scope->getScopeNode())
503 DIScope DS(Scope->getScopeNode());
504 DISubprogram InlinedSP = getDISubprogram(DS);
505 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
507 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
511 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
512 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
513 dwarf::DW_FORM_ref4, OriginDIE);
515 if (Ranges.size() > 1) {
516 // .debug_range section has not been laid out yet. Emit offset in
517 // .debug_range as a uint, size 4, for now. emitDIE will handle
518 // DW_AT_ranges appropriately.
519 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
520 DebugRangeSymbols.size()
521 * Asm->getDataLayout().getPointerSize());
522 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
523 RE = Ranges.end(); RI != RE; ++RI) {
524 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
525 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
527 DebugRangeSymbols.push_back(NULL);
528 DebugRangeSymbols.push_back(NULL);
530 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
531 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
532 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
534 if (StartLabel == 0 || EndLabel == 0)
535 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
537 assert(StartLabel->isDefined() &&
538 "Invalid starting label for an inlined scope!");
539 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
541 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
542 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
545 InlinedSubprogramDIEs.insert(OriginDIE);
547 // Add the call site information to the DIE.
548 DILocation DL(Scope->getInlinedAt());
549 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
550 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
551 TheCU->getUniqueID()));
552 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
554 // Track the start label for this inlined function.
555 //.debug_inlined section specification does not clearly state how
556 // to emit inlined scopes that are split into multiple instruction ranges.
557 // For now, use the first instruction range and emit low_pc/high_pc pair and
558 // corresponding the .debug_inlined section entry for this pair.
559 if (Asm->MAI->doesDwarfUseInlineInfoSection()) {
560 MCSymbol *StartLabel = getLabelBeforeInsn(Ranges.begin()->first);
561 InlineInfoMap::iterator I = InlineInfo.find(InlinedSP);
563 if (I == InlineInfo.end()) {
564 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
565 InlinedSPNodes.push_back(InlinedSP);
567 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
570 // Add name to the name table, we do this here because we're guaranteed
571 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
572 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
577 // Construct a DIE for this scope.
578 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
579 if (!Scope || !Scope->getScopeNode())
582 DIScope DS(Scope->getScopeNode());
583 // Early return to avoid creating dangling variable|scope DIEs.
584 if (!Scope->getInlinedAt() && DS.isSubprogram() && Scope->isAbstractScope() &&
588 SmallVector<DIE *, 8> Children;
589 DIE *ObjectPointer = NULL;
591 // Collect arguments for current function.
592 if (LScopes.isCurrentFunctionScope(Scope))
593 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
594 if (DbgVariable *ArgDV = CurrentFnArguments[i])
596 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope())) {
597 Children.push_back(Arg);
598 if (ArgDV->isObjectPointer()) ObjectPointer = Arg;
601 // Collect lexical scope children first.
602 const SmallVectorImpl<DbgVariable *> &Variables =ScopeVariables.lookup(Scope);
603 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
605 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope())) {
606 Children.push_back(Variable);
607 if (Variables[i]->isObjectPointer()) ObjectPointer = Variable;
609 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
610 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
611 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
612 Children.push_back(Nested);
613 DIE *ScopeDIE = NULL;
614 if (Scope->getInlinedAt())
615 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
616 else if (DS.isSubprogram()) {
617 ProcessedSPNodes.insert(DS);
618 if (Scope->isAbstractScope()) {
619 ScopeDIE = TheCU->getDIE(DS);
620 // Note down abstract DIE.
622 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
625 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
628 // There is no need to emit empty lexical block DIE.
629 std::pair<ImportedEntityMap::const_iterator,
630 ImportedEntityMap::const_iterator> Range = std::equal_range(
631 ScopesWithImportedEntities.begin(), ScopesWithImportedEntities.end(),
632 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode*)0),
634 if (Children.empty() && Range.first == Range.second)
636 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
637 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
639 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
642 if (!ScopeDIE) return NULL;
645 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
646 E = Children.end(); I != E; ++I)
647 ScopeDIE->addChild(*I);
649 if (DS.isSubprogram() && ObjectPointer != NULL)
650 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer,
651 dwarf::DW_FORM_ref4, ObjectPointer);
653 if (DS.isSubprogram())
654 TheCU->addPubTypes(DISubprogram(DS));
659 // Look up the source id with the given directory and source file names.
660 // If none currently exists, create a new id and insert it in the
661 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
663 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName,
664 StringRef DirName, unsigned CUID) {
665 // If we use .loc in assembly, we can't separate .file entries according to
666 // compile units. Thus all files will belong to the default compile unit.
667 if (Asm->TM.hasMCUseLoc() &&
668 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer)
671 // If FE did not provide a file name, then assume stdin.
672 if (FileName.empty())
673 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
675 // TODO: this might not belong here. See if we can factor this better.
676 if (DirName == CompilationDir)
679 // FileIDCUMap stores the current ID for the given compile unit.
680 unsigned SrcId = FileIDCUMap[CUID] + 1;
682 // We look up the CUID/file/dir by concatenating them with a zero byte.
683 SmallString<128> NamePair;
684 NamePair += utostr(CUID);
687 NamePair += '\0'; // Zero bytes are not allowed in paths.
688 NamePair += FileName;
690 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
691 if (Ent.getValue() != SrcId)
692 return Ent.getValue();
694 FileIDCUMap[CUID] = SrcId;
695 // Print out a .file directive to specify files for .loc directives.
696 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
701 // Create new CompileUnit for the given metadata node with tag
702 // DW_TAG_compile_unit.
703 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
704 DICompileUnit DIUnit(N);
705 StringRef FN = DIUnit.getFilename();
706 CompilationDir = DIUnit.getDirectory();
708 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
709 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
710 DIUnit.getLanguage(), Die, N, Asm,
713 FileIDCUMap[NewCU->getUniqueID()] = 0;
714 // Call this to emit a .file directive if it wasn't emitted for the source
715 // file this CU comes from yet.
716 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
718 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
719 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
720 DIUnit.getLanguage());
721 NewCU->addString(Die, dwarf::DW_AT_name, FN);
723 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
724 // into an entity. We're using 0 (or a NULL label) for this. For
725 // split dwarf it's in the skeleton CU so omit it here.
726 if (!useSplitDwarf())
727 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
729 // Define start line table label for each Compile Unit.
730 MCSymbol *LineTableStartSym = Asm->GetTempSymbol("line_table_start",
731 NewCU->getUniqueID());
732 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
733 NewCU->getUniqueID());
735 // Use a single line table if we are using .loc and generating assembly.
737 (Asm->TM.hasMCUseLoc() &&
738 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer) ||
739 (NewCU->getUniqueID() == 0);
741 // DW_AT_stmt_list is a offset of line number information for this
742 // compile unit in debug_line section. For split dwarf this is
743 // left in the skeleton CU and so not included.
744 // The line table entries are not always emitted in assembly, so it
745 // is not okay to use line_table_start here.
746 if (!useSplitDwarf()) {
747 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
748 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
750 Asm->GetTempSymbol("section_line") : LineTableStartSym);
751 else if (UseTheFirstCU)
752 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
754 NewCU->addDelta(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
755 LineTableStartSym, DwarfLineSectionSym);
758 // If we're using split dwarf the compilation dir is going to be in the
759 // skeleton CU and so we don't need to duplicate it here.
760 if (!useSplitDwarf() && !CompilationDir.empty())
761 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
762 if (DIUnit.isOptimized())
763 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
765 StringRef Flags = DIUnit.getFlags();
767 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
769 if (unsigned RVer = DIUnit.getRunTimeVersion())
770 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
771 dwarf::DW_FORM_data1, RVer);
776 InfoHolder.addUnit(NewCU);
778 CUMap.insert(std::make_pair(N, NewCU));
782 // Construct subprogram DIE.
783 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
785 CompileUnit *&CURef = SPMap[N];
791 if (!SP.isDefinition())
792 // This is a method declaration which will be handled while constructing
796 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
799 TheCU->insertDIE(N, SubprogramDie);
801 // Add to context owner.
802 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
804 // Expose as global, if requested.
805 if (HasDwarfPubNames)
806 TheCU->addGlobalName(SP.getName(), SubprogramDie);
809 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
811 DIImportedEntity Module(N);
812 if (!Module.Verify())
814 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
815 constructImportedEntityDIE(TheCU, Module, D);
818 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU, const MDNode *N,
820 DIImportedEntity Module(N);
821 if (!Module.Verify())
823 return constructImportedEntityDIE(TheCU, Module, Context);
826 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
827 const DIImportedEntity &Module,
829 assert(Module.Verify() &&
830 "Use one of the MDNode * overloads to handle invalid metadata");
831 assert(Context && "Should always have a context for an imported_module");
832 DIE *IMDie = new DIE(Module.getTag());
833 TheCU->insertDIE(Module, IMDie);
835 DIDescriptor Entity = Module.getEntity();
836 if (Entity.isNameSpace())
837 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
838 else if (Entity.isSubprogram())
839 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
840 else if (Entity.isType())
841 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
843 EntityDie = TheCU->getDIE(Entity);
844 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
845 Module.getContext().getDirectory(),
846 TheCU->getUniqueID());
847 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, 0, FileID);
848 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, 0, Module.getLineNumber());
849 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, dwarf::DW_FORM_ref4,
851 StringRef Name = Module.getName();
853 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
854 Context->addChild(IMDie);
857 // Emit all Dwarf sections that should come prior to the content. Create
858 // global DIEs and emit initial debug info sections. This is invoked by
859 // the target AsmPrinter.
860 void DwarfDebug::beginModule() {
861 if (DisableDebugInfoPrinting)
864 const Module *M = MMI->getModule();
866 // If module has named metadata anchors then use them, otherwise scan the
867 // module using debug info finder to collect debug info.
868 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
872 // Emit initial sections so we can reference labels later.
875 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
876 DICompileUnit CUNode(CU_Nodes->getOperand(i));
877 CompileUnit *CU = constructCompileUnit(CUNode);
878 DIArray ImportedEntities = CUNode.getImportedEntities();
879 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
880 ScopesWithImportedEntities.push_back(std::make_pair(
881 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
882 ImportedEntities.getElement(i)));
883 std::sort(ScopesWithImportedEntities.begin(),
884 ScopesWithImportedEntities.end(), CompareFirst());
885 DIArray GVs = CUNode.getGlobalVariables();
886 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
887 CU->createGlobalVariableDIE(GVs.getElement(i));
888 DIArray SPs = CUNode.getSubprograms();
889 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
890 constructSubprogramDIE(CU, SPs.getElement(i));
891 DIArray EnumTypes = CUNode.getEnumTypes();
892 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
893 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
894 DIArray RetainedTypes = CUNode.getRetainedTypes();
895 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
896 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
897 // Emit imported_modules last so that the relevant context is already
899 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
900 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
903 // Tell MMI that we have debug info.
904 MMI->setDebugInfoAvailability(true);
906 // Prime section data.
907 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
910 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
911 void DwarfDebug::computeInlinedDIEs() {
912 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
913 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
914 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
916 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
918 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
919 AE = AbstractSPDies.end(); AI != AE; ++AI) {
920 DIE *ISP = AI->second;
921 if (InlinedSubprogramDIEs.count(ISP))
923 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
927 // Collect info for variables that were optimized out.
928 void DwarfDebug::collectDeadVariables() {
929 const Module *M = MMI->getModule();
930 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
932 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
933 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
934 DICompileUnit TheCU(CU_Nodes->getOperand(i));
935 DIArray Subprograms = TheCU.getSubprograms();
936 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
937 DISubprogram SP(Subprograms.getElement(i));
938 if (ProcessedSPNodes.count(SP) != 0) continue;
939 if (!SP.isSubprogram()) continue;
940 if (!SP.isDefinition()) continue;
941 DIArray Variables = SP.getVariables();
942 if (Variables.getNumElements() == 0) continue;
944 LexicalScope *Scope =
945 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
946 DeadFnScopeMap[SP] = Scope;
948 // Construct subprogram DIE and add variables DIEs.
949 CompileUnit *SPCU = CUMap.lookup(TheCU);
950 assert(SPCU && "Unable to find Compile Unit!");
951 constructSubprogramDIE(SPCU, SP);
952 DIE *ScopeDIE = SPCU->getDIE(SP);
953 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
954 DIVariable DV(Variables.getElement(vi));
955 if (!DV.isVariable()) continue;
956 DbgVariable NewVar(DV, NULL);
957 if (DIE *VariableDIE =
958 SPCU->constructVariableDIE(&NewVar, Scope->isAbstractScope()))
959 ScopeDIE->addChild(VariableDIE);
964 DeleteContainerSeconds(DeadFnScopeMap);
967 // Type Signature [7.27] and ODR Hash code.
969 /// \brief Grabs the string in whichever attribute is passed in and returns
970 /// a reference to it. Returns "" if the attribute doesn't exist.
971 static StringRef getDIEStringAttr(DIE *Die, unsigned Attr) {
972 DIEValue *V = Die->findAttribute(Attr);
974 if (DIEString *S = dyn_cast_or_null<DIEString>(V))
975 return S->getString();
977 return StringRef("");
980 /// Return true if the current DIE is contained within an anonymous namespace.
981 static bool isContainedInAnonNamespace(DIE *Die) {
982 DIE *Parent = Die->getParent();
985 if (Parent->getTag() == dwarf::DW_TAG_namespace &&
986 getDIEStringAttr(Parent, dwarf::DW_AT_name) == "")
988 Parent = Parent->getParent();
994 /// Test if the current CU language is C++ and that we have
995 /// a named type that is not contained in an anonymous namespace.
996 static bool shouldAddODRHash(CompileUnit *CU, DIE *Die) {
997 return CU->getLanguage() == dwarf::DW_LANG_C_plus_plus &&
998 getDIEStringAttr(Die, dwarf::DW_AT_name) != "" &&
999 !isContainedInAnonNamespace(Die);
1002 void DwarfDebug::finalizeModuleInfo() {
1003 // Collect info for variables that were optimized out.
1004 collectDeadVariables();
1006 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1007 computeInlinedDIEs();
1009 // Split out type units and conditionally add an ODR tag to the split
1011 // FIXME: Do type splitting.
1012 for (unsigned i = 0, e = TypeUnits.size(); i != e; ++i) {
1013 DIE *Die = TypeUnits[i];
1015 // If we've requested ODR hashes and it's applicable for an ODR hash then
1016 // add the ODR signature now.
1017 // FIXME: This should be added onto the type unit, not the type, but this
1018 // works as an intermediate stage.
1019 if (GenerateODRHash && shouldAddODRHash(CUMap.begin()->second, Die))
1020 CUMap.begin()->second->addUInt(Die, dwarf::DW_AT_GNU_odr_signature,
1021 dwarf::DW_FORM_data8,
1022 Hash.computeDIEODRSignature(Die));
1025 // Handle anything that needs to be done on a per-cu basis.
1026 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
1028 CUI != CUE; ++CUI) {
1029 CompileUnit *TheCU = CUI->second;
1030 // Emit DW_AT_containing_type attribute to connect types with their
1031 // vtable holding type.
1032 TheCU->constructContainingTypeDIEs();
1034 // If we're splitting the dwarf out now that we've got the entire
1035 // CU then construct a skeleton CU based upon it.
1036 if (useSplitDwarf()) {
1038 if (GenerateCUHash) {
1040 ID = CUHash.computeCUSignature(TheCU->getCUDie());
1042 // This should be a unique identifier when we want to build .dwp files.
1043 TheCU->addUInt(TheCU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
1044 dwarf::DW_FORM_data8, ID);
1045 // Now construct the skeleton CU associated.
1046 CompileUnit *SkCU = constructSkeletonCU(CUI->first);
1047 // This should be a unique identifier when we want to build .dwp files.
1048 SkCU->addUInt(SkCU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
1049 dwarf::DW_FORM_data8, ID);
1053 // Compute DIE offsets and sizes.
1054 InfoHolder.computeSizeAndOffsets();
1055 if (useSplitDwarf())
1056 SkeletonHolder.computeSizeAndOffsets();
1059 void DwarfDebug::endSections() {
1060 // Standard sections final addresses.
1061 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1062 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
1063 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1064 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
1066 // End text sections.
1067 for (unsigned I = 0, E = SectionMap.size(); I != E; ++I) {
1068 Asm->OutStreamer.SwitchSection(SectionMap[I]);
1069 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", I+1));
1073 // Emit all Dwarf sections that should come after the content.
1074 void DwarfDebug::endModule() {
1076 if (!FirstCU) return;
1078 // End any existing sections.
1079 // TODO: Does this need to happen?
1082 // Finalize the debug info for the module.
1083 finalizeModuleInfo();
1085 if (!useSplitDwarf()) {
1086 // Emit all the DIEs into a debug info section.
1089 // Corresponding abbreviations into a abbrev section.
1090 emitAbbreviations();
1092 // Emit info into a debug loc section.
1095 // Emit info into a debug aranges section.
1098 // Emit info into a debug ranges section.
1101 // Emit info into a debug macinfo section.
1104 // Emit inline info.
1105 // TODO: When we don't need the option anymore we
1106 // can remove all of the code that this section
1108 if (useDarwinGDBCompat())
1109 emitDebugInlineInfo();
1111 // TODO: Fill this in for separated debug sections and separate
1112 // out information into new sections.
1114 // Emit the debug info section and compile units.
1118 // Corresponding abbreviations into a abbrev section.
1119 emitAbbreviations();
1120 emitDebugAbbrevDWO();
1122 // Emit info into a debug loc section.
1125 // Emit info into a debug aranges section.
1128 // Emit info into a debug ranges section.
1131 // Emit info into a debug macinfo section.
1134 // Emit DWO addresses.
1135 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1137 // Emit inline info.
1138 // TODO: When we don't need the option anymore we
1139 // can remove all of the code that this section
1141 if (useDarwinGDBCompat())
1142 emitDebugInlineInfo();
1145 // Emit info into the dwarf accelerator table sections.
1146 if (useDwarfAccelTables()) {
1149 emitAccelNamespaces();
1153 // Emit info into a debug pubnames section, if requested.
1154 if (HasDwarfPubNames)
1155 emitDebugPubnames();
1157 // Emit info into a debug pubtypes section.
1158 // TODO: When we don't need the option anymore we can
1159 // remove all of the code that adds to the table.
1160 if (useDarwinGDBCompat())
1161 emitDebugPubTypes();
1163 // Finally emit string information into a string table.
1165 if (useSplitDwarf())
1170 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1171 E = CUMap.end(); I != E; ++I)
1174 for (SmallVectorImpl<CompileUnit *>::iterator I = SkeletonCUs.begin(),
1175 E = SkeletonCUs.end(); I != E; ++I)
1178 // Reset these for the next Module if we have one.
1182 // Find abstract variable, if any, associated with Var.
1183 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1184 DebugLoc ScopeLoc) {
1185 LLVMContext &Ctx = DV->getContext();
1186 // More then one inlined variable corresponds to one abstract variable.
1187 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1188 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1190 return AbsDbgVariable;
1192 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1196 AbsDbgVariable = new DbgVariable(Var, NULL);
1197 addScopeVariable(Scope, AbsDbgVariable);
1198 AbstractVariables[Var] = AbsDbgVariable;
1199 return AbsDbgVariable;
1202 // If Var is a current function argument then add it to CurrentFnArguments list.
1203 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1204 DbgVariable *Var, LexicalScope *Scope) {
1205 if (!LScopes.isCurrentFunctionScope(Scope))
1207 DIVariable DV = Var->getVariable();
1208 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1210 unsigned ArgNo = DV.getArgNumber();
1214 size_t Size = CurrentFnArguments.size();
1216 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1217 // llvm::Function argument size is not good indicator of how many
1218 // arguments does the function have at source level.
1220 CurrentFnArguments.resize(ArgNo * 2);
1221 CurrentFnArguments[ArgNo - 1] = Var;
1225 // Collect variable information from side table maintained by MMI.
1227 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1228 SmallPtrSet<const MDNode *, 16> &Processed) {
1229 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1230 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1231 VE = VMap.end(); VI != VE; ++VI) {
1232 const MDNode *Var = VI->first;
1234 Processed.insert(Var);
1236 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1238 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1240 // If variable scope is not found then skip this variable.
1244 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1245 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
1246 RegVar->setFrameIndex(VP.first);
1247 if (!addCurrentFnArgument(MF, RegVar, Scope))
1248 addScopeVariable(Scope, RegVar);
1250 AbsDbgVariable->setFrameIndex(VP.first);
1254 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1256 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1257 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1258 return MI->getNumOperands() == 3 &&
1259 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1260 (MI->getOperand(1).isImm() ||
1261 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1264 // Get .debug_loc entry for the instruction range starting at MI.
1265 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1266 const MCSymbol *FLabel,
1267 const MCSymbol *SLabel,
1268 const MachineInstr *MI) {
1269 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1271 assert(MI->getNumOperands() == 3);
1272 if (MI->getOperand(0).isReg()) {
1273 MachineLocation MLoc;
1274 // If the second operand is an immediate, this is a
1275 // register-indirect address.
1276 if (!MI->getOperand(1).isImm())
1277 MLoc.set(MI->getOperand(0).getReg());
1279 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1280 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1282 if (MI->getOperand(0).isImm())
1283 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1284 if (MI->getOperand(0).isFPImm())
1285 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1286 if (MI->getOperand(0).isCImm())
1287 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1289 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1292 // Find variables for each lexical scope.
1294 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1295 SmallPtrSet<const MDNode *, 16> &Processed) {
1297 // Grab the variable info that was squirreled away in the MMI side-table.
1298 collectVariableInfoFromMMITable(MF, Processed);
1300 for (SmallVectorImpl<const MDNode*>::const_iterator
1301 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1303 const MDNode *Var = *UVI;
1304 if (Processed.count(Var))
1307 // History contains relevant DBG_VALUE instructions for Var and instructions
1309 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1310 if (History.empty())
1312 const MachineInstr *MInsn = History.front();
1315 LexicalScope *Scope = NULL;
1316 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1317 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1318 Scope = LScopes.getCurrentFunctionScope();
1319 else if (MDNode *IA = DV.getInlinedAt())
1320 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1322 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1323 // If variable scope is not found then skip this variable.
1327 Processed.insert(DV);
1328 assert(MInsn->isDebugValue() && "History must begin with debug value");
1329 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1330 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1331 if (!addCurrentFnArgument(MF, RegVar, Scope))
1332 addScopeVariable(Scope, RegVar);
1334 AbsVar->setMInsn(MInsn);
1336 // Simplify ranges that are fully coalesced.
1337 if (History.size() <= 1 || (History.size() == 2 &&
1338 MInsn->isIdenticalTo(History.back()))) {
1339 RegVar->setMInsn(MInsn);
1343 // Handle multiple DBG_VALUE instructions describing one variable.
1344 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1346 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1347 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1348 const MachineInstr *Begin = *HI;
1349 assert(Begin->isDebugValue() && "Invalid History entry");
1351 // Check if DBG_VALUE is truncating a range.
1352 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1353 && !Begin->getOperand(0).getReg())
1356 // Compute the range for a register location.
1357 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1358 const MCSymbol *SLabel = 0;
1361 // If Begin is the last instruction in History then its value is valid
1362 // until the end of the function.
1363 SLabel = FunctionEndSym;
1365 const MachineInstr *End = HI[1];
1366 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1367 << "\t" << *Begin << "\t" << *End << "\n");
1368 if (End->isDebugValue())
1369 SLabel = getLabelBeforeInsn(End);
1371 // End is a normal instruction clobbering the range.
1372 SLabel = getLabelAfterInsn(End);
1373 assert(SLabel && "Forgot label after clobber instruction");
1378 // The value is valid until the next DBG_VALUE or clobber.
1379 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1382 DotDebugLocEntries.push_back(DotDebugLocEntry());
1385 // Collect info for variables that were optimized out.
1386 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1387 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1388 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1389 DIVariable DV(Variables.getElement(i));
1390 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1392 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1393 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1397 // Return Label preceding the instruction.
1398 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1399 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1400 assert(Label && "Didn't insert label before instruction");
1404 // Return Label immediately following the instruction.
1405 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1406 return LabelsAfterInsn.lookup(MI);
1409 // Process beginning of an instruction.
1410 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1411 // Check if source location changes, but ignore DBG_VALUE locations.
1412 if (!MI->isDebugValue()) {
1413 DebugLoc DL = MI->getDebugLoc();
1414 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1417 if (DL == PrologEndLoc) {
1418 Flags |= DWARF2_FLAG_PROLOGUE_END;
1419 PrologEndLoc = DebugLoc();
1421 if (PrologEndLoc.isUnknown())
1422 Flags |= DWARF2_FLAG_IS_STMT;
1424 if (!DL.isUnknown()) {
1425 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1426 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1428 recordSourceLine(0, 0, 0, 0);
1432 // Insert labels where requested.
1433 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1434 LabelsBeforeInsn.find(MI);
1437 if (I == LabelsBeforeInsn.end())
1440 // Label already assigned.
1445 PrevLabel = MMI->getContext().CreateTempSymbol();
1446 Asm->OutStreamer.EmitLabel(PrevLabel);
1448 I->second = PrevLabel;
1451 // Process end of an instruction.
1452 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1453 // Don't create a new label after DBG_VALUE instructions.
1454 // They don't generate code.
1455 if (!MI->isDebugValue())
1458 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1459 LabelsAfterInsn.find(MI);
1462 if (I == LabelsAfterInsn.end())
1465 // Label already assigned.
1469 // We need a label after this instruction.
1471 PrevLabel = MMI->getContext().CreateTempSymbol();
1472 Asm->OutStreamer.EmitLabel(PrevLabel);
1474 I->second = PrevLabel;
1477 // Each LexicalScope has first instruction and last instruction to mark
1478 // beginning and end of a scope respectively. Create an inverse map that list
1479 // scopes starts (and ends) with an instruction. One instruction may start (or
1480 // end) multiple scopes. Ignore scopes that are not reachable.
1481 void DwarfDebug::identifyScopeMarkers() {
1482 SmallVector<LexicalScope *, 4> WorkList;
1483 WorkList.push_back(LScopes.getCurrentFunctionScope());
1484 while (!WorkList.empty()) {
1485 LexicalScope *S = WorkList.pop_back_val();
1487 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1488 if (!Children.empty())
1489 for (SmallVectorImpl<LexicalScope *>::const_iterator SI = Children.begin(),
1490 SE = Children.end(); SI != SE; ++SI)
1491 WorkList.push_back(*SI);
1493 if (S->isAbstractScope())
1496 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1499 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1500 RE = Ranges.end(); RI != RE; ++RI) {
1501 assert(RI->first && "InsnRange does not have first instruction!");
1502 assert(RI->second && "InsnRange does not have second instruction!");
1503 requestLabelBeforeInsn(RI->first);
1504 requestLabelAfterInsn(RI->second);
1509 // Get MDNode for DebugLoc's scope.
1510 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1511 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1512 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1513 return DL.getScope(Ctx);
1516 // Walk up the scope chain of given debug loc and find line number info
1517 // for the function.
1518 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1519 const MDNode *Scope = getScopeNode(DL, Ctx);
1520 DISubprogram SP = getDISubprogram(Scope);
1521 if (SP.isSubprogram()) {
1522 // Check for number of operands since the compatibility is
1524 if (SP->getNumOperands() > 19)
1525 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1527 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1533 // Gather pre-function debug information. Assumes being called immediately
1534 // after the function entry point has been emitted.
1535 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1536 if (!MMI->hasDebugInfo()) return;
1537 LScopes.initialize(*MF);
1538 if (LScopes.empty()) return;
1539 identifyScopeMarkers();
1541 // Set DwarfCompileUnitID in MCContext to the Compile Unit this function
1543 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1544 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1545 assert(TheCU && "Unable to find compile unit!");
1546 if (Asm->TM.hasMCUseLoc() &&
1547 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer)
1548 // Use a single line table if we are using .loc and generating assembly.
1549 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1551 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1553 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1554 Asm->getFunctionNumber());
1555 // Assumes in correct section after the entry point.
1556 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1558 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1560 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1561 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1562 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1564 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1566 bool AtBlockEntry = true;
1567 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1569 const MachineInstr *MI = II;
1571 if (MI->isDebugValue()) {
1572 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1574 // Keep track of user variables.
1576 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1578 // Variable is in a register, we need to check for clobbers.
1579 if (isDbgValueInDefinedReg(MI))
1580 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1582 // Check the history of this variable.
1583 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1584 if (History.empty()) {
1585 UserVariables.push_back(Var);
1586 // The first mention of a function argument gets the FunctionBeginSym
1587 // label, so arguments are visible when breaking at function entry.
1589 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1590 DISubprogram(getDISubprogram(DV.getContext()))
1591 .describes(MF->getFunction()))
1592 LabelsBeforeInsn[MI] = FunctionBeginSym;
1594 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1595 const MachineInstr *Prev = History.back();
1596 if (Prev->isDebugValue()) {
1597 // Coalesce identical entries at the end of History.
1598 if (History.size() >= 2 &&
1599 Prev->isIdenticalTo(History[History.size() - 2])) {
1600 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1602 << "\t" << *History[History.size() - 2] << "\n");
1606 // Terminate old register assignments that don't reach MI;
1607 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1608 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1609 isDbgValueInDefinedReg(Prev)) {
1610 // Previous register assignment needs to terminate at the end of
1612 MachineBasicBlock::const_iterator LastMI =
1613 PrevMBB->getLastNonDebugInstr();
1614 if (LastMI == PrevMBB->end()) {
1615 // Drop DBG_VALUE for empty range.
1616 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1617 << "\t" << *Prev << "\n");
1619 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1620 // Terminate after LastMI.
1621 History.push_back(LastMI);
1625 History.push_back(MI);
1627 // Not a DBG_VALUE instruction.
1629 AtBlockEntry = false;
1631 // First known non-DBG_VALUE and non-frame setup location marks
1632 // the beginning of the function body.
1633 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1634 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1635 PrologEndLoc = MI->getDebugLoc();
1637 // Check if the instruction clobbers any registers with debug vars.
1638 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1639 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1640 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1642 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1643 AI.isValid(); ++AI) {
1645 const MDNode *Var = LiveUserVar[Reg];
1648 // Reg is now clobbered.
1649 LiveUserVar[Reg] = 0;
1651 // Was MD last defined by a DBG_VALUE referring to Reg?
1652 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1653 if (HistI == DbgValues.end())
1655 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1656 if (History.empty())
1658 const MachineInstr *Prev = History.back();
1659 // Sanity-check: Register assignments are terminated at the end of
1661 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1663 // Is the variable still in Reg?
1664 if (!isDbgValueInDefinedReg(Prev) ||
1665 Prev->getOperand(0).getReg() != Reg)
1667 // Var is clobbered. Make sure the next instruction gets a label.
1668 History.push_back(MI);
1675 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1677 SmallVectorImpl<const MachineInstr*> &History = I->second;
1678 if (History.empty())
1681 // Make sure the final register assignments are terminated.
1682 const MachineInstr *Prev = History.back();
1683 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1684 const MachineBasicBlock *PrevMBB = Prev->getParent();
1685 MachineBasicBlock::const_iterator LastMI =
1686 PrevMBB->getLastNonDebugInstr();
1687 if (LastMI == PrevMBB->end())
1688 // Drop DBG_VALUE for empty range.
1690 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1691 // Terminate after LastMI.
1692 History.push_back(LastMI);
1695 // Request labels for the full history.
1696 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1697 const MachineInstr *MI = History[i];
1698 if (MI->isDebugValue())
1699 requestLabelBeforeInsn(MI);
1701 requestLabelAfterInsn(MI);
1705 PrevInstLoc = DebugLoc();
1706 PrevLabel = FunctionBeginSym;
1708 // Record beginning of function.
1709 if (!PrologEndLoc.isUnknown()) {
1710 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1711 MF->getFunction()->getContext());
1712 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1713 FnStartDL.getScope(MF->getFunction()->getContext()),
1714 // We'd like to list the prologue as "not statements" but GDB behaves
1715 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1716 DWARF2_FLAG_IS_STMT);
1720 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1721 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1722 DIVariable DV = Var->getVariable();
1723 // Variables with positive arg numbers are parameters.
1724 if (unsigned ArgNum = DV.getArgNumber()) {
1725 // Keep all parameters in order at the start of the variable list to ensure
1726 // function types are correct (no out-of-order parameters)
1728 // This could be improved by only doing it for optimized builds (unoptimized
1729 // builds have the right order to begin with), searching from the back (this
1730 // would catch the unoptimized case quickly), or doing a binary search
1731 // rather than linear search.
1732 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1733 while (I != Vars.end()) {
1734 unsigned CurNum = (*I)->getVariable().getArgNumber();
1735 // A local (non-parameter) variable has been found, insert immediately
1739 // A later indexed parameter has been found, insert immediately before it.
1740 if (CurNum > ArgNum)
1744 Vars.insert(I, Var);
1748 Vars.push_back(Var);
1751 // Gather and emit post-function debug information.
1752 void DwarfDebug::endFunction(const MachineFunction *MF) {
1753 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1755 // Define end label for subprogram.
1756 FunctionEndSym = Asm->GetTempSymbol("func_end",
1757 Asm->getFunctionNumber());
1758 // Assumes in correct section after the entry point.
1759 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1760 // Set DwarfCompileUnitID in MCContext to default value.
1761 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1763 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1764 collectVariableInfo(MF, ProcessedVars);
1766 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1767 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1768 assert(TheCU && "Unable to find compile unit!");
1770 // Construct abstract scopes.
1771 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1772 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1773 LexicalScope *AScope = AList[i];
1774 DISubprogram SP(AScope->getScopeNode());
1775 if (SP.isSubprogram()) {
1776 // Collect info for variables that were optimized out.
1777 DIArray Variables = SP.getVariables();
1778 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1779 DIVariable DV(Variables.getElement(i));
1780 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1782 // Check that DbgVariable for DV wasn't created earlier, when
1783 // findAbstractVariable() was called for inlined instance of DV.
1784 LLVMContext &Ctx = DV->getContext();
1785 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1786 if (AbstractVariables.lookup(CleanDV))
1788 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1789 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1792 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1793 constructScopeDIE(TheCU, AScope);
1796 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1798 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1799 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1802 for (ScopeVariablesMap::iterator
1803 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1804 DeleteContainerPointers(I->second);
1805 ScopeVariables.clear();
1806 DeleteContainerPointers(CurrentFnArguments);
1807 UserVariables.clear();
1809 AbstractVariables.clear();
1810 LabelsBeforeInsn.clear();
1811 LabelsAfterInsn.clear();
1815 // Register a source line with debug info. Returns the unique label that was
1816 // emitted and which provides correspondence to the source line list.
1817 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1823 DIDescriptor Scope(S);
1825 if (Scope.isCompileUnit()) {
1826 DICompileUnit CU(S);
1827 Fn = CU.getFilename();
1828 Dir = CU.getDirectory();
1829 } else if (Scope.isFile()) {
1831 Fn = F.getFilename();
1832 Dir = F.getDirectory();
1833 } else if (Scope.isSubprogram()) {
1835 Fn = SP.getFilename();
1836 Dir = SP.getDirectory();
1837 } else if (Scope.isLexicalBlockFile()) {
1838 DILexicalBlockFile DBF(S);
1839 Fn = DBF.getFilename();
1840 Dir = DBF.getDirectory();
1841 } else if (Scope.isLexicalBlock()) {
1842 DILexicalBlock DB(S);
1843 Fn = DB.getFilename();
1844 Dir = DB.getDirectory();
1846 llvm_unreachable("Unexpected scope info");
1848 Src = getOrCreateSourceID(Fn, Dir,
1849 Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1851 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1854 //===----------------------------------------------------------------------===//
1856 //===----------------------------------------------------------------------===//
1858 // Compute the size and offset of a DIE.
1860 DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1861 // Get the children.
1862 const std::vector<DIE *> &Children = Die->getChildren();
1864 // Record the abbreviation.
1865 assignAbbrevNumber(Die->getAbbrev());
1867 // Get the abbreviation for this DIE.
1868 unsigned AbbrevNumber = Die->getAbbrevNumber();
1869 const DIEAbbrev *Abbrev = Abbreviations->at(AbbrevNumber - 1);
1872 Die->setOffset(Offset);
1874 // Start the size with the size of abbreviation code.
1875 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1877 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1878 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1880 // Size the DIE attribute values.
1881 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1882 // Size attribute value.
1883 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1885 // Size the DIE children if any.
1886 if (!Children.empty()) {
1887 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1888 "Children flag not set");
1890 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1891 Offset = computeSizeAndOffset(Children[j], Offset);
1893 // End of children marker.
1894 Offset += sizeof(int8_t);
1897 Die->setSize(Offset - Die->getOffset());
1901 // Compute the size and offset of all the DIEs.
1902 void DwarfUnits::computeSizeAndOffsets() {
1903 // Offset from the beginning of debug info section.
1904 unsigned SecOffset = 0;
1905 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1906 E = CUs.end(); I != E; ++I) {
1907 (*I)->setDebugInfoOffset(SecOffset);
1909 sizeof(int32_t) + // Length of Compilation Unit Info
1910 sizeof(int16_t) + // DWARF version number
1911 sizeof(int32_t) + // Offset Into Abbrev. Section
1912 sizeof(int8_t); // Pointer Size (in bytes)
1914 unsigned EndOffset = computeSizeAndOffset((*I)->getCUDie(), Offset);
1915 SecOffset += EndOffset;
1919 // Emit initial Dwarf sections with a label at the start of each one.
1920 void DwarfDebug::emitSectionLabels() {
1921 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1923 // Dwarf sections base addresses.
1924 DwarfInfoSectionSym =
1925 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1926 DwarfAbbrevSectionSym =
1927 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1928 if (useSplitDwarf())
1929 DwarfAbbrevDWOSectionSym =
1930 emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
1931 "section_abbrev_dwo");
1932 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1934 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1935 emitSectionSym(Asm, MacroInfo);
1937 DwarfLineSectionSym =
1938 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1939 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1940 if (HasDwarfPubNames)
1941 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1942 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1943 DwarfStrSectionSym =
1944 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1945 if (useSplitDwarf()) {
1946 DwarfStrDWOSectionSym =
1947 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1948 DwarfAddrSectionSym =
1949 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1951 DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1954 DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
1955 "section_debug_loc");
1957 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1958 emitSectionSym(Asm, TLOF.getDataSection());
1961 // Recursively emits a debug information entry.
1962 void DwarfDebug::emitDIE(DIE *Die, std::vector<DIEAbbrev *> *Abbrevs) {
1963 // Get the abbreviation for this DIE.
1964 unsigned AbbrevNumber = Die->getAbbrevNumber();
1965 const DIEAbbrev *Abbrev = Abbrevs->at(AbbrevNumber - 1);
1967 // Emit the code (index) for the abbreviation.
1968 if (Asm->isVerbose())
1969 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1970 Twine::utohexstr(Die->getOffset()) + ":0x" +
1971 Twine::utohexstr(Die->getSize()) + " " +
1972 dwarf::TagString(Abbrev->getTag()));
1973 Asm->EmitULEB128(AbbrevNumber);
1975 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1976 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1978 // Emit the DIE attribute values.
1979 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1980 unsigned Attr = AbbrevData[i].getAttribute();
1981 unsigned Form = AbbrevData[i].getForm();
1982 assert(Form && "Too many attributes for DIE (check abbreviation)");
1984 if (Asm->isVerbose())
1985 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1988 case dwarf::DW_AT_abstract_origin: {
1989 DIEEntry *E = cast<DIEEntry>(Values[i]);
1990 DIE *Origin = E->getEntry();
1991 unsigned Addr = Origin->getOffset();
1992 if (Form == dwarf::DW_FORM_ref_addr) {
1993 // For DW_FORM_ref_addr, output the offset from beginning of debug info
1994 // section. Origin->getOffset() returns the offset from start of the
1996 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1997 Addr += Holder.getCUOffset(Origin->getCompileUnit());
1999 Asm->OutStreamer.EmitIntValue(Addr,
2000 Form == dwarf::DW_FORM_ref_addr ? DIEEntry::getRefAddrSize(Asm) : 4);
2003 case dwarf::DW_AT_ranges: {
2004 // DW_AT_range Value encodes offset in debug_range section.
2005 DIEInteger *V = cast<DIEInteger>(Values[i]);
2007 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
2008 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
2012 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
2014 DwarfDebugRangeSectionSym,
2019 case dwarf::DW_AT_location: {
2020 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
2021 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2022 Asm->EmitLabelReference(L->getValue(), 4);
2024 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2026 Values[i]->EmitValue(Asm, Form);
2030 case dwarf::DW_AT_accessibility: {
2031 if (Asm->isVerbose()) {
2032 DIEInteger *V = cast<DIEInteger>(Values[i]);
2033 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2035 Values[i]->EmitValue(Asm, Form);
2039 // Emit an attribute using the defined form.
2040 Values[i]->EmitValue(Asm, Form);
2045 // Emit the DIE children if any.
2046 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2047 const std::vector<DIE *> &Children = Die->getChildren();
2049 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2050 emitDIE(Children[j], Abbrevs);
2052 if (Asm->isVerbose())
2053 Asm->OutStreamer.AddComment("End Of Children Mark");
2058 // Emit the various dwarf units to the unit section USection with
2059 // the abbreviations going into ASection.
2060 void DwarfUnits::emitUnits(DwarfDebug *DD,
2061 const MCSection *USection,
2062 const MCSection *ASection,
2063 const MCSymbol *ASectionSym) {
2064 Asm->OutStreamer.SwitchSection(USection);
2065 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
2066 E = CUs.end(); I != E; ++I) {
2067 CompileUnit *TheCU = *I;
2068 DIE *Die = TheCU->getCUDie();
2070 // Emit the compile units header.
2072 .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
2073 TheCU->getUniqueID()));
2075 // Emit size of content not including length itself
2076 unsigned ContentSize = Die->getSize() +
2077 sizeof(int16_t) + // DWARF version number
2078 sizeof(int32_t) + // Offset Into Abbrev. Section
2079 sizeof(int8_t); // Pointer Size (in bytes)
2081 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2082 Asm->EmitInt32(ContentSize);
2083 Asm->OutStreamer.AddComment("DWARF version number");
2084 Asm->EmitInt16(DD->getDwarfVersion());
2085 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2086 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
2088 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2089 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2091 DD->emitDIE(Die, Abbreviations);
2092 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
2093 TheCU->getUniqueID()));
2097 /// For a given compile unit DIE, returns offset from beginning of debug info.
2098 unsigned DwarfUnits::getCUOffset(DIE *Die) {
2099 assert(Die->getTag() == dwarf::DW_TAG_compile_unit &&
2100 "Input DIE should be compile unit in getCUOffset.");
2101 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(), E = CUs.end();
2103 CompileUnit *TheCU = *I;
2104 if (TheCU->getCUDie() == Die)
2105 return TheCU->getDebugInfoOffset();
2107 llvm_unreachable("The compile unit DIE should belong to CUs in DwarfUnits.");
2110 // Emit the debug info section.
2111 void DwarfDebug::emitDebugInfo() {
2112 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2114 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
2115 Asm->getObjFileLowering().getDwarfAbbrevSection(),
2116 DwarfAbbrevSectionSym);
2119 // Emit the abbreviation section.
2120 void DwarfDebug::emitAbbreviations() {
2121 if (!useSplitDwarf())
2122 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
2125 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2128 void DwarfDebug::emitAbbrevs(const MCSection *Section,
2129 std::vector<DIEAbbrev *> *Abbrevs) {
2130 // Check to see if it is worth the effort.
2131 if (!Abbrevs->empty()) {
2132 // Start the debug abbrev section.
2133 Asm->OutStreamer.SwitchSection(Section);
2135 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
2136 Asm->OutStreamer.EmitLabel(Begin);
2138 // For each abbrevation.
2139 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
2140 // Get abbreviation data
2141 const DIEAbbrev *Abbrev = Abbrevs->at(i);
2143 // Emit the abbrevations code (base 1 index.)
2144 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2146 // Emit the abbreviations data.
2150 // Mark end of abbreviations.
2151 Asm->EmitULEB128(0, "EOM(3)");
2153 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
2154 Asm->OutStreamer.EmitLabel(End);
2158 // Emit the last address of the section and the end of the line matrix.
2159 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2160 // Define last address of section.
2161 Asm->OutStreamer.AddComment("Extended Op");
2164 Asm->OutStreamer.AddComment("Op size");
2165 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2166 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2167 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2169 Asm->OutStreamer.AddComment("Section end label");
2171 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2172 Asm->getDataLayout().getPointerSize());
2174 // Mark end of matrix.
2175 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2181 // Emit visible names into a hashed accelerator table section.
2182 void DwarfDebug::emitAccelNames() {
2183 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2184 dwarf::DW_FORM_data4));
2185 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2186 E = CUMap.end(); I != E; ++I) {
2187 CompileUnit *TheCU = I->second;
2188 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
2189 for (StringMap<std::vector<DIE*> >::const_iterator
2190 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2191 StringRef Name = GI->getKey();
2192 const std::vector<DIE *> &Entities = GI->second;
2193 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2194 DE = Entities.end(); DI != DE; ++DI)
2195 AT.AddName(Name, (*DI));
2199 AT.FinalizeTable(Asm, "Names");
2200 Asm->OutStreamer.SwitchSection(
2201 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2202 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2203 Asm->OutStreamer.EmitLabel(SectionBegin);
2205 // Emit the full data.
2206 AT.Emit(Asm, SectionBegin, &InfoHolder);
2209 // Emit objective C classes and categories into a hashed accelerator table
2211 void DwarfDebug::emitAccelObjC() {
2212 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2213 dwarf::DW_FORM_data4));
2214 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2215 E = CUMap.end(); I != E; ++I) {
2216 CompileUnit *TheCU = I->second;
2217 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
2218 for (StringMap<std::vector<DIE*> >::const_iterator
2219 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2220 StringRef Name = GI->getKey();
2221 const std::vector<DIE *> &Entities = GI->second;
2222 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2223 DE = Entities.end(); DI != DE; ++DI)
2224 AT.AddName(Name, (*DI));
2228 AT.FinalizeTable(Asm, "ObjC");
2229 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2230 .getDwarfAccelObjCSection());
2231 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2232 Asm->OutStreamer.EmitLabel(SectionBegin);
2234 // Emit the full data.
2235 AT.Emit(Asm, SectionBegin, &InfoHolder);
2238 // Emit namespace dies into a hashed accelerator table.
2239 void DwarfDebug::emitAccelNamespaces() {
2240 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2241 dwarf::DW_FORM_data4));
2242 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2243 E = CUMap.end(); I != E; ++I) {
2244 CompileUnit *TheCU = I->second;
2245 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2246 for (StringMap<std::vector<DIE*> >::const_iterator
2247 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2248 StringRef Name = GI->getKey();
2249 const std::vector<DIE *> &Entities = GI->second;
2250 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2251 DE = Entities.end(); DI != DE; ++DI)
2252 AT.AddName(Name, (*DI));
2256 AT.FinalizeTable(Asm, "namespac");
2257 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2258 .getDwarfAccelNamespaceSection());
2259 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2260 Asm->OutStreamer.EmitLabel(SectionBegin);
2262 // Emit the full data.
2263 AT.Emit(Asm, SectionBegin, &InfoHolder);
2266 // Emit type dies into a hashed accelerator table.
2267 void DwarfDebug::emitAccelTypes() {
2268 std::vector<DwarfAccelTable::Atom> Atoms;
2269 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2270 dwarf::DW_FORM_data4));
2271 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
2272 dwarf::DW_FORM_data2));
2273 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
2274 dwarf::DW_FORM_data1));
2275 DwarfAccelTable AT(Atoms);
2276 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2277 E = CUMap.end(); I != E; ++I) {
2278 CompileUnit *TheCU = I->second;
2279 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2280 = TheCU->getAccelTypes();
2281 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2282 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2283 StringRef Name = GI->getKey();
2284 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2285 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2286 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2287 AT.AddName(Name, (*DI).first, (*DI).second);
2291 AT.FinalizeTable(Asm, "types");
2292 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2293 .getDwarfAccelTypesSection());
2294 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2295 Asm->OutStreamer.EmitLabel(SectionBegin);
2297 // Emit the full data.
2298 AT.Emit(Asm, SectionBegin, &InfoHolder);
2301 /// emitDebugPubnames - Emit visible names into a debug pubnames section.
2303 void DwarfDebug::emitDebugPubnames() {
2304 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2306 typedef DenseMap<const MDNode*, CompileUnit*> CUMapType;
2307 for (CUMapType::iterator I = CUMap.begin(), E = CUMap.end(); I != E; ++I) {
2308 CompileUnit *TheCU = I->second;
2309 unsigned ID = TheCU->getUniqueID();
2311 if (TheCU->getGlobalNames().empty())
2314 // Start the dwarf pubnames section.
2316 .SwitchSection(Asm->getObjFileLowering().getDwarfPubNamesSection());
2318 Asm->OutStreamer.AddComment("Length of Public Names Info");
2319 Asm->EmitLabelDifference(Asm->GetTempSymbol("pubnames_end", ID),
2320 Asm->GetTempSymbol("pubnames_begin", ID), 4);
2322 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", ID));
2324 Asm->OutStreamer.AddComment("DWARF Version");
2325 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2327 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2328 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2329 DwarfInfoSectionSym);
2331 Asm->OutStreamer.AddComment("Compilation Unit Length");
2332 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(), ID),
2333 Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2336 const StringMap<DIE*> &Globals = TheCU->getGlobalNames();
2337 for (StringMap<DIE*>::const_iterator
2338 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2339 const char *Name = GI->getKeyData();
2340 const DIE *Entity = GI->second;
2342 Asm->OutStreamer.AddComment("DIE offset");
2343 Asm->EmitInt32(Entity->getOffset());
2345 if (Asm->isVerbose())
2346 Asm->OutStreamer.AddComment("External Name");
2347 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2350 Asm->OutStreamer.AddComment("End Mark");
2352 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", ID));
2356 void DwarfDebug::emitDebugPubTypes() {
2357 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2358 E = CUMap.end(); I != E; ++I) {
2359 CompileUnit *TheCU = I->second;
2360 // Start the dwarf pubtypes section.
2361 Asm->OutStreamer.SwitchSection(
2362 Asm->getObjFileLowering().getDwarfPubTypesSection());
2363 Asm->OutStreamer.AddComment("Length of Public Types Info");
2364 Asm->EmitLabelDifference(
2365 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2366 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2368 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2369 TheCU->getUniqueID()));
2371 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2372 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2374 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2375 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2376 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(),
2377 TheCU->getUniqueID()),
2378 DwarfInfoSectionSym);
2380 Asm->OutStreamer.AddComment("Compilation Unit Length");
2381 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(),
2382 TheCU->getUniqueID()),
2383 Asm->GetTempSymbol(ISec->getLabelBeginName(),
2384 TheCU->getUniqueID()),
2387 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2388 for (StringMap<DIE*>::const_iterator
2389 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2390 const char *Name = GI->getKeyData();
2391 DIE *Entity = GI->second;
2393 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2394 Asm->EmitInt32(Entity->getOffset());
2396 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2397 // Emit the name with a terminating null byte.
2398 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2401 Asm->OutStreamer.AddComment("End Mark");
2403 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2404 TheCU->getUniqueID()));
2408 // Emit strings into a string section.
2409 void DwarfUnits::emitStrings(const MCSection *StrSection,
2410 const MCSection *OffsetSection = NULL,
2411 const MCSymbol *StrSecSym = NULL) {
2413 if (StringPool.empty()) return;
2415 // Start the dwarf str section.
2416 Asm->OutStreamer.SwitchSection(StrSection);
2418 // Get all of the string pool entries and put them in an array by their ID so
2419 // we can sort them.
2420 SmallVector<std::pair<unsigned,
2421 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2423 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2424 I = StringPool.begin(), E = StringPool.end();
2426 Entries.push_back(std::make_pair(I->second.second, &*I));
2428 array_pod_sort(Entries.begin(), Entries.end());
2430 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2431 // Emit a label for reference from debug information entries.
2432 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2434 // Emit the string itself with a terminating null byte.
2435 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2436 Entries[i].second->getKeyLength()+1));
2439 // If we've got an offset section go ahead and emit that now as well.
2440 if (OffsetSection) {
2441 Asm->OutStreamer.SwitchSection(OffsetSection);
2442 unsigned offset = 0;
2443 unsigned size = 4; // FIXME: DWARF64 is 8.
2444 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2445 Asm->OutStreamer.EmitIntValue(offset, size);
2446 offset += Entries[i].second->getKeyLength() + 1;
2451 // Emit strings into a string section.
2452 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2454 if (AddressPool.empty()) return;
2456 // Start the dwarf addr section.
2457 Asm->OutStreamer.SwitchSection(AddrSection);
2459 // Order the address pool entries by ID
2460 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2462 for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2463 E = AddressPool.end();
2465 Entries[I->second] = I->first;
2467 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2468 // Emit an expression for reference from debug information entries.
2469 if (const MCExpr *Expr = Entries[i])
2470 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2472 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2477 // Emit visible names into a debug str section.
2478 void DwarfDebug::emitDebugStr() {
2479 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2480 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2483 // Emit locations into the debug loc section.
2484 void DwarfDebug::emitDebugLoc() {
2485 if (DotDebugLocEntries.empty())
2488 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2489 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2491 DotDebugLocEntry &Entry = *I;
2492 if (I + 1 != DotDebugLocEntries.end())
2496 // Start the dwarf loc section.
2497 Asm->OutStreamer.SwitchSection(
2498 Asm->getObjFileLowering().getDwarfLocSection());
2499 unsigned char Size = Asm->getDataLayout().getPointerSize();
2500 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2502 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2503 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2504 I != E; ++I, ++index) {
2505 DotDebugLocEntry &Entry = *I;
2506 if (Entry.isMerged()) continue;
2507 if (Entry.isEmpty()) {
2508 Asm->OutStreamer.EmitIntValue(0, Size);
2509 Asm->OutStreamer.EmitIntValue(0, Size);
2510 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2512 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2513 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2514 DIVariable DV(Entry.getVariable());
2515 Asm->OutStreamer.AddComment("Loc expr size");
2516 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2517 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2518 Asm->EmitLabelDifference(end, begin, 2);
2519 Asm->OutStreamer.EmitLabel(begin);
2520 if (Entry.isInt()) {
2521 DIBasicType BTy(DV.getType());
2523 (BTy.getEncoding() == dwarf::DW_ATE_signed
2524 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2525 Asm->OutStreamer.AddComment("DW_OP_consts");
2526 Asm->EmitInt8(dwarf::DW_OP_consts);
2527 Asm->EmitSLEB128(Entry.getInt());
2529 Asm->OutStreamer.AddComment("DW_OP_constu");
2530 Asm->EmitInt8(dwarf::DW_OP_constu);
2531 Asm->EmitULEB128(Entry.getInt());
2533 } else if (Entry.isLocation()) {
2534 MachineLocation Loc = Entry.getLoc();
2535 if (!DV.hasComplexAddress())
2537 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2539 // Complex address entry.
2540 unsigned N = DV.getNumAddrElements();
2542 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2543 if (Loc.getOffset()) {
2545 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2546 Asm->OutStreamer.AddComment("DW_OP_deref");
2547 Asm->EmitInt8(dwarf::DW_OP_deref);
2548 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2549 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2550 Asm->EmitSLEB128(DV.getAddrElement(1));
2552 // If first address element is OpPlus then emit
2553 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2554 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2555 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2559 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2562 // Emit remaining complex address elements.
2563 for (; i < N; ++i) {
2564 uint64_t Element = DV.getAddrElement(i);
2565 if (Element == DIBuilder::OpPlus) {
2566 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2567 Asm->EmitULEB128(DV.getAddrElement(++i));
2568 } else if (Element == DIBuilder::OpDeref) {
2570 Asm->EmitInt8(dwarf::DW_OP_deref);
2572 llvm_unreachable("unknown Opcode found in complex address");
2576 // else ... ignore constant fp. There is not any good way to
2577 // to represent them here in dwarf.
2578 Asm->OutStreamer.EmitLabel(end);
2583 // Emit visible names into a debug aranges section.
2584 void DwarfDebug::emitDebugARanges() {
2585 // Start the dwarf aranges section.
2586 Asm->OutStreamer.SwitchSection(
2587 Asm->getObjFileLowering().getDwarfARangesSection());
2590 // Emit visible names into a debug ranges section.
2591 void DwarfDebug::emitDebugRanges() {
2592 // Start the dwarf ranges section.
2593 Asm->OutStreamer.SwitchSection(
2594 Asm->getObjFileLowering().getDwarfRangesSection());
2595 unsigned char Size = Asm->getDataLayout().getPointerSize();
2596 for (SmallVectorImpl<const MCSymbol *>::iterator
2597 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2600 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size);
2602 Asm->OutStreamer.EmitIntValue(0, Size);
2606 // Emit visible names into a debug macinfo section.
2607 void DwarfDebug::emitDebugMacInfo() {
2608 if (const MCSection *LineInfo =
2609 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2610 // Start the dwarf macinfo section.
2611 Asm->OutStreamer.SwitchSection(LineInfo);
2615 // Emit inline info using following format.
2617 // 1. length of section
2618 // 2. Dwarf version number
2621 // Entries (one "entry" for each function that was inlined):
2623 // 1. offset into __debug_str section for MIPS linkage name, if exists;
2624 // otherwise offset into __debug_str for regular function name.
2625 // 2. offset into __debug_str section for regular function name.
2626 // 3. an unsigned LEB128 number indicating the number of distinct inlining
2627 // instances for the function.
2629 // The rest of the entry consists of a {die_offset, low_pc} pair for each
2630 // inlined instance; the die_offset points to the inlined_subroutine die in the
2631 // __debug_info section, and the low_pc is the starting address for the
2632 // inlining instance.
2633 void DwarfDebug::emitDebugInlineInfo() {
2634 if (!Asm->MAI->doesDwarfUseInlineInfoSection())
2640 Asm->OutStreamer.SwitchSection(
2641 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2643 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2644 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2645 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2647 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2649 Asm->OutStreamer.AddComment("Dwarf Version");
2650 Asm->EmitInt16(DwarfVersion);
2651 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2652 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2654 for (SmallVectorImpl<const MDNode *>::iterator I = InlinedSPNodes.begin(),
2655 E = InlinedSPNodes.end(); I != E; ++I) {
2657 const MDNode *Node = *I;
2658 InlineInfoMap::iterator II = InlineInfo.find(Node);
2659 SmallVectorImpl<InlineInfoLabels> &Labels = II->second;
2660 DISubprogram SP(Node);
2661 StringRef LName = SP.getLinkageName();
2662 StringRef Name = SP.getName();
2664 Asm->OutStreamer.AddComment("MIPS linkage name");
2666 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2667 DwarfStrSectionSym);
2669 Asm->EmitSectionOffset(
2670 InfoHolder.getStringPoolEntry(Function::getRealLinkageName(LName)),
2671 DwarfStrSectionSym);
2673 Asm->OutStreamer.AddComment("Function name");
2674 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2675 DwarfStrSectionSym);
2676 Asm->EmitULEB128(Labels.size(), "Inline count");
2678 for (SmallVectorImpl<InlineInfoLabels>::iterator LI = Labels.begin(),
2679 LE = Labels.end(); LI != LE; ++LI) {
2680 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2681 Asm->EmitInt32(LI->second->getOffset());
2683 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2684 Asm->OutStreamer.EmitSymbolValue(LI->first,
2685 Asm->getDataLayout().getPointerSize());
2689 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2692 // DWARF5 Experimental Separate Dwarf emitters.
2694 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2695 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2696 // DW_AT_ranges_base, DW_AT_addr_base. If DW_AT_ranges is present,
2697 // DW_AT_low_pc and DW_AT_high_pc are not used, and vice versa.
2698 CompileUnit *DwarfDebug::constructSkeletonCU(const MDNode *N) {
2699 DICompileUnit DIUnit(N);
2700 CompilationDir = DIUnit.getDirectory();
2702 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2703 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
2704 DIUnit.getLanguage(), Die, N, Asm,
2705 this, &SkeletonHolder);
2707 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2708 DIUnit.getSplitDebugFilename());
2710 // Relocate to the beginning of the addr_base section, else 0 for the
2711 // beginning of the one for this compile unit.
2712 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2713 NewCU->addLabel(Die, dwarf::DW_AT_GNU_addr_base, dwarf::DW_FORM_sec_offset,
2714 DwarfAddrSectionSym);
2716 NewCU->addUInt(Die, dwarf::DW_AT_GNU_addr_base,
2717 dwarf::DW_FORM_sec_offset, 0);
2719 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2720 // into an entity. We're using 0, or a NULL label for this.
2721 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2723 // DW_AT_stmt_list is a offset of line number information for this
2724 // compile unit in debug_line section.
2725 // FIXME: Should handle multiple compile units.
2726 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2727 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
2728 DwarfLineSectionSym);
2730 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset, 0);
2732 if (!CompilationDir.empty())
2733 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2735 SkeletonHolder.addUnit(NewCU);
2736 SkeletonCUs.push_back(NewCU);
2741 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
2742 assert(useSplitDwarf() && "No split dwarf debug info?");
2743 emitAbbrevs(Section, &SkeletonAbbrevs);
2746 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2747 // compile units that would normally be in debug_info.
2748 void DwarfDebug::emitDebugInfoDWO() {
2749 assert(useSplitDwarf() && "No split dwarf debug info?");
2750 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
2751 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2752 DwarfAbbrevDWOSectionSym);
2755 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2756 // abbreviations for the .debug_info.dwo section.
2757 void DwarfDebug::emitDebugAbbrevDWO() {
2758 assert(useSplitDwarf() && "No split dwarf?");
2759 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2763 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2764 // string section and is identical in format to traditional .debug_str
2766 void DwarfDebug::emitDebugStrDWO() {
2767 assert(useSplitDwarf() && "No split dwarf?");
2768 const MCSection *OffSec = Asm->getObjFileLowering()
2769 .getDwarfStrOffDWOSection();
2770 const MCSymbol *StrSym = DwarfStrSectionSym;
2771 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),