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/ErrorHandling.h"
39 #include "llvm/Support/FormattedStream.h"
40 #include "llvm/Support/MD5.h"
41 #include "llvm/Support/Path.h"
42 #include "llvm/Support/Timer.h"
43 #include "llvm/Support/ValueHandle.h"
44 #include "llvm/Target/TargetFrameLowering.h"
45 #include "llvm/Target/TargetLoweringObjectFile.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetOptions.h"
48 #include "llvm/Target/TargetRegisterInfo.h"
52 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
53 cl::desc("Disable debug info printing"));
55 static cl::opt<bool> UnknownLocations(
56 "use-unknown-locations", cl::Hidden,
57 cl::desc("Make an absence of debug location information explicit."),
61 GenerateDwarfPubNamesSection("generate-dwarf-pubnames", cl::Hidden,
63 cl::desc("Generate DWARF pubnames section"));
66 GenerateODRHash("generate-odr-hash", cl::Hidden,
67 cl::desc("Add an ODR hash to external type DIEs."),
71 GenerateCUHash("generate-cu-hash", cl::Hidden,
72 cl::desc("Add the CU hash as the dwo_id."),
83 static cl::opt<DefaultOnOff>
84 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
85 cl::desc("Output prototype dwarf accelerator tables."),
86 cl::values(clEnumVal(Default, "Default for platform"),
87 clEnumVal(Enable, "Enabled"),
88 clEnumVal(Disable, "Disabled"), clEnumValEnd),
91 static cl::opt<DefaultOnOff>
92 DarwinGDBCompat("darwin-gdb-compat", cl::Hidden,
93 cl::desc("Compatibility with Darwin gdb."),
94 cl::values(clEnumVal(Default, "Default for platform"),
95 clEnumVal(Enable, "Enabled"),
96 clEnumVal(Disable, "Disabled"), clEnumValEnd),
99 static cl::opt<DefaultOnOff>
100 SplitDwarf("split-dwarf", cl::Hidden,
101 cl::desc("Output prototype dwarf split debug info."),
102 cl::values(clEnumVal(Default, "Default for platform"),
103 clEnumVal(Enable, "Enabled"),
104 clEnumVal(Disable, "Disabled"), clEnumValEnd),
108 const char *const DWARFGroupName = "DWARF Emission";
109 const char *const DbgTimerName = "DWARF Debug Writer";
111 struct CompareFirst {
112 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
113 return lhs.first < rhs.first;
116 } // end anonymous namespace
118 //===----------------------------------------------------------------------===//
120 // Configuration values for initial hash set sizes (log2).
122 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
126 DIType DbgVariable::getType() const {
127 DIType Ty = Var.getType();
128 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
129 // addresses instead.
130 if (Var.isBlockByrefVariable()) {
131 /* Byref variables, in Blocks, are declared by the programmer as
132 "SomeType VarName;", but the compiler creates a
133 __Block_byref_x_VarName struct, and gives the variable VarName
134 either the struct, or a pointer to the struct, as its type. This
135 is necessary for various behind-the-scenes things the compiler
136 needs to do with by-reference variables in blocks.
138 However, as far as the original *programmer* is concerned, the
139 variable should still have type 'SomeType', as originally declared.
141 The following function dives into the __Block_byref_x_VarName
142 struct to find the original type of the variable. This will be
143 passed back to the code generating the type for the Debug
144 Information Entry for the variable 'VarName'. 'VarName' will then
145 have the original type 'SomeType' in its debug information.
147 The original type 'SomeType' will be the type of the field named
148 'VarName' inside the __Block_byref_x_VarName struct.
150 NOTE: In order for this to not completely fail on the debugger
151 side, the Debug Information Entry for the variable VarName needs to
152 have a DW_AT_location that tells the debugger how to unwind through
153 the pointers and __Block_byref_x_VarName struct to find the actual
154 value of the variable. The function addBlockByrefType does this. */
156 uint16_t tag = Ty.getTag();
158 if (tag == dwarf::DW_TAG_pointer_type) {
159 DIDerivedType DTy = DIDerivedType(Ty);
160 subType = DTy.getTypeDerivedFrom();
163 DICompositeType blockStruct = DICompositeType(subType);
164 DIArray Elements = blockStruct.getTypeArray();
166 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
167 DIDescriptor Element = Elements.getElement(i);
168 DIDerivedType DT = DIDerivedType(Element);
169 if (getName() == DT.getName())
170 return (DT.getTypeDerivedFrom());
176 } // end llvm namespace
178 /// Return Dwarf Version by checking module flags.
179 static unsigned getDwarfVersionFromModule(const Module *M) {
180 Value *Val = M->getModuleFlag("Dwarf Version");
182 return dwarf::DWARF_VERSION;
183 return cast<ConstantInt>(Val)->getZExtValue();
186 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
187 : Asm(A), MMI(Asm->MMI), FirstCU(0),
188 AbbreviationsSet(InitAbbreviationsSetSize),
189 SourceIdMap(DIEValueAllocator),
190 PrevLabel(NULL), GlobalCUIndexCount(0),
191 InfoHolder(A, &AbbreviationsSet, &Abbreviations, "info_string",
193 SkeletonAbbrevSet(InitAbbreviationsSetSize),
194 SkeletonHolder(A, &SkeletonAbbrevSet, &SkeletonAbbrevs, "skel_string",
197 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
198 DwarfStrSectionSym = TextSectionSym = 0;
199 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
200 DwarfAddrSectionSym = 0;
201 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
202 FunctionBeginSym = FunctionEndSym = 0;
204 // Turn on accelerator tables and older gdb compatibility
206 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
207 if (DarwinGDBCompat == Default) {
209 IsDarwinGDBCompat = true;
211 IsDarwinGDBCompat = false;
213 IsDarwinGDBCompat = DarwinGDBCompat == Enable ? true : false;
215 if (DwarfAccelTables == Default) {
217 HasDwarfAccelTables = true;
219 HasDwarfAccelTables = false;
221 HasDwarfAccelTables = DwarfAccelTables == Enable ? true : false;
223 if (SplitDwarf == Default)
224 HasSplitDwarf = false;
226 HasSplitDwarf = SplitDwarf == Enable ? true : false;
228 DwarfVersion = getDwarfVersionFromModule(MMI->getModule());
231 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
235 DwarfDebug::~DwarfDebug() {
238 // Switch to the specified MCSection and emit an assembler
239 // temporary label to it if SymbolStem is specified.
240 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
241 const char *SymbolStem = 0) {
242 Asm->OutStreamer.SwitchSection(Section);
243 if (!SymbolStem) return 0;
245 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
246 Asm->OutStreamer.EmitLabel(TmpSym);
250 MCSymbol *DwarfUnits::getStringPoolSym() {
251 return Asm->GetTempSymbol(StringPref);
254 MCSymbol *DwarfUnits::getStringPoolEntry(StringRef Str) {
255 std::pair<MCSymbol*, unsigned> &Entry =
256 StringPool.GetOrCreateValue(Str).getValue();
257 if (Entry.first) return Entry.first;
259 Entry.second = NextStringPoolNumber++;
260 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
263 unsigned DwarfUnits::getStringPoolIndex(StringRef Str) {
264 std::pair<MCSymbol*, unsigned> &Entry =
265 StringPool.GetOrCreateValue(Str).getValue();
266 if (Entry.first) return Entry.second;
268 Entry.second = NextStringPoolNumber++;
269 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
273 unsigned DwarfUnits::getAddrPoolIndex(const MCSymbol *Sym) {
274 return getAddrPoolIndex(MCSymbolRefExpr::Create(Sym, Asm->OutContext));
277 unsigned DwarfUnits::getAddrPoolIndex(const MCExpr *Sym) {
278 std::pair<DenseMap<const MCExpr *, unsigned>::iterator, bool> P =
279 AddressPool.insert(std::make_pair(Sym, NextAddrPoolNumber));
281 ++NextAddrPoolNumber;
282 return P.first->second;
285 // Define a unique number for the abbreviation.
287 void DwarfUnits::assignAbbrevNumber(DIEAbbrev &Abbrev) {
288 // Check the set for priors.
289 DIEAbbrev *InSet = AbbreviationsSet->GetOrInsertNode(&Abbrev);
291 // If it's newly added.
292 if (InSet == &Abbrev) {
293 // Add to abbreviation list.
294 Abbreviations->push_back(&Abbrev);
296 // Assign the vector position + 1 as its number.
297 Abbrev.setNumber(Abbreviations->size());
299 // Assign existing abbreviation number.
300 Abbrev.setNumber(InSet->getNumber());
304 static bool isObjCClass(StringRef Name) {
305 return Name.startswith("+") || Name.startswith("-");
308 static bool hasObjCCategory(StringRef Name) {
309 if (!isObjCClass(Name)) return false;
311 size_t pos = Name.find(')');
312 if (pos != std::string::npos) {
313 if (Name[pos+1] != ' ') return false;
319 static void getObjCClassCategory(StringRef In, StringRef &Class,
320 StringRef &Category) {
321 if (!hasObjCCategory(In)) {
322 Class = In.slice(In.find('[') + 1, In.find(' '));
327 Class = In.slice(In.find('[') + 1, In.find('('));
328 Category = In.slice(In.find('[') + 1, In.find(' '));
332 static StringRef getObjCMethodName(StringRef In) {
333 return In.slice(In.find(' ') + 1, In.find(']'));
336 // Add the various names to the Dwarf accelerator table names.
337 static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
339 if (!SP.isDefinition()) return;
341 TheCU->addAccelName(SP.getName(), Die);
343 // If the linkage name is different than the name, go ahead and output
344 // that as well into the name table.
345 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
346 TheCU->addAccelName(SP.getLinkageName(), Die);
348 // If this is an Objective-C selector name add it to the ObjC accelerator
350 if (isObjCClass(SP.getName())) {
351 StringRef Class, Category;
352 getObjCClassCategory(SP.getName(), Class, Category);
353 TheCU->addAccelObjC(Class, Die);
355 TheCU->addAccelObjC(Category, Die);
356 // Also add the base method name to the name table.
357 TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
361 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
362 // and DW_AT_high_pc attributes. If there are global variables in this
363 // scope then create and insert DIEs for these variables.
364 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
365 const MDNode *SPNode) {
366 DIE *SPDie = SPCU->getDIE(SPNode);
368 assert(SPDie && "Unable to find subprogram DIE!");
369 DISubprogram SP(SPNode);
371 // If we're updating an abstract DIE, then we will be adding the children and
372 // object pointer later on. But what we don't want to do is process the
373 // concrete DIE twice.
374 DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode);
376 bool InSameCU = (AbsSPDIE->getCompileUnit() == SPCU->getCUDie());
377 // Pick up abstract subprogram DIE.
378 SPDie = new DIE(dwarf::DW_TAG_subprogram);
379 // If AbsSPDIE belongs to a different CU, use DW_FORM_ref_addr instead of
381 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
382 InSameCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
386 DISubprogram SPDecl = SP.getFunctionDeclaration();
387 if (!SPDecl.isSubprogram()) {
388 // There is not any need to generate specification DIE for a function
389 // defined at compile unit level. If a function is defined inside another
390 // function then gdb prefers the definition at top level and but does not
391 // expect specification DIE in parent function. So avoid creating
392 // specification DIE for a function defined inside a function.
393 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
394 !SP.getContext().isFile() &&
395 !isSubprogramContext(SP.getContext())) {
396 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
399 DICompositeType SPTy = SP.getType();
400 DIArray Args = SPTy.getTypeArray();
401 uint16_t SPTag = SPTy.getTag();
402 if (SPTag == dwarf::DW_TAG_subroutine_type)
403 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
404 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
405 DIType ATy = DIType(Args.getElement(i));
406 SPCU->addType(Arg, ATy);
407 if (ATy.isArtificial())
408 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
409 if (ATy.isObjectPointer())
410 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer,
411 dwarf::DW_FORM_ref4, Arg);
412 SPDie->addChild(Arg);
414 DIE *SPDeclDie = SPDie;
415 SPDie = new DIE(dwarf::DW_TAG_subprogram);
416 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification,
417 dwarf::DW_FORM_ref4, SPDeclDie);
423 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc,
424 Asm->GetTempSymbol("func_begin",
425 Asm->getFunctionNumber()));
426 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc,
427 Asm->GetTempSymbol("func_end",
428 Asm->getFunctionNumber()));
429 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
430 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
431 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
433 // Add name to the name table, we do this here because we're guaranteed
434 // to have concrete versions of our DW_TAG_subprogram nodes.
435 addSubprogramNames(SPCU, SP, SPDie);
440 // Construct new DW_TAG_lexical_block for this scope and attach
441 // DW_AT_low_pc/DW_AT_high_pc labels.
442 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
443 LexicalScope *Scope) {
444 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
445 if (Scope->isAbstractScope())
448 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
452 // If we have multiple ranges, emit them into the range section.
453 if (Ranges.size() > 1) {
454 // .debug_range section has not been laid out yet. Emit offset in
455 // .debug_range as a uint, size 4, for now. emitDIE will handle
456 // DW_AT_ranges appropriately.
457 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
458 DebugRangeSymbols.size()
459 * Asm->getDataLayout().getPointerSize());
460 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
461 RE = Ranges.end(); RI != RE; ++RI) {
462 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
463 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
466 // Terminate the range list.
467 DebugRangeSymbols.push_back(NULL);
468 DebugRangeSymbols.push_back(NULL);
472 // Construct the address range for this DIE.
473 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
474 MCSymbol *Start = getLabelBeforeInsn(RI->first);
475 MCSymbol *End = getLabelAfterInsn(RI->second);
477 if (End == 0) return 0;
479 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
480 assert(End->isDefined() && "Invalid end label for an inlined scope!");
482 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
483 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
488 // This scope represents inlined body of a function. Construct DIE to
489 // represent this concrete inlined copy of the function.
490 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
491 LexicalScope *Scope) {
492 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
493 assert(Ranges.empty() == false &&
494 "LexicalScope does not have instruction markers!");
496 if (!Scope->getScopeNode())
498 DIScope DS(Scope->getScopeNode());
499 DISubprogram InlinedSP = getDISubprogram(DS);
500 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
502 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
506 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
507 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
508 dwarf::DW_FORM_ref4, OriginDIE);
510 if (Ranges.size() > 1) {
511 // .debug_range section has not been laid out yet. Emit offset in
512 // .debug_range as a uint, size 4, for now. emitDIE will handle
513 // DW_AT_ranges appropriately.
514 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
515 DebugRangeSymbols.size()
516 * Asm->getDataLayout().getPointerSize());
517 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
518 RE = Ranges.end(); RI != RE; ++RI) {
519 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
520 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
522 DebugRangeSymbols.push_back(NULL);
523 DebugRangeSymbols.push_back(NULL);
525 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
526 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
527 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
529 if (StartLabel == 0 || EndLabel == 0)
530 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
532 assert(StartLabel->isDefined() &&
533 "Invalid starting label for an inlined scope!");
534 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
536 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
537 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
540 InlinedSubprogramDIEs.insert(OriginDIE);
542 // Add the call site information to the DIE.
543 DILocation DL(Scope->getInlinedAt());
544 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
545 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
546 TheCU->getUniqueID()));
547 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
549 // Track the start label for this inlined function.
550 //.debug_inlined section specification does not clearly state how
551 // to emit inlined scopes that are split into multiple instruction ranges.
552 // For now, use the first instruction range and emit low_pc/high_pc pair and
553 // corresponding the .debug_inlined section entry for this pair.
554 if (Asm->MAI->doesDwarfUseInlineInfoSection()) {
555 MCSymbol *StartLabel = getLabelBeforeInsn(Ranges.begin()->first);
556 InlineInfoMap::iterator I = InlineInfo.find(InlinedSP);
558 if (I == InlineInfo.end()) {
559 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
560 InlinedSPNodes.push_back(InlinedSP);
562 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
565 // Add name to the name table, we do this here because we're guaranteed
566 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
567 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
572 // Construct a DIE for this scope.
573 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
574 if (!Scope || !Scope->getScopeNode())
577 DIScope DS(Scope->getScopeNode());
578 // Early return to avoid creating dangling variable|scope DIEs.
579 if (!Scope->getInlinedAt() && DS.isSubprogram() && Scope->isAbstractScope() &&
583 SmallVector<DIE *, 8> Children;
584 DIE *ObjectPointer = NULL;
586 // Collect arguments for current function.
587 if (LScopes.isCurrentFunctionScope(Scope))
588 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
589 if (DbgVariable *ArgDV = CurrentFnArguments[i])
591 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope())) {
592 Children.push_back(Arg);
593 if (ArgDV->isObjectPointer()) ObjectPointer = Arg;
596 // Collect lexical scope children first.
597 const SmallVectorImpl<DbgVariable *> &Variables =ScopeVariables.lookup(Scope);
598 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
600 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope())) {
601 Children.push_back(Variable);
602 if (Variables[i]->isObjectPointer()) ObjectPointer = Variable;
604 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
605 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
606 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
607 Children.push_back(Nested);
608 DIE *ScopeDIE = NULL;
609 if (Scope->getInlinedAt())
610 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
611 else if (DS.isSubprogram()) {
612 ProcessedSPNodes.insert(DS);
613 if (Scope->isAbstractScope()) {
614 ScopeDIE = TheCU->getDIE(DS);
615 // Note down abstract DIE.
617 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
620 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
623 // There is no need to emit empty lexical block DIE.
624 std::pair<ImportedEntityMap::const_iterator,
625 ImportedEntityMap::const_iterator> Range = std::equal_range(
626 ScopesWithImportedEntities.begin(), ScopesWithImportedEntities.end(),
627 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode*)0),
629 if (Children.empty() && Range.first == Range.second)
631 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
632 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
634 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
637 if (!ScopeDIE) return NULL;
640 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
641 E = Children.end(); I != E; ++I)
642 ScopeDIE->addChild(*I);
644 if (DS.isSubprogram() && ObjectPointer != NULL)
645 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer,
646 dwarf::DW_FORM_ref4, ObjectPointer);
648 if (DS.isSubprogram())
649 TheCU->addPubTypes(DISubprogram(DS));
654 // Look up the source id with the given directory and source file names.
655 // If none currently exists, create a new id and insert it in the
656 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
658 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName,
659 StringRef DirName, unsigned CUID) {
660 // If we use .loc in assembly, we can't separate .file entries according to
661 // compile units. Thus all files will belong to the default compile unit.
662 if (Asm->TM.hasMCUseLoc() &&
663 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer)
666 // If FE did not provide a file name, then assume stdin.
667 if (FileName.empty())
668 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
670 // TODO: this might not belong here. See if we can factor this better.
671 if (DirName == CompilationDir)
674 // FileIDCUMap stores the current ID for the given compile unit.
675 unsigned SrcId = FileIDCUMap[CUID] + 1;
677 // We look up the CUID/file/dir by concatenating them with a zero byte.
678 SmallString<128> NamePair;
679 NamePair += utostr(CUID);
682 NamePair += '\0'; // Zero bytes are not allowed in paths.
683 NamePair += FileName;
685 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
686 if (Ent.getValue() != SrcId)
687 return Ent.getValue();
689 FileIDCUMap[CUID] = SrcId;
690 // Print out a .file directive to specify files for .loc directives.
691 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
696 // Create new CompileUnit for the given metadata node with tag
697 // DW_TAG_compile_unit.
698 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
699 DICompileUnit DIUnit(N);
700 StringRef FN = DIUnit.getFilename();
701 CompilationDir = DIUnit.getDirectory();
703 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
704 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
705 DIUnit.getLanguage(), Die, N, Asm,
708 FileIDCUMap[NewCU->getUniqueID()] = 0;
709 // Call this to emit a .file directive if it wasn't emitted for the source
710 // file this CU comes from yet.
711 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
713 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
714 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
715 DIUnit.getLanguage());
716 NewCU->addString(Die, dwarf::DW_AT_name, FN);
718 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
719 // into an entity. We're using 0 (or a NULL label) for this. For
720 // split dwarf it's in the skeleton CU so omit it here.
721 if (!useSplitDwarf())
722 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
724 // Define start line table label for each Compile Unit.
725 MCSymbol *LineTableStartSym = Asm->GetTempSymbol("line_table_start",
726 NewCU->getUniqueID());
727 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
728 NewCU->getUniqueID());
730 // Use a single line table if we are using .loc and generating assembly.
732 (Asm->TM.hasMCUseLoc() &&
733 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer) ||
734 (NewCU->getUniqueID() == 0);
736 // DW_AT_stmt_list is a offset of line number information for this
737 // compile unit in debug_line section. For split dwarf this is
738 // left in the skeleton CU and so not included.
739 // The line table entries are not always emitted in assembly, so it
740 // is not okay to use line_table_start here.
741 if (!useSplitDwarf()) {
742 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
743 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
745 Asm->GetTempSymbol("section_line") : LineTableStartSym);
746 else if (UseTheFirstCU)
747 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
749 NewCU->addDelta(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
750 LineTableStartSym, DwarfLineSectionSym);
753 // If we're using split dwarf the compilation dir is going to be in the
754 // skeleton CU and so we don't need to duplicate it here.
755 if (!useSplitDwarf() && !CompilationDir.empty())
756 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
757 if (DIUnit.isOptimized())
758 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
760 StringRef Flags = DIUnit.getFlags();
762 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
764 if (unsigned RVer = DIUnit.getRunTimeVersion())
765 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
766 dwarf::DW_FORM_data1, RVer);
771 InfoHolder.addUnit(NewCU);
773 CUMap.insert(std::make_pair(N, NewCU));
777 // Construct subprogram DIE.
778 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
780 CompileUnit *&CURef = SPMap[N];
786 if (!SP.isDefinition())
787 // This is a method declaration which will be handled while constructing
791 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
794 TheCU->insertDIE(N, SubprogramDie);
796 // Add to context owner.
797 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
799 // Expose as global, if requested.
800 if (GenerateDwarfPubNamesSection)
801 TheCU->addGlobalName(SP.getName(), SubprogramDie);
804 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
806 DIImportedEntity Module(N);
807 if (!Module.Verify())
809 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
810 constructImportedEntityDIE(TheCU, Module, D);
813 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU, const MDNode *N,
815 DIImportedEntity Module(N);
816 if (!Module.Verify())
818 return constructImportedEntityDIE(TheCU, Module, Context);
821 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
822 const DIImportedEntity &Module,
824 assert(Module.Verify() &&
825 "Use one of the MDNode * overloads to handle invalid metadata");
826 assert(Context && "Should always have a context for an imported_module");
827 DIE *IMDie = new DIE(Module.getTag());
828 TheCU->insertDIE(Module, IMDie);
830 DIDescriptor Entity = Module.getEntity();
831 if (Entity.isNameSpace())
832 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
833 else if (Entity.isSubprogram())
834 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
835 else if (Entity.isType())
836 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
838 EntityDie = TheCU->getDIE(Entity);
839 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
840 Module.getContext().getDirectory(),
841 TheCU->getUniqueID());
842 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, 0, FileID);
843 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, 0, Module.getLineNumber());
844 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, dwarf::DW_FORM_ref4,
846 StringRef Name = Module.getName();
848 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
849 Context->addChild(IMDie);
852 // Emit all Dwarf sections that should come prior to the content. Create
853 // global DIEs and emit initial debug info sections. This is invoked by
854 // the target AsmPrinter.
855 void DwarfDebug::beginModule() {
856 if (DisableDebugInfoPrinting)
859 const Module *M = MMI->getModule();
861 // If module has named metadata anchors then use them, otherwise scan the
862 // module using debug info finder to collect debug info.
863 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
867 // Emit initial sections so we can reference labels later.
870 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
871 DICompileUnit CUNode(CU_Nodes->getOperand(i));
872 CompileUnit *CU = constructCompileUnit(CUNode);
873 DIArray ImportedEntities = CUNode.getImportedEntities();
874 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
875 ScopesWithImportedEntities.push_back(std::make_pair(
876 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
877 ImportedEntities.getElement(i)));
878 std::sort(ScopesWithImportedEntities.begin(),
879 ScopesWithImportedEntities.end(), CompareFirst());
880 DIArray GVs = CUNode.getGlobalVariables();
881 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
882 CU->createGlobalVariableDIE(GVs.getElement(i));
883 DIArray SPs = CUNode.getSubprograms();
884 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
885 constructSubprogramDIE(CU, SPs.getElement(i));
886 DIArray EnumTypes = CUNode.getEnumTypes();
887 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
888 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
889 DIArray RetainedTypes = CUNode.getRetainedTypes();
890 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
891 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
892 // Emit imported_modules last so that the relevant context is already
894 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
895 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
898 // Tell MMI that we have debug info.
899 MMI->setDebugInfoAvailability(true);
901 // Prime section data.
902 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
905 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
906 void DwarfDebug::computeInlinedDIEs() {
907 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
908 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
909 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
911 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
913 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
914 AE = AbstractSPDies.end(); AI != AE; ++AI) {
915 DIE *ISP = AI->second;
916 if (InlinedSubprogramDIEs.count(ISP))
918 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
922 // Collect info for variables that were optimized out.
923 void DwarfDebug::collectDeadVariables() {
924 const Module *M = MMI->getModule();
925 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
927 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
928 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
929 DICompileUnit TheCU(CU_Nodes->getOperand(i));
930 DIArray Subprograms = TheCU.getSubprograms();
931 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
932 DISubprogram SP(Subprograms.getElement(i));
933 if (ProcessedSPNodes.count(SP) != 0) continue;
934 if (!SP.isSubprogram()) continue;
935 if (!SP.isDefinition()) continue;
936 DIArray Variables = SP.getVariables();
937 if (Variables.getNumElements() == 0) continue;
939 LexicalScope *Scope =
940 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
941 DeadFnScopeMap[SP] = Scope;
943 // Construct subprogram DIE and add variables DIEs.
944 CompileUnit *SPCU = CUMap.lookup(TheCU);
945 assert(SPCU && "Unable to find Compile Unit!");
946 constructSubprogramDIE(SPCU, SP);
947 DIE *ScopeDIE = SPCU->getDIE(SP);
948 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
949 DIVariable DV(Variables.getElement(vi));
950 if (!DV.isVariable()) continue;
951 DbgVariable NewVar(DV, NULL);
952 if (DIE *VariableDIE =
953 SPCU->constructVariableDIE(&NewVar, Scope->isAbstractScope()))
954 ScopeDIE->addChild(VariableDIE);
959 DeleteContainerSeconds(DeadFnScopeMap);
962 // Type Signature [7.27] and ODR Hash code.
964 /// \brief Grabs the string in whichever attribute is passed in and returns
965 /// a reference to it. Returns "" if the attribute doesn't exist.
966 static StringRef getDIEStringAttr(DIE *Die, unsigned Attr) {
967 DIEValue *V = Die->findAttribute(Attr);
969 if (DIEString *S = dyn_cast_or_null<DIEString>(V))
970 return S->getString();
972 return StringRef("");
975 /// Return true if the current DIE is contained within an anonymous namespace.
976 static bool isContainedInAnonNamespace(DIE *Die) {
977 DIE *Parent = Die->getParent();
980 if (Parent->getTag() == dwarf::DW_TAG_namespace &&
981 getDIEStringAttr(Parent, dwarf::DW_AT_name) == "")
983 Parent = Parent->getParent();
989 /// Test if the current CU language is C++ and that we have
990 /// a named type that is not contained in an anonymous namespace.
991 static bool shouldAddODRHash(CompileUnit *CU, DIE *Die) {
992 return CU->getLanguage() == dwarf::DW_LANG_C_plus_plus &&
993 getDIEStringAttr(Die, dwarf::DW_AT_name) != "" &&
994 !isContainedInAnonNamespace(Die);
997 void DwarfDebug::finalizeModuleInfo() {
998 // Collect info for variables that were optimized out.
999 collectDeadVariables();
1001 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1002 computeInlinedDIEs();
1004 // Split out type units and conditionally add an ODR tag to the split
1006 // FIXME: Do type splitting.
1007 for (unsigned i = 0, e = TypeUnits.size(); i != e; ++i) {
1008 DIE *Die = TypeUnits[i];
1010 // If we've requested ODR hashes and it's applicable for an ODR hash then
1011 // add the ODR signature now.
1012 // FIXME: This should be added onto the type unit, not the type, but this
1013 // works as an intermediate stage.
1014 if (GenerateODRHash && shouldAddODRHash(CUMap.begin()->second, Die))
1015 CUMap.begin()->second->addUInt(Die, dwarf::DW_AT_GNU_odr_signature,
1016 dwarf::DW_FORM_data8,
1017 Hash.computeDIEODRSignature(Die));
1020 // Handle anything that needs to be done on a per-cu basis.
1021 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
1023 CUI != CUE; ++CUI) {
1024 CompileUnit *TheCU = CUI->second;
1025 // Emit DW_AT_containing_type attribute to connect types with their
1026 // vtable holding type.
1027 TheCU->constructContainingTypeDIEs();
1029 // If we're splitting the dwarf out now that we've got the entire
1030 // CU then construct a skeleton CU based upon it.
1031 if (useSplitDwarf()) {
1033 if (GenerateCUHash) {
1035 ID = CUHash.computeCUSignature(TheCU->getCUDie());
1037 // This should be a unique identifier when we want to build .dwp files.
1038 TheCU->addUInt(TheCU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
1039 dwarf::DW_FORM_data8, ID);
1040 // Now construct the skeleton CU associated.
1041 CompileUnit *SkCU = constructSkeletonCU(CUI->first);
1042 // This should be a unique identifier when we want to build .dwp files.
1043 SkCU->addUInt(SkCU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
1044 dwarf::DW_FORM_data8, ID);
1048 // Compute DIE offsets and sizes.
1049 InfoHolder.computeSizeAndOffsets();
1050 if (useSplitDwarf())
1051 SkeletonHolder.computeSizeAndOffsets();
1054 void DwarfDebug::endSections() {
1055 // Standard sections final addresses.
1056 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1057 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
1058 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1059 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
1061 // End text sections.
1062 for (unsigned I = 0, E = SectionMap.size(); I != E; ++I) {
1063 Asm->OutStreamer.SwitchSection(SectionMap[I]);
1064 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", I+1));
1068 // Emit all Dwarf sections that should come after the content.
1069 void DwarfDebug::endModule() {
1071 if (!FirstCU) return;
1073 // End any existing sections.
1074 // TODO: Does this need to happen?
1077 // Finalize the debug info for the module.
1078 finalizeModuleInfo();
1080 if (!useSplitDwarf()) {
1081 // Emit all the DIEs into a debug info section.
1084 // Corresponding abbreviations into a abbrev section.
1085 emitAbbreviations();
1087 // Emit info into a debug loc section.
1090 // Emit info into a debug aranges section.
1093 // Emit info into a debug ranges section.
1096 // Emit info into a debug macinfo section.
1099 // Emit inline info.
1100 // TODO: When we don't need the option anymore we
1101 // can remove all of the code that this section
1103 if (useDarwinGDBCompat())
1104 emitDebugInlineInfo();
1106 // TODO: Fill this in for separated debug sections and separate
1107 // out information into new sections.
1109 // Emit the debug info section and compile units.
1113 // Corresponding abbreviations into a abbrev section.
1114 emitAbbreviations();
1115 emitDebugAbbrevDWO();
1117 // Emit info into a debug loc section.
1120 // Emit info into a debug aranges section.
1123 // Emit info into a debug ranges section.
1126 // Emit info into a debug macinfo section.
1129 // Emit DWO addresses.
1130 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1132 // Emit inline info.
1133 // TODO: When we don't need the option anymore we
1134 // can remove all of the code that this section
1136 if (useDarwinGDBCompat())
1137 emitDebugInlineInfo();
1140 // Emit info into the dwarf accelerator table sections.
1141 if (useDwarfAccelTables()) {
1144 emitAccelNamespaces();
1148 // Emit info into a debug pubnames section, if requested.
1149 if (GenerateDwarfPubNamesSection)
1150 emitDebugPubnames();
1152 // Emit info into a debug pubtypes section.
1153 // TODO: When we don't need the option anymore we can
1154 // remove all of the code that adds to the table.
1155 if (useDarwinGDBCompat())
1156 emitDebugPubTypes();
1158 // Finally emit string information into a string table.
1160 if (useSplitDwarf())
1165 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1166 E = CUMap.end(); I != E; ++I)
1169 for (SmallVectorImpl<CompileUnit *>::iterator I = SkeletonCUs.begin(),
1170 E = SkeletonCUs.end(); I != E; ++I)
1173 // Reset these for the next Module if we have one.
1177 // Find abstract variable, if any, associated with Var.
1178 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1179 DebugLoc ScopeLoc) {
1180 LLVMContext &Ctx = DV->getContext();
1181 // More then one inlined variable corresponds to one abstract variable.
1182 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1183 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1185 return AbsDbgVariable;
1187 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1191 AbsDbgVariable = new DbgVariable(Var, NULL);
1192 addScopeVariable(Scope, AbsDbgVariable);
1193 AbstractVariables[Var] = AbsDbgVariable;
1194 return AbsDbgVariable;
1197 // If Var is a current function argument then add it to CurrentFnArguments list.
1198 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1199 DbgVariable *Var, LexicalScope *Scope) {
1200 if (!LScopes.isCurrentFunctionScope(Scope))
1202 DIVariable DV = Var->getVariable();
1203 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1205 unsigned ArgNo = DV.getArgNumber();
1209 size_t Size = CurrentFnArguments.size();
1211 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1212 // llvm::Function argument size is not good indicator of how many
1213 // arguments does the function have at source level.
1215 CurrentFnArguments.resize(ArgNo * 2);
1216 CurrentFnArguments[ArgNo - 1] = Var;
1220 // Collect variable information from side table maintained by MMI.
1222 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1223 SmallPtrSet<const MDNode *, 16> &Processed) {
1224 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1225 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1226 VE = VMap.end(); VI != VE; ++VI) {
1227 const MDNode *Var = VI->first;
1229 Processed.insert(Var);
1231 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1233 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1235 // If variable scope is not found then skip this variable.
1239 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1240 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
1241 RegVar->setFrameIndex(VP.first);
1242 if (!addCurrentFnArgument(MF, RegVar, Scope))
1243 addScopeVariable(Scope, RegVar);
1245 AbsDbgVariable->setFrameIndex(VP.first);
1249 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1251 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1252 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1253 return MI->getNumOperands() == 3 &&
1254 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1255 (MI->getOperand(1).isImm() ||
1256 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1259 // Get .debug_loc entry for the instruction range starting at MI.
1260 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1261 const MCSymbol *FLabel,
1262 const MCSymbol *SLabel,
1263 const MachineInstr *MI) {
1264 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1266 assert(MI->getNumOperands() == 3);
1267 if (MI->getOperand(0).isReg()) {
1268 MachineLocation MLoc;
1269 // If the second operand is an immediate, this is a
1270 // register-indirect address.
1271 if (!MI->getOperand(1).isImm())
1272 MLoc.set(MI->getOperand(0).getReg());
1274 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1275 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1277 if (MI->getOperand(0).isImm())
1278 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1279 if (MI->getOperand(0).isFPImm())
1280 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1281 if (MI->getOperand(0).isCImm())
1282 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1284 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1287 // Find variables for each lexical scope.
1289 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1290 SmallPtrSet<const MDNode *, 16> &Processed) {
1292 // Grab the variable info that was squirreled away in the MMI side-table.
1293 collectVariableInfoFromMMITable(MF, Processed);
1295 for (SmallVectorImpl<const MDNode*>::const_iterator
1296 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1298 const MDNode *Var = *UVI;
1299 if (Processed.count(Var))
1302 // History contains relevant DBG_VALUE instructions for Var and instructions
1304 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1305 if (History.empty())
1307 const MachineInstr *MInsn = History.front();
1310 LexicalScope *Scope = NULL;
1311 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1312 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1313 Scope = LScopes.getCurrentFunctionScope();
1314 else if (MDNode *IA = DV.getInlinedAt())
1315 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1317 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1318 // If variable scope is not found then skip this variable.
1322 Processed.insert(DV);
1323 assert(MInsn->isDebugValue() && "History must begin with debug value");
1324 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1325 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1326 if (!addCurrentFnArgument(MF, RegVar, Scope))
1327 addScopeVariable(Scope, RegVar);
1329 AbsVar->setMInsn(MInsn);
1331 // Simplify ranges that are fully coalesced.
1332 if (History.size() <= 1 || (History.size() == 2 &&
1333 MInsn->isIdenticalTo(History.back()))) {
1334 RegVar->setMInsn(MInsn);
1338 // Handle multiple DBG_VALUE instructions describing one variable.
1339 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1341 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1342 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1343 const MachineInstr *Begin = *HI;
1344 assert(Begin->isDebugValue() && "Invalid History entry");
1346 // Check if DBG_VALUE is truncating a range.
1347 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1348 && !Begin->getOperand(0).getReg())
1351 // Compute the range for a register location.
1352 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1353 const MCSymbol *SLabel = 0;
1356 // If Begin is the last instruction in History then its value is valid
1357 // until the end of the function.
1358 SLabel = FunctionEndSym;
1360 const MachineInstr *End = HI[1];
1361 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1362 << "\t" << *Begin << "\t" << *End << "\n");
1363 if (End->isDebugValue())
1364 SLabel = getLabelBeforeInsn(End);
1366 // End is a normal instruction clobbering the range.
1367 SLabel = getLabelAfterInsn(End);
1368 assert(SLabel && "Forgot label after clobber instruction");
1373 // The value is valid until the next DBG_VALUE or clobber.
1374 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1377 DotDebugLocEntries.push_back(DotDebugLocEntry());
1380 // Collect info for variables that were optimized out.
1381 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1382 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1383 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1384 DIVariable DV(Variables.getElement(i));
1385 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1387 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1388 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1392 // Return Label preceding the instruction.
1393 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1394 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1395 assert(Label && "Didn't insert label before instruction");
1399 // Return Label immediately following the instruction.
1400 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1401 return LabelsAfterInsn.lookup(MI);
1404 // Process beginning of an instruction.
1405 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1406 // Check if source location changes, but ignore DBG_VALUE locations.
1407 if (!MI->isDebugValue()) {
1408 DebugLoc DL = MI->getDebugLoc();
1409 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1412 if (DL == PrologEndLoc) {
1413 Flags |= DWARF2_FLAG_PROLOGUE_END;
1414 PrologEndLoc = DebugLoc();
1416 if (PrologEndLoc.isUnknown())
1417 Flags |= DWARF2_FLAG_IS_STMT;
1419 if (!DL.isUnknown()) {
1420 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1421 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1423 recordSourceLine(0, 0, 0, 0);
1427 // Insert labels where requested.
1428 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1429 LabelsBeforeInsn.find(MI);
1432 if (I == LabelsBeforeInsn.end())
1435 // Label already assigned.
1440 PrevLabel = MMI->getContext().CreateTempSymbol();
1441 Asm->OutStreamer.EmitLabel(PrevLabel);
1443 I->second = PrevLabel;
1446 // Process end of an instruction.
1447 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1448 // Don't create a new label after DBG_VALUE instructions.
1449 // They don't generate code.
1450 if (!MI->isDebugValue())
1453 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1454 LabelsAfterInsn.find(MI);
1457 if (I == LabelsAfterInsn.end())
1460 // Label already assigned.
1464 // We need a label after this instruction.
1466 PrevLabel = MMI->getContext().CreateTempSymbol();
1467 Asm->OutStreamer.EmitLabel(PrevLabel);
1469 I->second = PrevLabel;
1472 // Each LexicalScope has first instruction and last instruction to mark
1473 // beginning and end of a scope respectively. Create an inverse map that list
1474 // scopes starts (and ends) with an instruction. One instruction may start (or
1475 // end) multiple scopes. Ignore scopes that are not reachable.
1476 void DwarfDebug::identifyScopeMarkers() {
1477 SmallVector<LexicalScope *, 4> WorkList;
1478 WorkList.push_back(LScopes.getCurrentFunctionScope());
1479 while (!WorkList.empty()) {
1480 LexicalScope *S = WorkList.pop_back_val();
1482 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1483 if (!Children.empty())
1484 for (SmallVectorImpl<LexicalScope *>::const_iterator SI = Children.begin(),
1485 SE = Children.end(); SI != SE; ++SI)
1486 WorkList.push_back(*SI);
1488 if (S->isAbstractScope())
1491 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1494 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1495 RE = Ranges.end(); RI != RE; ++RI) {
1496 assert(RI->first && "InsnRange does not have first instruction!");
1497 assert(RI->second && "InsnRange does not have second instruction!");
1498 requestLabelBeforeInsn(RI->first);
1499 requestLabelAfterInsn(RI->second);
1504 // Get MDNode for DebugLoc's scope.
1505 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1506 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1507 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1508 return DL.getScope(Ctx);
1511 // Walk up the scope chain of given debug loc and find line number info
1512 // for the function.
1513 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1514 const MDNode *Scope = getScopeNode(DL, Ctx);
1515 DISubprogram SP = getDISubprogram(Scope);
1516 if (SP.isSubprogram()) {
1517 // Check for number of operands since the compatibility is
1519 if (SP->getNumOperands() > 19)
1520 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1522 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1528 // Gather pre-function debug information. Assumes being called immediately
1529 // after the function entry point has been emitted.
1530 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1531 if (!MMI->hasDebugInfo()) return;
1532 LScopes.initialize(*MF);
1533 if (LScopes.empty()) return;
1534 identifyScopeMarkers();
1536 // Set DwarfCompileUnitID in MCContext to the Compile Unit this function
1538 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1539 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1540 assert(TheCU && "Unable to find compile unit!");
1541 if (Asm->TM.hasMCUseLoc() &&
1542 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer)
1543 // Use a single line table if we are using .loc and generating assembly.
1544 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1546 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1548 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1549 Asm->getFunctionNumber());
1550 // Assumes in correct section after the entry point.
1551 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1553 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1555 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1556 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1557 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1559 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1561 bool AtBlockEntry = true;
1562 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1564 const MachineInstr *MI = II;
1566 if (MI->isDebugValue()) {
1567 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1569 // Keep track of user variables.
1571 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1573 // Variable is in a register, we need to check for clobbers.
1574 if (isDbgValueInDefinedReg(MI))
1575 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1577 // Check the history of this variable.
1578 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1579 if (History.empty()) {
1580 UserVariables.push_back(Var);
1581 // The first mention of a function argument gets the FunctionBeginSym
1582 // label, so arguments are visible when breaking at function entry.
1584 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1585 DISubprogram(getDISubprogram(DV.getContext()))
1586 .describes(MF->getFunction()))
1587 LabelsBeforeInsn[MI] = FunctionBeginSym;
1589 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1590 const MachineInstr *Prev = History.back();
1591 if (Prev->isDebugValue()) {
1592 // Coalesce identical entries at the end of History.
1593 if (History.size() >= 2 &&
1594 Prev->isIdenticalTo(History[History.size() - 2])) {
1595 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1597 << "\t" << *History[History.size() - 2] << "\n");
1601 // Terminate old register assignments that don't reach MI;
1602 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1603 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1604 isDbgValueInDefinedReg(Prev)) {
1605 // Previous register assignment needs to terminate at the end of
1607 MachineBasicBlock::const_iterator LastMI =
1608 PrevMBB->getLastNonDebugInstr();
1609 if (LastMI == PrevMBB->end()) {
1610 // Drop DBG_VALUE for empty range.
1611 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1612 << "\t" << *Prev << "\n");
1614 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1615 // Terminate after LastMI.
1616 History.push_back(LastMI);
1620 History.push_back(MI);
1622 // Not a DBG_VALUE instruction.
1624 AtBlockEntry = false;
1626 // First known non-DBG_VALUE and non-frame setup location marks
1627 // the beginning of the function body.
1628 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1629 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1630 PrologEndLoc = MI->getDebugLoc();
1632 // Check if the instruction clobbers any registers with debug vars.
1633 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1634 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1635 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1637 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1638 AI.isValid(); ++AI) {
1640 const MDNode *Var = LiveUserVar[Reg];
1643 // Reg is now clobbered.
1644 LiveUserVar[Reg] = 0;
1646 // Was MD last defined by a DBG_VALUE referring to Reg?
1647 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1648 if (HistI == DbgValues.end())
1650 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1651 if (History.empty())
1653 const MachineInstr *Prev = History.back();
1654 // Sanity-check: Register assignments are terminated at the end of
1656 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1658 // Is the variable still in Reg?
1659 if (!isDbgValueInDefinedReg(Prev) ||
1660 Prev->getOperand(0).getReg() != Reg)
1662 // Var is clobbered. Make sure the next instruction gets a label.
1663 History.push_back(MI);
1670 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1672 SmallVectorImpl<const MachineInstr*> &History = I->second;
1673 if (History.empty())
1676 // Make sure the final register assignments are terminated.
1677 const MachineInstr *Prev = History.back();
1678 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1679 const MachineBasicBlock *PrevMBB = Prev->getParent();
1680 MachineBasicBlock::const_iterator LastMI =
1681 PrevMBB->getLastNonDebugInstr();
1682 if (LastMI == PrevMBB->end())
1683 // Drop DBG_VALUE for empty range.
1685 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1686 // Terminate after LastMI.
1687 History.push_back(LastMI);
1690 // Request labels for the full history.
1691 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1692 const MachineInstr *MI = History[i];
1693 if (MI->isDebugValue())
1694 requestLabelBeforeInsn(MI);
1696 requestLabelAfterInsn(MI);
1700 PrevInstLoc = DebugLoc();
1701 PrevLabel = FunctionBeginSym;
1703 // Record beginning of function.
1704 if (!PrologEndLoc.isUnknown()) {
1705 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1706 MF->getFunction()->getContext());
1707 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1708 FnStartDL.getScope(MF->getFunction()->getContext()),
1709 // We'd like to list the prologue as "not statements" but GDB behaves
1710 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1711 DWARF2_FLAG_IS_STMT);
1715 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1716 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1717 DIVariable DV = Var->getVariable();
1718 // Variables with positive arg numbers are parameters.
1719 if (unsigned ArgNum = DV.getArgNumber()) {
1720 // Keep all parameters in order at the start of the variable list to ensure
1721 // function types are correct (no out-of-order parameters)
1723 // This could be improved by only doing it for optimized builds (unoptimized
1724 // builds have the right order to begin with), searching from the back (this
1725 // would catch the unoptimized case quickly), or doing a binary search
1726 // rather than linear search.
1727 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1728 while (I != Vars.end()) {
1729 unsigned CurNum = (*I)->getVariable().getArgNumber();
1730 // A local (non-parameter) variable has been found, insert immediately
1734 // A later indexed parameter has been found, insert immediately before it.
1735 if (CurNum > ArgNum)
1739 Vars.insert(I, Var);
1743 Vars.push_back(Var);
1746 // Gather and emit post-function debug information.
1747 void DwarfDebug::endFunction(const MachineFunction *MF) {
1748 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1750 // Define end label for subprogram.
1751 FunctionEndSym = Asm->GetTempSymbol("func_end",
1752 Asm->getFunctionNumber());
1753 // Assumes in correct section after the entry point.
1754 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1755 // Set DwarfCompileUnitID in MCContext to default value.
1756 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1758 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1759 collectVariableInfo(MF, ProcessedVars);
1761 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1762 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1763 assert(TheCU && "Unable to find compile unit!");
1765 // Construct abstract scopes.
1766 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1767 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1768 LexicalScope *AScope = AList[i];
1769 DISubprogram SP(AScope->getScopeNode());
1770 if (SP.isSubprogram()) {
1771 // Collect info for variables that were optimized out.
1772 DIArray Variables = SP.getVariables();
1773 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1774 DIVariable DV(Variables.getElement(i));
1775 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1777 // Check that DbgVariable for DV wasn't created earlier, when
1778 // findAbstractVariable() was called for inlined instance of DV.
1779 LLVMContext &Ctx = DV->getContext();
1780 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1781 if (AbstractVariables.lookup(CleanDV))
1783 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1784 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1787 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1788 constructScopeDIE(TheCU, AScope);
1791 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1793 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1794 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1797 for (ScopeVariablesMap::iterator
1798 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1799 DeleteContainerPointers(I->second);
1800 ScopeVariables.clear();
1801 DeleteContainerPointers(CurrentFnArguments);
1802 UserVariables.clear();
1804 AbstractVariables.clear();
1805 LabelsBeforeInsn.clear();
1806 LabelsAfterInsn.clear();
1810 // Register a source line with debug info. Returns the unique label that was
1811 // emitted and which provides correspondence to the source line list.
1812 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1818 DIDescriptor Scope(S);
1820 if (Scope.isCompileUnit()) {
1821 DICompileUnit CU(S);
1822 Fn = CU.getFilename();
1823 Dir = CU.getDirectory();
1824 } else if (Scope.isFile()) {
1826 Fn = F.getFilename();
1827 Dir = F.getDirectory();
1828 } else if (Scope.isSubprogram()) {
1830 Fn = SP.getFilename();
1831 Dir = SP.getDirectory();
1832 } else if (Scope.isLexicalBlockFile()) {
1833 DILexicalBlockFile DBF(S);
1834 Fn = DBF.getFilename();
1835 Dir = DBF.getDirectory();
1836 } else if (Scope.isLexicalBlock()) {
1837 DILexicalBlock DB(S);
1838 Fn = DB.getFilename();
1839 Dir = DB.getDirectory();
1841 llvm_unreachable("Unexpected scope info");
1843 Src = getOrCreateSourceID(Fn, Dir,
1844 Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1846 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1849 //===----------------------------------------------------------------------===//
1851 //===----------------------------------------------------------------------===//
1853 // Compute the size and offset of a DIE.
1855 DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1856 // Get the children.
1857 const std::vector<DIE *> &Children = Die->getChildren();
1859 // Record the abbreviation.
1860 assignAbbrevNumber(Die->getAbbrev());
1862 // Get the abbreviation for this DIE.
1863 unsigned AbbrevNumber = Die->getAbbrevNumber();
1864 const DIEAbbrev *Abbrev = Abbreviations->at(AbbrevNumber - 1);
1867 Die->setOffset(Offset);
1869 // Start the size with the size of abbreviation code.
1870 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1872 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1873 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1875 // Size the DIE attribute values.
1876 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1877 // Size attribute value.
1878 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1880 // Size the DIE children if any.
1881 if (!Children.empty()) {
1882 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1883 "Children flag not set");
1885 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1886 Offset = computeSizeAndOffset(Children[j], Offset);
1888 // End of children marker.
1889 Offset += sizeof(int8_t);
1892 Die->setSize(Offset - Die->getOffset());
1896 // Compute the size and offset of all the DIEs.
1897 void DwarfUnits::computeSizeAndOffsets() {
1898 // Offset from the beginning of debug info section.
1899 unsigned SecOffset = 0;
1900 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1901 E = CUs.end(); I != E; ++I) {
1902 (*I)->setDebugInfoOffset(SecOffset);
1904 sizeof(int32_t) + // Length of Compilation Unit Info
1905 sizeof(int16_t) + // DWARF version number
1906 sizeof(int32_t) + // Offset Into Abbrev. Section
1907 sizeof(int8_t); // Pointer Size (in bytes)
1909 unsigned EndOffset = computeSizeAndOffset((*I)->getCUDie(), Offset);
1910 SecOffset += EndOffset;
1914 // Emit initial Dwarf sections with a label at the start of each one.
1915 void DwarfDebug::emitSectionLabels() {
1916 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1918 // Dwarf sections base addresses.
1919 DwarfInfoSectionSym =
1920 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1921 DwarfAbbrevSectionSym =
1922 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1923 if (useSplitDwarf())
1924 DwarfAbbrevDWOSectionSym =
1925 emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
1926 "section_abbrev_dwo");
1927 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1929 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1930 emitSectionSym(Asm, MacroInfo);
1932 DwarfLineSectionSym =
1933 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1934 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1935 if (GenerateDwarfPubNamesSection)
1936 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1937 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1938 DwarfStrSectionSym =
1939 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1940 if (useSplitDwarf()) {
1941 DwarfStrDWOSectionSym =
1942 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1943 DwarfAddrSectionSym =
1944 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1946 DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1949 DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
1950 "section_debug_loc");
1952 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1953 emitSectionSym(Asm, TLOF.getDataSection());
1956 // Recursively emits a debug information entry.
1957 void DwarfDebug::emitDIE(DIE *Die, std::vector<DIEAbbrev *> *Abbrevs) {
1958 // Get the abbreviation for this DIE.
1959 unsigned AbbrevNumber = Die->getAbbrevNumber();
1960 const DIEAbbrev *Abbrev = Abbrevs->at(AbbrevNumber - 1);
1962 // Emit the code (index) for the abbreviation.
1963 if (Asm->isVerbose())
1964 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1965 Twine::utohexstr(Die->getOffset()) + ":0x" +
1966 Twine::utohexstr(Die->getSize()) + " " +
1967 dwarf::TagString(Abbrev->getTag()));
1968 Asm->EmitULEB128(AbbrevNumber);
1970 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1971 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1973 // Emit the DIE attribute values.
1974 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1975 unsigned Attr = AbbrevData[i].getAttribute();
1976 unsigned Form = AbbrevData[i].getForm();
1977 assert(Form && "Too many attributes for DIE (check abbreviation)");
1979 if (Asm->isVerbose())
1980 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1983 case dwarf::DW_AT_abstract_origin: {
1984 DIEEntry *E = cast<DIEEntry>(Values[i]);
1985 DIE *Origin = E->getEntry();
1986 unsigned Addr = Origin->getOffset();
1987 if (Form == dwarf::DW_FORM_ref_addr) {
1988 // For DW_FORM_ref_addr, output the offset from beginning of debug info
1989 // section. Origin->getOffset() returns the offset from start of the
1991 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1992 Addr += Holder.getCUOffset(Origin->getCompileUnit());
1994 Asm->OutStreamer.EmitIntValue(Addr,
1995 Form == dwarf::DW_FORM_ref_addr ? DIEEntry::getRefAddrSize(Asm) : 4);
1998 case dwarf::DW_AT_ranges: {
1999 // DW_AT_range Value encodes offset in debug_range section.
2000 DIEInteger *V = cast<DIEInteger>(Values[i]);
2002 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
2003 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
2007 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
2009 DwarfDebugRangeSectionSym,
2014 case dwarf::DW_AT_location: {
2015 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
2016 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2017 Asm->EmitLabelReference(L->getValue(), 4);
2019 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2021 Values[i]->EmitValue(Asm, Form);
2025 case dwarf::DW_AT_accessibility: {
2026 if (Asm->isVerbose()) {
2027 DIEInteger *V = cast<DIEInteger>(Values[i]);
2028 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2030 Values[i]->EmitValue(Asm, Form);
2034 // Emit an attribute using the defined form.
2035 Values[i]->EmitValue(Asm, Form);
2040 // Emit the DIE children if any.
2041 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2042 const std::vector<DIE *> &Children = Die->getChildren();
2044 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2045 emitDIE(Children[j], Abbrevs);
2047 if (Asm->isVerbose())
2048 Asm->OutStreamer.AddComment("End Of Children Mark");
2053 // Emit the various dwarf units to the unit section USection with
2054 // the abbreviations going into ASection.
2055 void DwarfUnits::emitUnits(DwarfDebug *DD,
2056 const MCSection *USection,
2057 const MCSection *ASection,
2058 const MCSymbol *ASectionSym) {
2059 Asm->OutStreamer.SwitchSection(USection);
2060 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
2061 E = CUs.end(); I != E; ++I) {
2062 CompileUnit *TheCU = *I;
2063 DIE *Die = TheCU->getCUDie();
2065 // Emit the compile units header.
2067 .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
2068 TheCU->getUniqueID()));
2070 // Emit size of content not including length itself
2071 unsigned ContentSize = Die->getSize() +
2072 sizeof(int16_t) + // DWARF version number
2073 sizeof(int32_t) + // Offset Into Abbrev. Section
2074 sizeof(int8_t); // Pointer Size (in bytes)
2076 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2077 Asm->EmitInt32(ContentSize);
2078 Asm->OutStreamer.AddComment("DWARF version number");
2079 Asm->EmitInt16(DD->getDwarfVersion());
2080 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2081 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
2083 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2084 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2086 DD->emitDIE(Die, Abbreviations);
2087 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
2088 TheCU->getUniqueID()));
2092 /// For a given compile unit DIE, returns offset from beginning of debug info.
2093 unsigned DwarfUnits::getCUOffset(DIE *Die) {
2094 assert(Die->getTag() == dwarf::DW_TAG_compile_unit &&
2095 "Input DIE should be compile unit in getCUOffset.");
2096 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(), E = CUs.end();
2098 CompileUnit *TheCU = *I;
2099 if (TheCU->getCUDie() == Die)
2100 return TheCU->getDebugInfoOffset();
2102 llvm_unreachable("The compile unit DIE should belong to CUs in DwarfUnits.");
2105 // Emit the debug info section.
2106 void DwarfDebug::emitDebugInfo() {
2107 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2109 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
2110 Asm->getObjFileLowering().getDwarfAbbrevSection(),
2111 DwarfAbbrevSectionSym);
2114 // Emit the abbreviation section.
2115 void DwarfDebug::emitAbbreviations() {
2116 if (!useSplitDwarf())
2117 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
2120 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2123 void DwarfDebug::emitAbbrevs(const MCSection *Section,
2124 std::vector<DIEAbbrev *> *Abbrevs) {
2125 // Check to see if it is worth the effort.
2126 if (!Abbrevs->empty()) {
2127 // Start the debug abbrev section.
2128 Asm->OutStreamer.SwitchSection(Section);
2130 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
2131 Asm->OutStreamer.EmitLabel(Begin);
2133 // For each abbrevation.
2134 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
2135 // Get abbreviation data
2136 const DIEAbbrev *Abbrev = Abbrevs->at(i);
2138 // Emit the abbrevations code (base 1 index.)
2139 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2141 // Emit the abbreviations data.
2145 // Mark end of abbreviations.
2146 Asm->EmitULEB128(0, "EOM(3)");
2148 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
2149 Asm->OutStreamer.EmitLabel(End);
2153 // Emit the last address of the section and the end of the line matrix.
2154 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2155 // Define last address of section.
2156 Asm->OutStreamer.AddComment("Extended Op");
2159 Asm->OutStreamer.AddComment("Op size");
2160 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2161 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2162 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2164 Asm->OutStreamer.AddComment("Section end label");
2166 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2167 Asm->getDataLayout().getPointerSize());
2169 // Mark end of matrix.
2170 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2176 // Emit visible names into a hashed accelerator table section.
2177 void DwarfDebug::emitAccelNames() {
2178 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2179 dwarf::DW_FORM_data4));
2180 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2181 E = CUMap.end(); I != E; ++I) {
2182 CompileUnit *TheCU = I->second;
2183 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
2184 for (StringMap<std::vector<DIE*> >::const_iterator
2185 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2186 StringRef Name = GI->getKey();
2187 const std::vector<DIE *> &Entities = GI->second;
2188 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2189 DE = Entities.end(); DI != DE; ++DI)
2190 AT.AddName(Name, (*DI));
2194 AT.FinalizeTable(Asm, "Names");
2195 Asm->OutStreamer.SwitchSection(
2196 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2197 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2198 Asm->OutStreamer.EmitLabel(SectionBegin);
2200 // Emit the full data.
2201 AT.Emit(Asm, SectionBegin, &InfoHolder);
2204 // Emit objective C classes and categories into a hashed accelerator table
2206 void DwarfDebug::emitAccelObjC() {
2207 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2208 dwarf::DW_FORM_data4));
2209 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2210 E = CUMap.end(); I != E; ++I) {
2211 CompileUnit *TheCU = I->second;
2212 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
2213 for (StringMap<std::vector<DIE*> >::const_iterator
2214 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2215 StringRef Name = GI->getKey();
2216 const std::vector<DIE *> &Entities = GI->second;
2217 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2218 DE = Entities.end(); DI != DE; ++DI)
2219 AT.AddName(Name, (*DI));
2223 AT.FinalizeTable(Asm, "ObjC");
2224 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2225 .getDwarfAccelObjCSection());
2226 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2227 Asm->OutStreamer.EmitLabel(SectionBegin);
2229 // Emit the full data.
2230 AT.Emit(Asm, SectionBegin, &InfoHolder);
2233 // Emit namespace dies into a hashed accelerator table.
2234 void DwarfDebug::emitAccelNamespaces() {
2235 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2236 dwarf::DW_FORM_data4));
2237 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2238 E = CUMap.end(); I != E; ++I) {
2239 CompileUnit *TheCU = I->second;
2240 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2241 for (StringMap<std::vector<DIE*> >::const_iterator
2242 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2243 StringRef Name = GI->getKey();
2244 const std::vector<DIE *> &Entities = GI->second;
2245 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2246 DE = Entities.end(); DI != DE; ++DI)
2247 AT.AddName(Name, (*DI));
2251 AT.FinalizeTable(Asm, "namespac");
2252 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2253 .getDwarfAccelNamespaceSection());
2254 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2255 Asm->OutStreamer.EmitLabel(SectionBegin);
2257 // Emit the full data.
2258 AT.Emit(Asm, SectionBegin, &InfoHolder);
2261 // Emit type dies into a hashed accelerator table.
2262 void DwarfDebug::emitAccelTypes() {
2263 std::vector<DwarfAccelTable::Atom> Atoms;
2264 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2265 dwarf::DW_FORM_data4));
2266 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
2267 dwarf::DW_FORM_data2));
2268 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
2269 dwarf::DW_FORM_data1));
2270 DwarfAccelTable AT(Atoms);
2271 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2272 E = CUMap.end(); I != E; ++I) {
2273 CompileUnit *TheCU = I->second;
2274 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2275 = TheCU->getAccelTypes();
2276 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2277 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2278 StringRef Name = GI->getKey();
2279 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2280 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2281 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2282 AT.AddName(Name, (*DI).first, (*DI).second);
2286 AT.FinalizeTable(Asm, "types");
2287 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2288 .getDwarfAccelTypesSection());
2289 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2290 Asm->OutStreamer.EmitLabel(SectionBegin);
2292 // Emit the full data.
2293 AT.Emit(Asm, SectionBegin, &InfoHolder);
2296 /// emitDebugPubnames - Emit visible names into a debug pubnames section.
2298 void DwarfDebug::emitDebugPubnames() {
2299 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2301 typedef DenseMap<const MDNode*, CompileUnit*> CUMapType;
2302 for (CUMapType::iterator I = CUMap.begin(), E = CUMap.end(); I != E; ++I) {
2303 CompileUnit *TheCU = I->second;
2304 unsigned ID = TheCU->getUniqueID();
2306 if (TheCU->getGlobalNames().empty())
2309 // Start the dwarf pubnames section.
2310 Asm->OutStreamer.SwitchSection(
2311 Asm->getObjFileLowering().getDwarfPubNamesSection());
2313 Asm->OutStreamer.AddComment("Length of Public Names Info");
2314 Asm->EmitLabelDifference(Asm->GetTempSymbol("pubnames_end", ID),
2315 Asm->GetTempSymbol("pubnames_begin", ID), 4);
2317 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", ID));
2319 Asm->OutStreamer.AddComment("DWARF Version");
2320 Asm->EmitInt16(DwarfVersion);
2322 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2323 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2324 DwarfInfoSectionSym);
2326 Asm->OutStreamer.AddComment("Compilation Unit Length");
2327 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(), ID),
2328 Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2331 const StringMap<DIE*> &Globals = TheCU->getGlobalNames();
2332 for (StringMap<DIE*>::const_iterator
2333 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2334 const char *Name = GI->getKeyData();
2335 const DIE *Entity = GI->second;
2337 Asm->OutStreamer.AddComment("DIE offset");
2338 Asm->EmitInt32(Entity->getOffset());
2340 if (Asm->isVerbose())
2341 Asm->OutStreamer.AddComment("External Name");
2342 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2345 Asm->OutStreamer.AddComment("End Mark");
2347 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", ID));
2351 void DwarfDebug::emitDebugPubTypes() {
2352 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2353 E = CUMap.end(); I != E; ++I) {
2354 CompileUnit *TheCU = I->second;
2355 // Start the dwarf pubtypes section.
2356 Asm->OutStreamer.SwitchSection(
2357 Asm->getObjFileLowering().getDwarfPubTypesSection());
2358 Asm->OutStreamer.AddComment("Length of Public Types Info");
2359 Asm->EmitLabelDifference(
2360 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2361 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2363 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2364 TheCU->getUniqueID()));
2366 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2367 Asm->EmitInt16(DwarfVersion);
2369 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2370 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2371 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(),
2372 TheCU->getUniqueID()),
2373 DwarfInfoSectionSym);
2375 Asm->OutStreamer.AddComment("Compilation Unit Length");
2376 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(),
2377 TheCU->getUniqueID()),
2378 Asm->GetTempSymbol(ISec->getLabelBeginName(),
2379 TheCU->getUniqueID()),
2382 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2383 for (StringMap<DIE*>::const_iterator
2384 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2385 const char *Name = GI->getKeyData();
2386 DIE *Entity = GI->second;
2388 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2389 Asm->EmitInt32(Entity->getOffset());
2391 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2392 // Emit the name with a terminating null byte.
2393 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2396 Asm->OutStreamer.AddComment("End Mark");
2398 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2399 TheCU->getUniqueID()));
2403 // Emit strings into a string section.
2404 void DwarfUnits::emitStrings(const MCSection *StrSection,
2405 const MCSection *OffsetSection = NULL,
2406 const MCSymbol *StrSecSym = NULL) {
2408 if (StringPool.empty()) return;
2410 // Start the dwarf str section.
2411 Asm->OutStreamer.SwitchSection(StrSection);
2413 // Get all of the string pool entries and put them in an array by their ID so
2414 // we can sort them.
2415 SmallVector<std::pair<unsigned,
2416 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2418 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2419 I = StringPool.begin(), E = StringPool.end();
2421 Entries.push_back(std::make_pair(I->second.second, &*I));
2423 array_pod_sort(Entries.begin(), Entries.end());
2425 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2426 // Emit a label for reference from debug information entries.
2427 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2429 // Emit the string itself with a terminating null byte.
2430 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2431 Entries[i].second->getKeyLength()+1));
2434 // If we've got an offset section go ahead and emit that now as well.
2435 if (OffsetSection) {
2436 Asm->OutStreamer.SwitchSection(OffsetSection);
2437 unsigned offset = 0;
2438 unsigned size = 4; // FIXME: DWARF64 is 8.
2439 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2440 Asm->OutStreamer.EmitIntValue(offset, size);
2441 offset += Entries[i].second->getKeyLength() + 1;
2446 // Emit strings into a string section.
2447 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2449 if (AddressPool.empty()) return;
2451 // Start the dwarf addr section.
2452 Asm->OutStreamer.SwitchSection(AddrSection);
2454 // Order the address pool entries by ID
2455 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2457 for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2458 E = AddressPool.end();
2460 Entries[I->second] = I->first;
2462 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2463 // Emit an expression for reference from debug information entries.
2464 if (const MCExpr *Expr = Entries[i])
2465 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2467 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2472 // Emit visible names into a debug str section.
2473 void DwarfDebug::emitDebugStr() {
2474 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2475 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2478 // Emit locations into the debug loc section.
2479 void DwarfDebug::emitDebugLoc() {
2480 if (DotDebugLocEntries.empty())
2483 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2484 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2486 DotDebugLocEntry &Entry = *I;
2487 if (I + 1 != DotDebugLocEntries.end())
2491 // Start the dwarf loc section.
2492 Asm->OutStreamer.SwitchSection(
2493 Asm->getObjFileLowering().getDwarfLocSection());
2494 unsigned char Size = Asm->getDataLayout().getPointerSize();
2495 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2497 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2498 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2499 I != E; ++I, ++index) {
2500 DotDebugLocEntry &Entry = *I;
2501 if (Entry.isMerged()) continue;
2502 if (Entry.isEmpty()) {
2503 Asm->OutStreamer.EmitIntValue(0, Size);
2504 Asm->OutStreamer.EmitIntValue(0, Size);
2505 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2507 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2508 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2509 DIVariable DV(Entry.getVariable());
2510 Asm->OutStreamer.AddComment("Loc expr size");
2511 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2512 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2513 Asm->EmitLabelDifference(end, begin, 2);
2514 Asm->OutStreamer.EmitLabel(begin);
2515 if (Entry.isInt()) {
2516 DIBasicType BTy(DV.getType());
2518 (BTy.getEncoding() == dwarf::DW_ATE_signed
2519 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2520 Asm->OutStreamer.AddComment("DW_OP_consts");
2521 Asm->EmitInt8(dwarf::DW_OP_consts);
2522 Asm->EmitSLEB128(Entry.getInt());
2524 Asm->OutStreamer.AddComment("DW_OP_constu");
2525 Asm->EmitInt8(dwarf::DW_OP_constu);
2526 Asm->EmitULEB128(Entry.getInt());
2528 } else if (Entry.isLocation()) {
2529 MachineLocation Loc = Entry.getLoc();
2530 if (!DV.hasComplexAddress())
2532 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2534 // Complex address entry.
2535 unsigned N = DV.getNumAddrElements();
2537 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2538 if (Loc.getOffset()) {
2540 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2541 Asm->OutStreamer.AddComment("DW_OP_deref");
2542 Asm->EmitInt8(dwarf::DW_OP_deref);
2543 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2544 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2545 Asm->EmitSLEB128(DV.getAddrElement(1));
2547 // If first address element is OpPlus then emit
2548 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2549 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2550 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2554 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2557 // Emit remaining complex address elements.
2558 for (; i < N; ++i) {
2559 uint64_t Element = DV.getAddrElement(i);
2560 if (Element == DIBuilder::OpPlus) {
2561 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2562 Asm->EmitULEB128(DV.getAddrElement(++i));
2563 } else if (Element == DIBuilder::OpDeref) {
2565 Asm->EmitInt8(dwarf::DW_OP_deref);
2567 llvm_unreachable("unknown Opcode found in complex address");
2571 // else ... ignore constant fp. There is not any good way to
2572 // to represent them here in dwarf.
2573 Asm->OutStreamer.EmitLabel(end);
2578 // Emit visible names into a debug aranges section.
2579 void DwarfDebug::emitDebugARanges() {
2580 // Start the dwarf aranges section.
2581 Asm->OutStreamer.SwitchSection(
2582 Asm->getObjFileLowering().getDwarfARangesSection());
2585 // Emit visible names into a debug ranges section.
2586 void DwarfDebug::emitDebugRanges() {
2587 // Start the dwarf ranges section.
2588 Asm->OutStreamer.SwitchSection(
2589 Asm->getObjFileLowering().getDwarfRangesSection());
2590 unsigned char Size = Asm->getDataLayout().getPointerSize();
2591 for (SmallVectorImpl<const MCSymbol *>::iterator
2592 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2595 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size);
2597 Asm->OutStreamer.EmitIntValue(0, Size);
2601 // Emit visible names into a debug macinfo section.
2602 void DwarfDebug::emitDebugMacInfo() {
2603 if (const MCSection *LineInfo =
2604 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2605 // Start the dwarf macinfo section.
2606 Asm->OutStreamer.SwitchSection(LineInfo);
2610 // Emit inline info using following format.
2612 // 1. length of section
2613 // 2. Dwarf version number
2616 // Entries (one "entry" for each function that was inlined):
2618 // 1. offset into __debug_str section for MIPS linkage name, if exists;
2619 // otherwise offset into __debug_str for regular function name.
2620 // 2. offset into __debug_str section for regular function name.
2621 // 3. an unsigned LEB128 number indicating the number of distinct inlining
2622 // instances for the function.
2624 // The rest of the entry consists of a {die_offset, low_pc} pair for each
2625 // inlined instance; the die_offset points to the inlined_subroutine die in the
2626 // __debug_info section, and the low_pc is the starting address for the
2627 // inlining instance.
2628 void DwarfDebug::emitDebugInlineInfo() {
2629 if (!Asm->MAI->doesDwarfUseInlineInfoSection())
2635 Asm->OutStreamer.SwitchSection(
2636 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2638 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2639 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2640 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2642 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2644 Asm->OutStreamer.AddComment("Dwarf Version");
2645 Asm->EmitInt16(DwarfVersion);
2646 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2647 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2649 for (SmallVectorImpl<const MDNode *>::iterator I = InlinedSPNodes.begin(),
2650 E = InlinedSPNodes.end(); I != E; ++I) {
2652 const MDNode *Node = *I;
2653 InlineInfoMap::iterator II = InlineInfo.find(Node);
2654 SmallVectorImpl<InlineInfoLabels> &Labels = II->second;
2655 DISubprogram SP(Node);
2656 StringRef LName = SP.getLinkageName();
2657 StringRef Name = SP.getName();
2659 Asm->OutStreamer.AddComment("MIPS linkage name");
2661 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2662 DwarfStrSectionSym);
2664 Asm->EmitSectionOffset(
2665 InfoHolder.getStringPoolEntry(Function::getRealLinkageName(LName)),
2666 DwarfStrSectionSym);
2668 Asm->OutStreamer.AddComment("Function name");
2669 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2670 DwarfStrSectionSym);
2671 Asm->EmitULEB128(Labels.size(), "Inline count");
2673 for (SmallVectorImpl<InlineInfoLabels>::iterator LI = Labels.begin(),
2674 LE = Labels.end(); LI != LE; ++LI) {
2675 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2676 Asm->EmitInt32(LI->second->getOffset());
2678 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2679 Asm->OutStreamer.EmitSymbolValue(LI->first,
2680 Asm->getDataLayout().getPointerSize());
2684 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2687 // DWARF5 Experimental Separate Dwarf emitters.
2689 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2690 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2691 // DW_AT_ranges_base, DW_AT_addr_base. If DW_AT_ranges is present,
2692 // DW_AT_low_pc and DW_AT_high_pc are not used, and vice versa.
2693 CompileUnit *DwarfDebug::constructSkeletonCU(const MDNode *N) {
2694 DICompileUnit DIUnit(N);
2695 CompilationDir = DIUnit.getDirectory();
2697 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2698 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
2699 DIUnit.getLanguage(), Die, N, Asm,
2700 this, &SkeletonHolder);
2702 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2703 DIUnit.getSplitDebugFilename());
2705 // Relocate to the beginning of the addr_base section, else 0 for the
2706 // beginning of the one for this compile unit.
2707 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2708 NewCU->addLabel(Die, dwarf::DW_AT_GNU_addr_base, dwarf::DW_FORM_sec_offset,
2709 DwarfAddrSectionSym);
2711 NewCU->addUInt(Die, dwarf::DW_AT_GNU_addr_base,
2712 dwarf::DW_FORM_sec_offset, 0);
2714 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2715 // into an entity. We're using 0, or a NULL label for this.
2716 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2718 // DW_AT_stmt_list is a offset of line number information for this
2719 // compile unit in debug_line section.
2720 // FIXME: Should handle multiple compile units.
2721 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2722 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
2723 DwarfLineSectionSym);
2725 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset, 0);
2727 if (!CompilationDir.empty())
2728 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2730 SkeletonHolder.addUnit(NewCU);
2731 SkeletonCUs.push_back(NewCU);
2736 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
2737 assert(useSplitDwarf() && "No split dwarf debug info?");
2738 emitAbbrevs(Section, &SkeletonAbbrevs);
2741 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2742 // compile units that would normally be in debug_info.
2743 void DwarfDebug::emitDebugInfoDWO() {
2744 assert(useSplitDwarf() && "No split dwarf debug info?");
2745 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
2746 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2747 DwarfAbbrevDWOSectionSym);
2750 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2751 // abbreviations for the .debug_info.dwo section.
2752 void DwarfDebug::emitDebugAbbrevDWO() {
2753 assert(useSplitDwarf() && "No split dwarf?");
2754 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2758 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2759 // string section and is identical in format to traditional .debug_str
2761 void DwarfDebug::emitDebugStrDWO() {
2762 assert(useSplitDwarf() && "No split dwarf?");
2763 const MCSection *OffSec = Asm->getObjFileLowering()
2764 .getDwarfStrOffDWOSection();
2765 const MCSymbol *StrSym = DwarfStrSectionSym;
2766 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),