1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf debug info into asm files.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "dwarfdebug"
15 #include "DwarfDebug.h"
17 #include "DwarfAccelTable.h"
18 #include "DwarfCompileUnit.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/DIBuilder.h"
26 #include "llvm/DebugInfo.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/MC/MCAsmInfo.h"
32 #include "llvm/MC/MCSection.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/FormattedStream.h"
39 #include "llvm/Support/Path.h"
40 #include "llvm/Support/Timer.h"
41 #include "llvm/Support/ValueHandle.h"
42 #include "llvm/Target/TargetFrameLowering.h"
43 #include "llvm/Target/TargetLoweringObjectFile.h"
44 #include "llvm/Target/TargetMachine.h"
45 #include "llvm/Target/TargetOptions.h"
46 #include "llvm/Target/TargetRegisterInfo.h"
49 static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print",
51 cl::desc("Disable debug info printing"));
53 static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
54 cl::desc("Make an absence of debug location information explicit."),
57 static cl::opt<bool> GenerateDwarfPubNamesSection("generate-dwarf-pubnames",
58 cl::Hidden, cl::init(false),
59 cl::desc("Generate DWARF pubnames section"));
63 Default, Enable, Disable
67 static cl::opt<DefaultOnOff> DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
68 cl::desc("Output prototype dwarf accelerator tables."),
70 clEnumVal(Default, "Default for platform"),
71 clEnumVal(Enable, "Enabled"),
72 clEnumVal(Disable, "Disabled"),
76 static cl::opt<DefaultOnOff> DarwinGDBCompat("darwin-gdb-compat", cl::Hidden,
77 cl::desc("Compatibility with Darwin gdb."),
79 clEnumVal(Default, "Default for platform"),
80 clEnumVal(Enable, "Enabled"),
81 clEnumVal(Disable, "Disabled"),
85 static cl::opt<DefaultOnOff> SplitDwarf("split-dwarf", cl::Hidden,
86 cl::desc("Output prototype dwarf split debug info."),
88 clEnumVal(Default, "Default for platform"),
89 clEnumVal(Enable, "Enabled"),
90 clEnumVal(Disable, "Disabled"),
95 const char *DWARFGroupName = "DWARF Emission";
96 const char *DbgTimerName = "DWARF Debug Writer";
99 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
100 return lhs.first < rhs.first;
103 } // end anonymous namespace
105 //===----------------------------------------------------------------------===//
107 // Configuration values for initial hash set sizes (log2).
109 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
113 DIType DbgVariable::getType() const {
114 DIType Ty = Var.getType();
115 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
116 // addresses instead.
117 if (Var.isBlockByrefVariable()) {
118 /* Byref variables, in Blocks, are declared by the programmer as
119 "SomeType VarName;", but the compiler creates a
120 __Block_byref_x_VarName struct, and gives the variable VarName
121 either the struct, or a pointer to the struct, as its type. This
122 is necessary for various behind-the-scenes things the compiler
123 needs to do with by-reference variables in blocks.
125 However, as far as the original *programmer* is concerned, the
126 variable should still have type 'SomeType', as originally declared.
128 The following function dives into the __Block_byref_x_VarName
129 struct to find the original type of the variable. This will be
130 passed back to the code generating the type for the Debug
131 Information Entry for the variable 'VarName'. 'VarName' will then
132 have the original type 'SomeType' in its debug information.
134 The original type 'SomeType' will be the type of the field named
135 'VarName' inside the __Block_byref_x_VarName struct.
137 NOTE: In order for this to not completely fail on the debugger
138 side, the Debug Information Entry for the variable VarName needs to
139 have a DW_AT_location that tells the debugger how to unwind through
140 the pointers and __Block_byref_x_VarName struct to find the actual
141 value of the variable. The function addBlockByrefType does this. */
143 unsigned tag = Ty.getTag();
145 if (tag == dwarf::DW_TAG_pointer_type) {
146 DIDerivedType DTy = DIDerivedType(Ty);
147 subType = DTy.getTypeDerivedFrom();
150 DICompositeType blockStruct = DICompositeType(subType);
151 DIArray Elements = blockStruct.getTypeArray();
153 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
154 DIDescriptor Element = Elements.getElement(i);
155 DIDerivedType DT = DIDerivedType(Element);
156 if (getName() == DT.getName())
157 return (DT.getTypeDerivedFrom());
163 } // end llvm namespace
165 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
166 : Asm(A), MMI(Asm->MMI), FirstCU(0),
167 AbbreviationsSet(InitAbbreviationsSetSize),
168 SourceIdMap(DIEValueAllocator),
169 PrevLabel(NULL), GlobalCUIndexCount(0),
170 InfoHolder(A, &AbbreviationsSet, &Abbreviations, "info_string",
172 SkeletonAbbrevSet(InitAbbreviationsSetSize),
173 SkeletonHolder(A, &SkeletonAbbrevSet, &SkeletonAbbrevs, "skel_string",
176 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
177 DwarfStrSectionSym = TextSectionSym = 0;
178 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
179 DwarfAddrSectionSym = 0;
180 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
181 FunctionBeginSym = FunctionEndSym = 0;
183 // Turn on accelerator tables and older gdb compatibility
185 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
186 if (DarwinGDBCompat == Default) {
188 IsDarwinGDBCompat = true;
190 IsDarwinGDBCompat = false;
192 IsDarwinGDBCompat = DarwinGDBCompat == Enable ? true : false;
194 if (DwarfAccelTables == Default) {
196 HasDwarfAccelTables = true;
198 HasDwarfAccelTables = false;
200 HasDwarfAccelTables = DwarfAccelTables == Enable ? true : false;
202 if (SplitDwarf == Default)
203 HasSplitDwarf = false;
205 HasSplitDwarf = SplitDwarf == Enable ? true : false;
208 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
212 DwarfDebug::~DwarfDebug() {
215 // Switch to the specified MCSection and emit an assembler
216 // temporary label to it if SymbolStem is specified.
217 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
218 const char *SymbolStem = 0) {
219 Asm->OutStreamer.SwitchSection(Section);
220 if (!SymbolStem) return 0;
222 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
223 Asm->OutStreamer.EmitLabel(TmpSym);
227 MCSymbol *DwarfUnits::getStringPoolSym() {
228 return Asm->GetTempSymbol(StringPref);
231 MCSymbol *DwarfUnits::getStringPoolEntry(StringRef Str) {
232 std::pair<MCSymbol*, unsigned> &Entry =
233 StringPool.GetOrCreateValue(Str).getValue();
234 if (Entry.first) return Entry.first;
236 Entry.second = NextStringPoolNumber++;
237 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
240 unsigned DwarfUnits::getStringPoolIndex(StringRef Str) {
241 std::pair<MCSymbol*, unsigned> &Entry =
242 StringPool.GetOrCreateValue(Str).getValue();
243 if (Entry.first) return Entry.second;
245 Entry.second = NextStringPoolNumber++;
246 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
250 unsigned DwarfUnits::getAddrPoolIndex(const MCSymbol *Sym) {
251 std::pair<DenseMap<const MCSymbol *, unsigned>::iterator, bool> P =
252 AddressPool.insert(std::make_pair(Sym, NextAddrPoolNumber));
254 ++NextAddrPoolNumber;
255 return P.first->second;
258 // Define a unique number for the abbreviation.
260 void DwarfUnits::assignAbbrevNumber(DIEAbbrev &Abbrev) {
261 // Check the set for priors.
262 DIEAbbrev *InSet = AbbreviationsSet->GetOrInsertNode(&Abbrev);
264 // If it's newly added.
265 if (InSet == &Abbrev) {
266 // Add to abbreviation list.
267 Abbreviations->push_back(&Abbrev);
269 // Assign the vector position + 1 as its number.
270 Abbrev.setNumber(Abbreviations->size());
272 // Assign existing abbreviation number.
273 Abbrev.setNumber(InSet->getNumber());
277 static bool isObjCClass(StringRef Name) {
278 return Name.startswith("+") || Name.startswith("-");
281 static bool hasObjCCategory(StringRef Name) {
282 if (!isObjCClass(Name)) return false;
284 size_t pos = Name.find(')');
285 if (pos != std::string::npos) {
286 if (Name[pos+1] != ' ') return false;
292 static void getObjCClassCategory(StringRef In, StringRef &Class,
293 StringRef &Category) {
294 if (!hasObjCCategory(In)) {
295 Class = In.slice(In.find('[') + 1, In.find(' '));
300 Class = In.slice(In.find('[') + 1, In.find('('));
301 Category = In.slice(In.find('[') + 1, In.find(' '));
305 static StringRef getObjCMethodName(StringRef In) {
306 return In.slice(In.find(' ') + 1, In.find(']'));
309 // Add the various names to the Dwarf accelerator table names.
310 static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
312 if (!SP.isDefinition()) return;
314 TheCU->addAccelName(SP.getName(), Die);
316 // If the linkage name is different than the name, go ahead and output
317 // that as well into the name table.
318 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
319 TheCU->addAccelName(SP.getLinkageName(), Die);
321 // If this is an Objective-C selector name add it to the ObjC accelerator
323 if (isObjCClass(SP.getName())) {
324 StringRef Class, Category;
325 getObjCClassCategory(SP.getName(), Class, Category);
326 TheCU->addAccelObjC(Class, Die);
328 TheCU->addAccelObjC(Category, Die);
329 // Also add the base method name to the name table.
330 TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
334 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
335 // and DW_AT_high_pc attributes. If there are global variables in this
336 // scope then create and insert DIEs for these variables.
337 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
338 const MDNode *SPNode) {
339 DIE *SPDie = SPCU->getDIE(SPNode);
341 assert(SPDie && "Unable to find subprogram DIE!");
342 DISubprogram SP(SPNode);
344 // If we're updating an abstract DIE, then we will be adding the children and
345 // object pointer later on. But what we don't want to do is process the
346 // concrete DIE twice.
347 DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode);
349 bool InSameCU = (AbsSPDIE->getCompileUnit() == SPCU->getCUDie());
350 // Pick up abstract subprogram DIE.
351 SPDie = new DIE(dwarf::DW_TAG_subprogram);
352 // If AbsSPDIE belongs to a different CU, use DW_FORM_ref_addr instead of
354 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
355 InSameCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
359 DISubprogram SPDecl = SP.getFunctionDeclaration();
360 if (!SPDecl.isSubprogram()) {
361 // There is not any need to generate specification DIE for a function
362 // defined at compile unit level. If a function is defined inside another
363 // function then gdb prefers the definition at top level and but does not
364 // expect specification DIE in parent function. So avoid creating
365 // specification DIE for a function defined inside a function.
366 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
367 !SP.getContext().isFile() &&
368 !isSubprogramContext(SP.getContext())) {
369 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
372 DICompositeType SPTy = SP.getType();
373 DIArray Args = SPTy.getTypeArray();
374 unsigned SPTag = SPTy.getTag();
375 if (SPTag == dwarf::DW_TAG_subroutine_type)
376 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
377 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
378 DIType ATy = DIType(Args.getElement(i));
379 SPCU->addType(Arg, ATy);
380 if (ATy.isArtificial())
381 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
382 if (ATy.isObjectPointer())
383 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer,
384 dwarf::DW_FORM_ref4, Arg);
385 SPDie->addChild(Arg);
387 DIE *SPDeclDie = SPDie;
388 SPDie = new DIE(dwarf::DW_TAG_subprogram);
389 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification,
390 dwarf::DW_FORM_ref4, SPDeclDie);
396 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc,
397 Asm->GetTempSymbol("func_begin",
398 Asm->getFunctionNumber()));
399 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc,
400 Asm->GetTempSymbol("func_end",
401 Asm->getFunctionNumber()));
402 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
403 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
404 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
406 // Add name to the name table, we do this here because we're guaranteed
407 // to have concrete versions of our DW_TAG_subprogram nodes.
408 addSubprogramNames(SPCU, SP, SPDie);
413 // Construct new DW_TAG_lexical_block for this scope and attach
414 // DW_AT_low_pc/DW_AT_high_pc labels.
415 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
416 LexicalScope *Scope) {
417 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
418 if (Scope->isAbstractScope())
421 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
425 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
426 if (Ranges.size() > 1) {
427 // .debug_range section has not been laid out yet. Emit offset in
428 // .debug_range as a uint, size 4, for now. emitDIE will handle
429 // DW_AT_ranges appropriately.
430 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
431 DebugRangeSymbols.size()
432 * Asm->getDataLayout().getPointerSize());
433 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
434 RE = Ranges.end(); RI != RE; ++RI) {
435 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
436 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
438 DebugRangeSymbols.push_back(NULL);
439 DebugRangeSymbols.push_back(NULL);
443 MCSymbol *Start = getLabelBeforeInsn(RI->first);
444 MCSymbol *End = getLabelAfterInsn(RI->second);
446 if (End == 0) return 0;
448 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
449 assert(End->isDefined() && "Invalid end label for an inlined scope!");
451 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
452 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
457 // This scope represents inlined body of a function. Construct DIE to
458 // represent this concrete inlined copy of the function.
459 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
460 LexicalScope *Scope) {
461 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
462 assert(Ranges.empty() == false &&
463 "LexicalScope does not have instruction markers!");
465 if (!Scope->getScopeNode())
467 DIScope DS(Scope->getScopeNode());
468 DISubprogram InlinedSP = getDISubprogram(DS);
469 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
471 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
475 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
476 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
477 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
479 if (StartLabel == 0 || EndLabel == 0) {
480 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
482 assert(StartLabel->isDefined() &&
483 "Invalid starting label for an inlined scope!");
484 assert(EndLabel->isDefined() &&
485 "Invalid end label for an inlined scope!");
487 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
488 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
489 dwarf::DW_FORM_ref4, OriginDIE);
491 if (Ranges.size() > 1) {
492 // .debug_range section has not been laid out yet. Emit offset in
493 // .debug_range as a uint, size 4, for now. emitDIE will handle
494 // DW_AT_ranges appropriately.
495 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
496 DebugRangeSymbols.size()
497 * Asm->getDataLayout().getPointerSize());
498 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
499 RE = Ranges.end(); RI != RE; ++RI) {
500 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
501 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
503 DebugRangeSymbols.push_back(NULL);
504 DebugRangeSymbols.push_back(NULL);
506 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
507 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
510 InlinedSubprogramDIEs.insert(OriginDIE);
512 // Track the start label for this inlined function.
513 //.debug_inlined section specification does not clearly state how
514 // to emit inlined scope that is split into multiple instruction ranges.
515 // For now, use first instruction range and emit low_pc/high_pc pair and
516 // corresponding .debug_inlined section entry for this pair.
517 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
518 I = InlineInfo.find(InlinedSP);
520 if (I == InlineInfo.end()) {
521 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
522 InlinedSPNodes.push_back(InlinedSP);
524 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
526 DILocation DL(Scope->getInlinedAt());
527 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
528 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
529 TheCU->getUniqueID()));
530 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
532 // Add name to the name table, we do this here because we're guaranteed
533 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
534 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
539 // Construct a DIE for this scope.
540 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
541 if (!Scope || !Scope->getScopeNode())
544 DIScope DS(Scope->getScopeNode());
545 // Early return to avoid creating dangling variable|scope DIEs.
546 if (!Scope->getInlinedAt() && DS.isSubprogram() && Scope->isAbstractScope() &&
550 SmallVector<DIE *, 8> Children;
551 DIE *ObjectPointer = NULL;
553 // Collect arguments for current function.
554 if (LScopes.isCurrentFunctionScope(Scope))
555 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
556 if (DbgVariable *ArgDV = CurrentFnArguments[i])
558 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope())) {
559 Children.push_back(Arg);
560 if (ArgDV->isObjectPointer()) ObjectPointer = Arg;
563 // Collect lexical scope children first.
564 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
565 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
567 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope())) {
568 Children.push_back(Variable);
569 if (Variables[i]->isObjectPointer()) ObjectPointer = Variable;
571 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
572 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
573 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
574 Children.push_back(Nested);
575 DIE *ScopeDIE = NULL;
576 if (Scope->getInlinedAt())
577 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
578 else if (DS.isSubprogram()) {
579 ProcessedSPNodes.insert(DS);
580 if (Scope->isAbstractScope()) {
581 ScopeDIE = TheCU->getDIE(DS);
582 // Note down abstract DIE.
584 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
587 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
590 // There is no need to emit empty lexical block DIE.
591 std::pair<ImportedEntityMap::const_iterator,
592 ImportedEntityMap::const_iterator> Range = std::equal_range(
593 ScopesWithImportedEntities.begin(), ScopesWithImportedEntities.end(),
594 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode*)0),
596 if (Children.empty() && Range.first == Range.second)
598 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
599 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
601 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
604 if (!ScopeDIE) return NULL;
607 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
608 E = Children.end(); I != E; ++I)
609 ScopeDIE->addChild(*I);
611 if (DS.isSubprogram() && ObjectPointer != NULL)
612 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer,
613 dwarf::DW_FORM_ref4, ObjectPointer);
615 if (DS.isSubprogram())
616 TheCU->addPubTypes(DISubprogram(DS));
621 // Look up the source id with the given directory and source file names.
622 // If none currently exists, create a new id and insert it in the
623 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
625 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName,
626 StringRef DirName, unsigned CUID) {
627 // If we use .loc in assembly, we can't separate .file entries according to
628 // compile units. Thus all files will belong to the default compile unit.
629 if (Asm->TM.hasMCUseLoc() &&
630 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer)
633 // If FE did not provide a file name, then assume stdin.
634 if (FileName.empty())
635 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
637 // TODO: this might not belong here. See if we can factor this better.
638 if (DirName == CompilationDir)
641 // FileIDCUMap stores the current ID for the given compile unit.
642 unsigned SrcId = FileIDCUMap[CUID] + 1;
644 // We look up the CUID/file/dir by concatenating them with a zero byte.
645 SmallString<128> NamePair;
646 NamePair += utostr(CUID);
649 NamePair += '\0'; // Zero bytes are not allowed in paths.
650 NamePair += FileName;
652 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
653 if (Ent.getValue() != SrcId)
654 return Ent.getValue();
656 FileIDCUMap[CUID] = SrcId;
657 // Print out a .file directive to specify files for .loc directives.
658 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
663 // Create new CompileUnit for the given metadata node with tag
664 // DW_TAG_compile_unit.
665 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
666 DICompileUnit DIUnit(N);
667 StringRef FN = DIUnit.getFilename();
668 CompilationDir = DIUnit.getDirectory();
670 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
671 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
672 DIUnit.getLanguage(), Die, N, Asm,
675 FileIDCUMap[NewCU->getUniqueID()] = 0;
676 // Call this to emit a .file directive if it wasn't emitted for the source
677 // file this CU comes from yet.
678 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
680 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
681 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
682 DIUnit.getLanguage());
683 NewCU->addString(Die, dwarf::DW_AT_name, FN);
685 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
686 // into an entity. We're using 0 (or a NULL label) for this. For
687 // split dwarf it's in the skeleton CU so omit it here.
688 if (!useSplitDwarf())
689 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
691 // Define start line table label for each Compile Unit.
692 MCSymbol *LineTableStartSym = Asm->GetTempSymbol("line_table_start",
693 NewCU->getUniqueID());
694 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
695 NewCU->getUniqueID());
697 // Use a single line table if we are using .loc and generating assembly.
699 (Asm->TM.hasMCUseLoc() &&
700 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer) ||
701 (NewCU->getUniqueID() == 0);
703 // DW_AT_stmt_list is a offset of line number information for this
704 // compile unit in debug_line section. For split dwarf this is
705 // left in the skeleton CU and so not included.
706 // The line table entries are not always emitted in assembly, so it
707 // is not okay to use line_table_start here.
708 if (!useSplitDwarf()) {
709 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
710 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
712 Asm->GetTempSymbol("section_line") : LineTableStartSym);
713 else if (UseTheFirstCU)
714 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
716 NewCU->addDelta(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
717 LineTableStartSym, DwarfLineSectionSym);
720 // If we're using split dwarf the compilation dir is going to be in the
721 // skeleton CU and so we don't need to duplicate it here.
722 if (!useSplitDwarf() && !CompilationDir.empty())
723 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
724 if (DIUnit.isOptimized())
725 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
727 StringRef Flags = DIUnit.getFlags();
729 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
731 if (unsigned RVer = DIUnit.getRunTimeVersion())
732 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
733 dwarf::DW_FORM_data1, RVer);
738 InfoHolder.addUnit(NewCU);
740 CUMap.insert(std::make_pair(N, NewCU));
744 // Construct subprogram DIE.
745 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
747 CompileUnit *&CURef = SPMap[N];
753 if (!SP.isDefinition())
754 // This is a method declaration which will be handled while constructing
758 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
761 TheCU->insertDIE(N, SubprogramDie);
763 // Add to context owner.
764 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
766 // Expose as global, if requested.
767 if (GenerateDwarfPubNamesSection)
768 TheCU->addGlobalName(SP.getName(), SubprogramDie);
771 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
773 DIImportedEntity Module(N);
774 if (!Module.Verify())
776 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
777 constructImportedEntityDIE(TheCU, Module, D);
780 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU, const MDNode *N,
782 DIImportedEntity Module(N);
783 if (!Module.Verify())
785 return constructImportedEntityDIE(TheCU, Module, Context);
788 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
789 const DIImportedEntity &Module,
791 assert(Module.Verify() &&
792 "Use one of the MDNode * overloads to handle invalid metadata");
793 assert(Context && "Should always have a context for an imported_module");
794 DIE *IMDie = new DIE(Module.getTag());
795 TheCU->insertDIE(Module, IMDie);
797 DIDescriptor Entity = Module.getEntity();
798 if (Entity.isNameSpace())
799 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
800 else if (Entity.isSubprogram())
801 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
802 else if (Entity.isType())
803 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
805 EntityDie = TheCU->getDIE(Entity);
806 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
807 Module.getContext().getDirectory(),
808 TheCU->getUniqueID());
809 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, 0, FileID);
810 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, 0, Module.getLineNumber());
811 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, dwarf::DW_FORM_ref4,
813 StringRef Name = Module.getName();
815 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
816 Context->addChild(IMDie);
819 // Emit all Dwarf sections that should come prior to the content. Create
820 // global DIEs and emit initial debug info sections. This is invoked by
821 // the target AsmPrinter.
822 void DwarfDebug::beginModule() {
823 if (DisableDebugInfoPrinting)
826 const Module *M = MMI->getModule();
828 // If module has named metadata anchors then use them, otherwise scan the
829 // module using debug info finder to collect debug info.
830 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
834 // Emit initial sections so we can reference labels later.
837 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
838 DICompileUnit CUNode(CU_Nodes->getOperand(i));
839 CompileUnit *CU = constructCompileUnit(CUNode);
840 DIArray ImportedEntities = CUNode.getImportedEntities();
841 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
842 ScopesWithImportedEntities.push_back(std::make_pair(
843 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
844 ImportedEntities.getElement(i)));
845 std::sort(ScopesWithImportedEntities.begin(),
846 ScopesWithImportedEntities.end(), CompareFirst());
847 DIArray GVs = CUNode.getGlobalVariables();
848 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
849 CU->createGlobalVariableDIE(GVs.getElement(i));
850 DIArray SPs = CUNode.getSubprograms();
851 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
852 constructSubprogramDIE(CU, SPs.getElement(i));
853 DIArray EnumTypes = CUNode.getEnumTypes();
854 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
855 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
856 DIArray RetainedTypes = CUNode.getRetainedTypes();
857 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
858 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
859 // Emit imported_modules last so that the relevant context is already
861 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
862 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
863 // If we're splitting the dwarf out now that we've got the entire
864 // CU then construct a skeleton CU based upon it.
865 if (useSplitDwarf()) {
866 // This should be a unique identifier when we want to build .dwp files.
867 CU->addUInt(CU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
868 dwarf::DW_FORM_data8, 0);
869 // Now construct the skeleton CU associated.
870 constructSkeletonCU(CUNode);
874 // Tell MMI that we have debug info.
875 MMI->setDebugInfoAvailability(true);
877 // Prime section data.
878 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
881 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
882 void DwarfDebug::computeInlinedDIEs() {
883 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
884 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
885 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
887 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
889 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
890 AE = AbstractSPDies.end(); AI != AE; ++AI) {
891 DIE *ISP = AI->second;
892 if (InlinedSubprogramDIEs.count(ISP))
894 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
898 // Collect info for variables that were optimized out.
899 void DwarfDebug::collectDeadVariables() {
900 const Module *M = MMI->getModule();
901 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
903 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
904 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
905 DICompileUnit TheCU(CU_Nodes->getOperand(i));
906 DIArray Subprograms = TheCU.getSubprograms();
907 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
908 DISubprogram SP(Subprograms.getElement(i));
909 if (ProcessedSPNodes.count(SP) != 0) continue;
910 if (!SP.Verify()) continue;
911 if (!SP.isDefinition()) continue;
912 DIArray Variables = SP.getVariables();
913 if (Variables.getNumElements() == 0) continue;
915 LexicalScope *Scope =
916 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
917 DeadFnScopeMap[SP] = Scope;
919 // Construct subprogram DIE and add variables DIEs.
920 CompileUnit *SPCU = CUMap.lookup(TheCU);
921 assert(SPCU && "Unable to find Compile Unit!");
922 constructSubprogramDIE(SPCU, SP);
923 DIE *ScopeDIE = SPCU->getDIE(SP);
924 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
925 DIVariable DV(Variables.getElement(vi));
926 if (!DV.Verify()) continue;
927 DbgVariable *NewVar = new DbgVariable(DV, NULL);
928 if (DIE *VariableDIE =
929 SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
930 ScopeDIE->addChild(VariableDIE);
935 DeleteContainerSeconds(DeadFnScopeMap);
938 void DwarfDebug::finalizeModuleInfo() {
939 // Collect info for variables that were optimized out.
940 collectDeadVariables();
942 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
943 computeInlinedDIEs();
945 // Emit DW_AT_containing_type attribute to connect types with their
946 // vtable holding type.
947 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
948 CUE = CUMap.end(); CUI != CUE; ++CUI) {
949 CompileUnit *TheCU = CUI->second;
950 TheCU->constructContainingTypeDIEs();
953 // Compute DIE offsets and sizes.
954 InfoHolder.computeSizeAndOffsets();
956 SkeletonHolder.computeSizeAndOffsets();
959 void DwarfDebug::endSections() {
960 // Standard sections final addresses.
961 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
962 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
963 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
964 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
966 // End text sections.
967 for (unsigned I = 0, E = SectionMap.size(); I != E; ++I) {
968 Asm->OutStreamer.SwitchSection(SectionMap[I]);
969 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", I+1));
973 // Emit all Dwarf sections that should come after the content.
974 void DwarfDebug::endModule() {
976 if (!FirstCU) return;
978 // End any existing sections.
979 // TODO: Does this need to happen?
982 // Finalize the debug info for the module.
983 finalizeModuleInfo();
985 if (!useSplitDwarf()) {
986 // Emit all the DIEs into a debug info section.
989 // Corresponding abbreviations into a abbrev section.
992 // Emit info into a debug loc section.
995 // Emit info into a debug aranges section.
998 // Emit info into a debug ranges section.
1001 // Emit info into a debug macinfo section.
1004 // Emit inline info.
1005 // TODO: When we don't need the option anymore we
1006 // can remove all of the code that this section
1008 if (useDarwinGDBCompat())
1009 emitDebugInlineInfo();
1011 // TODO: Fill this in for separated debug sections and separate
1012 // out information into new sections.
1014 // Emit the debug info section and compile units.
1018 // Corresponding abbreviations into a abbrev section.
1019 emitAbbreviations();
1020 emitDebugAbbrevDWO();
1022 // Emit info into a debug loc section.
1025 // Emit info into a debug aranges section.
1028 // Emit info into a debug ranges section.
1031 // Emit info into a debug macinfo section.
1034 // Emit DWO addresses.
1035 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1037 // Emit inline info.
1038 // TODO: When we don't need the option anymore we
1039 // can remove all of the code that this section
1041 if (useDarwinGDBCompat())
1042 emitDebugInlineInfo();
1045 // Emit info into the dwarf accelerator table sections.
1046 if (useDwarfAccelTables()) {
1049 emitAccelNamespaces();
1053 // Emit info into a debug pubnames section, if requested.
1054 if (GenerateDwarfPubNamesSection)
1055 emitDebugPubnames();
1057 // Emit info into a debug pubtypes section.
1058 // TODO: When we don't need the option anymore we can
1059 // remove all of the code that adds to the table.
1060 if (useDarwinGDBCompat())
1061 emitDebugPubTypes();
1063 // Finally emit string information into a string table.
1065 if (useSplitDwarf())
1070 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1071 E = CUMap.end(); I != E; ++I)
1074 for (SmallVector<CompileUnit *, 1>::iterator I = SkeletonCUs.begin(),
1075 E = SkeletonCUs.end(); I != E; ++I)
1078 // Reset these for the next Module if we have one.
1082 // Find abstract variable, if any, associated with Var.
1083 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1084 DebugLoc ScopeLoc) {
1085 LLVMContext &Ctx = DV->getContext();
1086 // More then one inlined variable corresponds to one abstract variable.
1087 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1088 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1090 return AbsDbgVariable;
1092 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1096 AbsDbgVariable = new DbgVariable(Var, NULL);
1097 addScopeVariable(Scope, AbsDbgVariable);
1098 AbstractVariables[Var] = AbsDbgVariable;
1099 return AbsDbgVariable;
1102 // If Var is a current function argument then add it to CurrentFnArguments list.
1103 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1104 DbgVariable *Var, LexicalScope *Scope) {
1105 if (!LScopes.isCurrentFunctionScope(Scope))
1107 DIVariable DV = Var->getVariable();
1108 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1110 unsigned ArgNo = DV.getArgNumber();
1114 size_t Size = CurrentFnArguments.size();
1116 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1117 // llvm::Function argument size is not good indicator of how many
1118 // arguments does the function have at source level.
1120 CurrentFnArguments.resize(ArgNo * 2);
1121 CurrentFnArguments[ArgNo - 1] = Var;
1125 // Collect variable information from side table maintained by MMI.
1127 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1128 SmallPtrSet<const MDNode *, 16> &Processed) {
1129 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1130 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1131 VE = VMap.end(); VI != VE; ++VI) {
1132 const MDNode *Var = VI->first;
1134 Processed.insert(Var);
1136 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1138 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1140 // If variable scope is not found then skip this variable.
1144 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1145 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
1146 RegVar->setFrameIndex(VP.first);
1147 if (!addCurrentFnArgument(MF, RegVar, Scope))
1148 addScopeVariable(Scope, RegVar);
1150 AbsDbgVariable->setFrameIndex(VP.first);
1154 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1156 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1157 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1158 return MI->getNumOperands() == 3 &&
1159 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1160 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
1163 // Get .debug_loc entry for the instruction range starting at MI.
1164 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1165 const MCSymbol *FLabel,
1166 const MCSymbol *SLabel,
1167 const MachineInstr *MI) {
1168 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1170 assert(MI->getNumOperands() == 3);
1171 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
1172 MachineLocation MLoc;
1173 // TODO: Currently an offset of 0 in a DBG_VALUE means
1174 // we need to generate a direct register value.
1175 // There is no way to specify an indirect value with offset 0.
1176 if (MI->getOperand(1).getImm() == 0)
1177 MLoc.set(MI->getOperand(0).getReg());
1179 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1180 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1182 if (MI->getOperand(0).isImm())
1183 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1184 if (MI->getOperand(0).isFPImm())
1185 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1186 if (MI->getOperand(0).isCImm())
1187 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1189 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1192 // Find variables for each lexical scope.
1194 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1195 SmallPtrSet<const MDNode *, 16> &Processed) {
1197 // collection info from MMI table.
1198 collectVariableInfoFromMMITable(MF, Processed);
1200 for (SmallVectorImpl<const MDNode*>::const_iterator
1201 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1203 const MDNode *Var = *UVI;
1204 if (Processed.count(Var))
1207 // History contains relevant DBG_VALUE instructions for Var and instructions
1209 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1210 if (History.empty())
1212 const MachineInstr *MInsn = History.front();
1215 LexicalScope *Scope = NULL;
1216 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1217 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1218 Scope = LScopes.getCurrentFunctionScope();
1219 else if (MDNode *IA = DV.getInlinedAt())
1220 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1222 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1223 // If variable scope is not found then skip this variable.
1227 Processed.insert(DV);
1228 assert(MInsn->isDebugValue() && "History must begin with debug value");
1229 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1230 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1231 if (!addCurrentFnArgument(MF, RegVar, Scope))
1232 addScopeVariable(Scope, RegVar);
1234 AbsVar->setMInsn(MInsn);
1236 // Simplify ranges that are fully coalesced.
1237 if (History.size() <= 1 || (History.size() == 2 &&
1238 MInsn->isIdenticalTo(History.back()))) {
1239 RegVar->setMInsn(MInsn);
1243 // Handle multiple DBG_VALUE instructions describing one variable.
1244 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1246 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1247 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1248 const MachineInstr *Begin = *HI;
1249 assert(Begin->isDebugValue() && "Invalid History entry");
1251 // Check if DBG_VALUE is truncating a range.
1252 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1253 && !Begin->getOperand(0).getReg())
1256 // Compute the range for a register location.
1257 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1258 const MCSymbol *SLabel = 0;
1261 // If Begin is the last instruction in History then its value is valid
1262 // until the end of the function.
1263 SLabel = FunctionEndSym;
1265 const MachineInstr *End = HI[1];
1266 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1267 << "\t" << *Begin << "\t" << *End << "\n");
1268 if (End->isDebugValue())
1269 SLabel = getLabelBeforeInsn(End);
1271 // End is a normal instruction clobbering the range.
1272 SLabel = getLabelAfterInsn(End);
1273 assert(SLabel && "Forgot label after clobber instruction");
1278 // The value is valid until the next DBG_VALUE or clobber.
1279 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1282 DotDebugLocEntries.push_back(DotDebugLocEntry());
1285 // Collect info for variables that were optimized out.
1286 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1287 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1288 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1289 DIVariable DV(Variables.getElement(i));
1290 if (!DV || !DV.Verify() || !Processed.insert(DV))
1292 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1293 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1297 // Return Label preceding the instruction.
1298 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1299 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1300 assert(Label && "Didn't insert label before instruction");
1304 // Return Label immediately following the instruction.
1305 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1306 return LabelsAfterInsn.lookup(MI);
1309 // Process beginning of an instruction.
1310 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1311 // Check if source location changes, but ignore DBG_VALUE locations.
1312 if (!MI->isDebugValue()) {
1313 DebugLoc DL = MI->getDebugLoc();
1314 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1317 if (DL == PrologEndLoc) {
1318 Flags |= DWARF2_FLAG_PROLOGUE_END;
1319 PrologEndLoc = DebugLoc();
1321 if (PrologEndLoc.isUnknown())
1322 Flags |= DWARF2_FLAG_IS_STMT;
1324 if (!DL.isUnknown()) {
1325 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1326 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1328 recordSourceLine(0, 0, 0, 0);
1332 // Insert labels where requested.
1333 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1334 LabelsBeforeInsn.find(MI);
1337 if (I == LabelsBeforeInsn.end())
1340 // Label already assigned.
1345 PrevLabel = MMI->getContext().CreateTempSymbol();
1346 Asm->OutStreamer.EmitLabel(PrevLabel);
1348 I->second = PrevLabel;
1351 // Process end of an instruction.
1352 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1353 // Don't create a new label after DBG_VALUE instructions.
1354 // They don't generate code.
1355 if (!MI->isDebugValue())
1358 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1359 LabelsAfterInsn.find(MI);
1362 if (I == LabelsAfterInsn.end())
1365 // Label already assigned.
1369 // We need a label after this instruction.
1371 PrevLabel = MMI->getContext().CreateTempSymbol();
1372 Asm->OutStreamer.EmitLabel(PrevLabel);
1374 I->second = PrevLabel;
1377 // Each LexicalScope has first instruction and last instruction to mark
1378 // beginning and end of a scope respectively. Create an inverse map that list
1379 // scopes starts (and ends) with an instruction. One instruction may start (or
1380 // end) multiple scopes. Ignore scopes that are not reachable.
1381 void DwarfDebug::identifyScopeMarkers() {
1382 SmallVector<LexicalScope *, 4> WorkList;
1383 WorkList.push_back(LScopes.getCurrentFunctionScope());
1384 while (!WorkList.empty()) {
1385 LexicalScope *S = WorkList.pop_back_val();
1387 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1388 if (!Children.empty())
1389 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1390 SE = Children.end(); SI != SE; ++SI)
1391 WorkList.push_back(*SI);
1393 if (S->isAbstractScope())
1396 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1399 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1400 RE = Ranges.end(); RI != RE; ++RI) {
1401 assert(RI->first && "InsnRange does not have first instruction!");
1402 assert(RI->second && "InsnRange does not have second instruction!");
1403 requestLabelBeforeInsn(RI->first);
1404 requestLabelAfterInsn(RI->second);
1409 // Get MDNode for DebugLoc's scope.
1410 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1411 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1412 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1413 return DL.getScope(Ctx);
1416 // Walk up the scope chain of given debug loc and find line number info
1417 // for the function.
1418 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1419 const MDNode *Scope = getScopeNode(DL, Ctx);
1420 DISubprogram SP = getDISubprogram(Scope);
1422 // Check for number of operands since the compatibility is
1424 if (SP->getNumOperands() > 19)
1425 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1427 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1433 // Gather pre-function debug information. Assumes being called immediately
1434 // after the function entry point has been emitted.
1435 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1436 if (!MMI->hasDebugInfo()) return;
1437 LScopes.initialize(*MF);
1438 if (LScopes.empty()) return;
1439 identifyScopeMarkers();
1441 // Set DwarfCompileUnitID in MCContext to the Compile Unit this function
1443 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1444 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1445 assert(TheCU && "Unable to find compile unit!");
1446 if (Asm->TM.hasMCUseLoc() &&
1447 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer)
1448 // Use a single line table if we are using .loc and generating assembly.
1449 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1451 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1453 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1454 Asm->getFunctionNumber());
1455 // Assumes in correct section after the entry point.
1456 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1458 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1460 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1461 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1462 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1464 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1466 bool AtBlockEntry = true;
1467 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1469 const MachineInstr *MI = II;
1471 if (MI->isDebugValue()) {
1472 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1474 // Keep track of user variables.
1476 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1478 // Variable is in a register, we need to check for clobbers.
1479 if (isDbgValueInDefinedReg(MI))
1480 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1482 // Check the history of this variable.
1483 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1484 if (History.empty()) {
1485 UserVariables.push_back(Var);
1486 // The first mention of a function argument gets the FunctionBeginSym
1487 // label, so arguments are visible when breaking at function entry.
1489 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1490 DISubprogram(getDISubprogram(DV.getContext()))
1491 .describes(MF->getFunction()))
1492 LabelsBeforeInsn[MI] = FunctionBeginSym;
1494 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1495 const MachineInstr *Prev = History.back();
1496 if (Prev->isDebugValue()) {
1497 // Coalesce identical entries at the end of History.
1498 if (History.size() >= 2 &&
1499 Prev->isIdenticalTo(History[History.size() - 2])) {
1500 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1502 << "\t" << *History[History.size() - 2] << "\n");
1506 // Terminate old register assignments that don't reach MI;
1507 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1508 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1509 isDbgValueInDefinedReg(Prev)) {
1510 // Previous register assignment needs to terminate at the end of
1512 MachineBasicBlock::const_iterator LastMI =
1513 PrevMBB->getLastNonDebugInstr();
1514 if (LastMI == PrevMBB->end()) {
1515 // Drop DBG_VALUE for empty range.
1516 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1517 << "\t" << *Prev << "\n");
1519 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1520 // Terminate after LastMI.
1521 History.push_back(LastMI);
1525 History.push_back(MI);
1527 // Not a DBG_VALUE instruction.
1529 AtBlockEntry = false;
1531 // First known non-DBG_VALUE and non-frame setup location marks
1532 // the beginning of the function body.
1533 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1534 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1535 PrologEndLoc = MI->getDebugLoc();
1537 // Check if the instruction clobbers any registers with debug vars.
1538 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1539 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1540 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1542 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1543 AI.isValid(); ++AI) {
1545 const MDNode *Var = LiveUserVar[Reg];
1548 // Reg is now clobbered.
1549 LiveUserVar[Reg] = 0;
1551 // Was MD last defined by a DBG_VALUE referring to Reg?
1552 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1553 if (HistI == DbgValues.end())
1555 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1556 if (History.empty())
1558 const MachineInstr *Prev = History.back();
1559 // Sanity-check: Register assignments are terminated at the end of
1561 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1563 // Is the variable still in Reg?
1564 if (!isDbgValueInDefinedReg(Prev) ||
1565 Prev->getOperand(0).getReg() != Reg)
1567 // Var is clobbered. Make sure the next instruction gets a label.
1568 History.push_back(MI);
1575 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1577 SmallVectorImpl<const MachineInstr*> &History = I->second;
1578 if (History.empty())
1581 // Make sure the final register assignments are terminated.
1582 const MachineInstr *Prev = History.back();
1583 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1584 const MachineBasicBlock *PrevMBB = Prev->getParent();
1585 MachineBasicBlock::const_iterator LastMI =
1586 PrevMBB->getLastNonDebugInstr();
1587 if (LastMI == PrevMBB->end())
1588 // Drop DBG_VALUE for empty range.
1590 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1591 // Terminate after LastMI.
1592 History.push_back(LastMI);
1595 // Request labels for the full history.
1596 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1597 const MachineInstr *MI = History[i];
1598 if (MI->isDebugValue())
1599 requestLabelBeforeInsn(MI);
1601 requestLabelAfterInsn(MI);
1605 PrevInstLoc = DebugLoc();
1606 PrevLabel = FunctionBeginSym;
1608 // Record beginning of function.
1609 if (!PrologEndLoc.isUnknown()) {
1610 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1611 MF->getFunction()->getContext());
1612 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1613 FnStartDL.getScope(MF->getFunction()->getContext()),
1614 // We'd like to list the prologue as "not statements" but GDB behaves
1615 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1616 DWARF2_FLAG_IS_STMT);
1620 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1621 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1622 DIVariable DV = Var->getVariable();
1623 // Variables with positive arg numbers are parameters.
1624 if (unsigned ArgNum = DV.getArgNumber()) {
1625 // Keep all parameters in order at the start of the variable list to ensure
1626 // function types are correct (no out-of-order parameters)
1628 // This could be improved by only doing it for optimized builds (unoptimized
1629 // builds have the right order to begin with), searching from the back (this
1630 // would catch the unoptimized case quickly), or doing a binary search
1631 // rather than linear search.
1632 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1633 while (I != Vars.end()) {
1634 unsigned CurNum = (*I)->getVariable().getArgNumber();
1635 // A local (non-parameter) variable has been found, insert immediately
1639 // A later indexed parameter has been found, insert immediately before it.
1640 if (CurNum > ArgNum)
1644 Vars.insert(I, Var);
1648 Vars.push_back(Var);
1651 // Gather and emit post-function debug information.
1652 void DwarfDebug::endFunction(const MachineFunction *MF) {
1653 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1655 // Define end label for subprogram.
1656 FunctionEndSym = Asm->GetTempSymbol("func_end",
1657 Asm->getFunctionNumber());
1658 // Assumes in correct section after the entry point.
1659 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1660 // Set DwarfCompileUnitID in MCContext to default value.
1661 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1663 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1664 collectVariableInfo(MF, ProcessedVars);
1666 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1667 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1668 assert(TheCU && "Unable to find compile unit!");
1670 // Construct abstract scopes.
1671 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1672 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1673 LexicalScope *AScope = AList[i];
1674 DISubprogram SP(AScope->getScopeNode());
1676 // Collect info for variables that were optimized out.
1677 DIArray Variables = SP.getVariables();
1678 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1679 DIVariable DV(Variables.getElement(i));
1680 if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1682 // Check that DbgVariable for DV wasn't created earlier, when
1683 // findAbstractVariable() was called for inlined instance of DV.
1684 LLVMContext &Ctx = DV->getContext();
1685 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1686 if (AbstractVariables.lookup(CleanDV))
1688 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1689 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1692 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1693 constructScopeDIE(TheCU, AScope);
1696 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1698 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1699 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1702 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1703 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1704 DeleteContainerPointers(I->second);
1705 ScopeVariables.clear();
1706 DeleteContainerPointers(CurrentFnArguments);
1707 UserVariables.clear();
1709 AbstractVariables.clear();
1710 LabelsBeforeInsn.clear();
1711 LabelsAfterInsn.clear();
1715 // Register a source line with debug info. Returns the unique label that was
1716 // emitted and which provides correspondence to the source line list.
1717 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1723 DIDescriptor Scope(S);
1725 if (Scope.isCompileUnit()) {
1726 DICompileUnit CU(S);
1727 Fn = CU.getFilename();
1728 Dir = CU.getDirectory();
1729 } else if (Scope.isFile()) {
1731 Fn = F.getFilename();
1732 Dir = F.getDirectory();
1733 } else if (Scope.isSubprogram()) {
1735 Fn = SP.getFilename();
1736 Dir = SP.getDirectory();
1737 } else if (Scope.isLexicalBlockFile()) {
1738 DILexicalBlockFile DBF(S);
1739 Fn = DBF.getFilename();
1740 Dir = DBF.getDirectory();
1741 } else if (Scope.isLexicalBlock()) {
1742 DILexicalBlock DB(S);
1743 Fn = DB.getFilename();
1744 Dir = DB.getDirectory();
1746 llvm_unreachable("Unexpected scope info");
1748 Src = getOrCreateSourceID(Fn, Dir,
1749 Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1751 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1754 //===----------------------------------------------------------------------===//
1756 //===----------------------------------------------------------------------===//
1758 // Compute the size and offset of a DIE.
1760 DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1761 // Get the children.
1762 const std::vector<DIE *> &Children = Die->getChildren();
1764 // Record the abbreviation.
1765 assignAbbrevNumber(Die->getAbbrev());
1767 // Get the abbreviation for this DIE.
1768 unsigned AbbrevNumber = Die->getAbbrevNumber();
1769 const DIEAbbrev *Abbrev = Abbreviations->at(AbbrevNumber - 1);
1772 Die->setOffset(Offset);
1774 // Start the size with the size of abbreviation code.
1775 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1777 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1778 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1780 // Size the DIE attribute values.
1781 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1782 // Size attribute value.
1783 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1785 // Size the DIE children if any.
1786 if (!Children.empty()) {
1787 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1788 "Children flag not set");
1790 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1791 Offset = computeSizeAndOffset(Children[j], Offset);
1793 // End of children marker.
1794 Offset += sizeof(int8_t);
1797 Die->setSize(Offset - Die->getOffset());
1801 // Compute the size and offset of all the DIEs.
1802 void DwarfUnits::computeSizeAndOffsets() {
1803 // Offset from the beginning of debug info section.
1804 unsigned SecOffset = 0;
1805 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1806 E = CUs.end(); I != E; ++I) {
1807 (*I)->setDebugInfoOffset(SecOffset);
1809 sizeof(int32_t) + // Length of Compilation Unit Info
1810 sizeof(int16_t) + // DWARF version number
1811 sizeof(int32_t) + // Offset Into Abbrev. Section
1812 sizeof(int8_t); // Pointer Size (in bytes)
1814 unsigned EndOffset = computeSizeAndOffset((*I)->getCUDie(), Offset);
1815 SecOffset += EndOffset;
1819 // Emit initial Dwarf sections with a label at the start of each one.
1820 void DwarfDebug::emitSectionLabels() {
1821 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1823 // Dwarf sections base addresses.
1824 DwarfInfoSectionSym =
1825 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1826 DwarfAbbrevSectionSym =
1827 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1828 if (useSplitDwarf())
1829 DwarfAbbrevDWOSectionSym =
1830 emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
1831 "section_abbrev_dwo");
1832 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1834 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1835 emitSectionSym(Asm, MacroInfo);
1837 DwarfLineSectionSym =
1838 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1839 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1840 if (GenerateDwarfPubNamesSection)
1841 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1842 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1843 DwarfStrSectionSym =
1844 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1845 if (useSplitDwarf()) {
1846 DwarfStrDWOSectionSym =
1847 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1848 DwarfAddrSectionSym =
1849 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1851 DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1854 DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
1855 "section_debug_loc");
1857 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1858 emitSectionSym(Asm, TLOF.getDataSection());
1861 // Recursively emits a debug information entry.
1862 void DwarfDebug::emitDIE(DIE *Die, std::vector<DIEAbbrev *> *Abbrevs) {
1863 // Get the abbreviation for this DIE.
1864 unsigned AbbrevNumber = Die->getAbbrevNumber();
1865 const DIEAbbrev *Abbrev = Abbrevs->at(AbbrevNumber - 1);
1867 // Emit the code (index) for the abbreviation.
1868 if (Asm->isVerbose())
1869 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1870 Twine::utohexstr(Die->getOffset()) + ":0x" +
1871 Twine::utohexstr(Die->getSize()) + " " +
1872 dwarf::TagString(Abbrev->getTag()));
1873 Asm->EmitULEB128(AbbrevNumber);
1875 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1876 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1878 // Emit the DIE attribute values.
1879 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1880 unsigned Attr = AbbrevData[i].getAttribute();
1881 unsigned Form = AbbrevData[i].getForm();
1882 assert(Form && "Too many attributes for DIE (check abbreviation)");
1884 if (Asm->isVerbose())
1885 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1888 case dwarf::DW_AT_abstract_origin: {
1889 DIEEntry *E = cast<DIEEntry>(Values[i]);
1890 DIE *Origin = E->getEntry();
1891 unsigned Addr = Origin->getOffset();
1892 if (Form == dwarf::DW_FORM_ref_addr) {
1893 // For DW_FORM_ref_addr, output the offset from beginning of debug info
1894 // section. Origin->getOffset() returns the offset from start of the
1896 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1897 Addr += Holder.getCUOffset(Origin->getCompileUnit());
1899 Asm->EmitInt32(Addr);
1902 case dwarf::DW_AT_ranges: {
1903 // DW_AT_range Value encodes offset in debug_range section.
1904 DIEInteger *V = cast<DIEInteger>(Values[i]);
1906 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1907 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1911 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1913 DwarfDebugRangeSectionSym,
1918 case dwarf::DW_AT_location: {
1919 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
1920 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1921 Asm->EmitLabelReference(L->getValue(), 4);
1923 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1925 Values[i]->EmitValue(Asm, Form);
1929 case dwarf::DW_AT_accessibility: {
1930 if (Asm->isVerbose()) {
1931 DIEInteger *V = cast<DIEInteger>(Values[i]);
1932 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1934 Values[i]->EmitValue(Asm, Form);
1938 // Emit an attribute using the defined form.
1939 Values[i]->EmitValue(Asm, Form);
1944 // Emit the DIE children if any.
1945 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1946 const std::vector<DIE *> &Children = Die->getChildren();
1948 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1949 emitDIE(Children[j], Abbrevs);
1951 if (Asm->isVerbose())
1952 Asm->OutStreamer.AddComment("End Of Children Mark");
1957 // Emit the various dwarf units to the unit section USection with
1958 // the abbreviations going into ASection.
1959 void DwarfUnits::emitUnits(DwarfDebug *DD,
1960 const MCSection *USection,
1961 const MCSection *ASection,
1962 const MCSymbol *ASectionSym) {
1963 Asm->OutStreamer.SwitchSection(USection);
1964 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1965 E = CUs.end(); I != E; ++I) {
1966 CompileUnit *TheCU = *I;
1967 DIE *Die = TheCU->getCUDie();
1969 // Emit the compile units header.
1971 .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
1972 TheCU->getUniqueID()));
1974 // Emit size of content not including length itself
1975 unsigned ContentSize = Die->getSize() +
1976 sizeof(int16_t) + // DWARF version number
1977 sizeof(int32_t) + // Offset Into Abbrev. Section
1978 sizeof(int8_t); // Pointer Size (in bytes)
1980 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1981 Asm->EmitInt32(ContentSize);
1982 Asm->OutStreamer.AddComment("DWARF version number");
1983 Asm->EmitInt16(dwarf::DWARF_VERSION);
1984 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1985 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
1987 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1988 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1990 DD->emitDIE(Die, Abbreviations);
1991 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
1992 TheCU->getUniqueID()));
1996 /// For a given compile unit DIE, returns offset from beginning of debug info.
1997 unsigned DwarfUnits::getCUOffset(DIE *Die) {
1998 assert(Die->getTag() == dwarf::DW_TAG_compile_unit &&
1999 "Input DIE should be compile unit in getCUOffset.");
2000 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
2001 E = CUs.end(); I != E; ++I) {
2002 CompileUnit *TheCU = *I;
2003 if (TheCU->getCUDie() == Die)
2004 return TheCU->getDebugInfoOffset();
2006 llvm_unreachable("The compile unit DIE should belong to CUs in DwarfUnits.");
2009 // Emit the debug info section.
2010 void DwarfDebug::emitDebugInfo() {
2011 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2013 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
2014 Asm->getObjFileLowering().getDwarfAbbrevSection(),
2015 DwarfAbbrevSectionSym);
2018 // Emit the abbreviation section.
2019 void DwarfDebug::emitAbbreviations() {
2020 if (!useSplitDwarf())
2021 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
2024 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2027 void DwarfDebug::emitAbbrevs(const MCSection *Section,
2028 std::vector<DIEAbbrev *> *Abbrevs) {
2029 // Check to see if it is worth the effort.
2030 if (!Abbrevs->empty()) {
2031 // Start the debug abbrev section.
2032 Asm->OutStreamer.SwitchSection(Section);
2034 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
2035 Asm->OutStreamer.EmitLabel(Begin);
2037 // For each abbrevation.
2038 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
2039 // Get abbreviation data
2040 const DIEAbbrev *Abbrev = Abbrevs->at(i);
2042 // Emit the abbrevations code (base 1 index.)
2043 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2045 // Emit the abbreviations data.
2049 // Mark end of abbreviations.
2050 Asm->EmitULEB128(0, "EOM(3)");
2052 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
2053 Asm->OutStreamer.EmitLabel(End);
2057 // Emit the last address of the section and the end of the line matrix.
2058 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2059 // Define last address of section.
2060 Asm->OutStreamer.AddComment("Extended Op");
2063 Asm->OutStreamer.AddComment("Op size");
2064 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2065 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2066 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2068 Asm->OutStreamer.AddComment("Section end label");
2070 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2071 Asm->getDataLayout().getPointerSize());
2073 // Mark end of matrix.
2074 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2080 // Emit visible names into a hashed accelerator table section.
2081 void DwarfDebug::emitAccelNames() {
2082 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2083 dwarf::DW_FORM_data4));
2084 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2085 E = CUMap.end(); I != E; ++I) {
2086 CompileUnit *TheCU = I->second;
2087 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
2088 for (StringMap<std::vector<DIE*> >::const_iterator
2089 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2090 StringRef Name = GI->getKey();
2091 const std::vector<DIE *> &Entities = GI->second;
2092 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2093 DE = Entities.end(); DI != DE; ++DI)
2094 AT.AddName(Name, (*DI));
2098 AT.FinalizeTable(Asm, "Names");
2099 Asm->OutStreamer.SwitchSection(
2100 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2101 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2102 Asm->OutStreamer.EmitLabel(SectionBegin);
2104 // Emit the full data.
2105 AT.Emit(Asm, SectionBegin, &InfoHolder);
2108 // Emit objective C classes and categories into a hashed accelerator table
2110 void DwarfDebug::emitAccelObjC() {
2111 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2112 dwarf::DW_FORM_data4));
2113 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2114 E = CUMap.end(); I != E; ++I) {
2115 CompileUnit *TheCU = I->second;
2116 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
2117 for (StringMap<std::vector<DIE*> >::const_iterator
2118 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2119 StringRef Name = GI->getKey();
2120 const std::vector<DIE *> &Entities = GI->second;
2121 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2122 DE = Entities.end(); DI != DE; ++DI)
2123 AT.AddName(Name, (*DI));
2127 AT.FinalizeTable(Asm, "ObjC");
2128 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2129 .getDwarfAccelObjCSection());
2130 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2131 Asm->OutStreamer.EmitLabel(SectionBegin);
2133 // Emit the full data.
2134 AT.Emit(Asm, SectionBegin, &InfoHolder);
2137 // Emit namespace dies into a hashed accelerator table.
2138 void DwarfDebug::emitAccelNamespaces() {
2139 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2140 dwarf::DW_FORM_data4));
2141 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2142 E = CUMap.end(); I != E; ++I) {
2143 CompileUnit *TheCU = I->second;
2144 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2145 for (StringMap<std::vector<DIE*> >::const_iterator
2146 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2147 StringRef Name = GI->getKey();
2148 const std::vector<DIE *> &Entities = GI->second;
2149 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2150 DE = Entities.end(); DI != DE; ++DI)
2151 AT.AddName(Name, (*DI));
2155 AT.FinalizeTable(Asm, "namespac");
2156 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2157 .getDwarfAccelNamespaceSection());
2158 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2159 Asm->OutStreamer.EmitLabel(SectionBegin);
2161 // Emit the full data.
2162 AT.Emit(Asm, SectionBegin, &InfoHolder);
2165 // Emit type dies into a hashed accelerator table.
2166 void DwarfDebug::emitAccelTypes() {
2167 std::vector<DwarfAccelTable::Atom> Atoms;
2168 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2169 dwarf::DW_FORM_data4));
2170 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
2171 dwarf::DW_FORM_data2));
2172 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
2173 dwarf::DW_FORM_data1));
2174 DwarfAccelTable AT(Atoms);
2175 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2176 E = CUMap.end(); I != E; ++I) {
2177 CompileUnit *TheCU = I->second;
2178 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2179 = TheCU->getAccelTypes();
2180 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2181 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2182 StringRef Name = GI->getKey();
2183 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2184 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2185 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2186 AT.AddName(Name, (*DI).first, (*DI).second);
2190 AT.FinalizeTable(Asm, "types");
2191 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2192 .getDwarfAccelTypesSection());
2193 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2194 Asm->OutStreamer.EmitLabel(SectionBegin);
2196 // Emit the full data.
2197 AT.Emit(Asm, SectionBegin, &InfoHolder);
2200 /// emitDebugPubnames - Emit visible names into a debug pubnames section.
2202 void DwarfDebug::emitDebugPubnames() {
2203 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2205 typedef DenseMap<const MDNode*, CompileUnit*> CUMapType;
2206 for (CUMapType::iterator I = CUMap.begin(), E = CUMap.end(); I != E; ++I) {
2207 CompileUnit *TheCU = I->second;
2208 unsigned ID = TheCU->getUniqueID();
2210 if (TheCU->getGlobalNames().empty())
2213 // Start the dwarf pubnames section.
2214 Asm->OutStreamer.SwitchSection(
2215 Asm->getObjFileLowering().getDwarfPubNamesSection());
2217 Asm->OutStreamer.AddComment("Length of Public Names Info");
2218 Asm->EmitLabelDifference(Asm->GetTempSymbol("pubnames_end", ID),
2219 Asm->GetTempSymbol("pubnames_begin", ID), 4);
2221 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", ID));
2223 Asm->OutStreamer.AddComment("DWARF Version");
2224 Asm->EmitInt16(dwarf::DWARF_VERSION);
2226 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2227 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2228 DwarfInfoSectionSym);
2230 Asm->OutStreamer.AddComment("Compilation Unit Length");
2231 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(), ID),
2232 Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2235 const StringMap<DIE*> &Globals = TheCU->getGlobalNames();
2236 for (StringMap<DIE*>::const_iterator
2237 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2238 const char *Name = GI->getKeyData();
2239 const DIE *Entity = GI->second;
2241 Asm->OutStreamer.AddComment("DIE offset");
2242 Asm->EmitInt32(Entity->getOffset());
2244 if (Asm->isVerbose())
2245 Asm->OutStreamer.AddComment("External Name");
2246 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
2249 Asm->OutStreamer.AddComment("End Mark");
2251 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", ID));
2255 void DwarfDebug::emitDebugPubTypes() {
2256 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2257 E = CUMap.end(); I != E; ++I) {
2258 CompileUnit *TheCU = I->second;
2259 // Start the dwarf pubtypes section.
2260 Asm->OutStreamer.SwitchSection(
2261 Asm->getObjFileLowering().getDwarfPubTypesSection());
2262 Asm->OutStreamer.AddComment("Length of Public Types Info");
2263 Asm->EmitLabelDifference(
2264 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2265 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2267 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2268 TheCU->getUniqueID()));
2270 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2271 Asm->EmitInt16(dwarf::DWARF_VERSION);
2273 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2274 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2275 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(),
2276 TheCU->getUniqueID()),
2277 DwarfInfoSectionSym);
2279 Asm->OutStreamer.AddComment("Compilation Unit Length");
2280 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(),
2281 TheCU->getUniqueID()),
2282 Asm->GetTempSymbol(ISec->getLabelBeginName(),
2283 TheCU->getUniqueID()),
2286 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2287 for (StringMap<DIE*>::const_iterator
2288 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2289 const char *Name = GI->getKeyData();
2290 DIE *Entity = GI->second;
2292 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2293 Asm->EmitInt32(Entity->getOffset());
2295 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2296 // Emit the name with a terminating null byte.
2297 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2300 Asm->OutStreamer.AddComment("End Mark");
2302 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2303 TheCU->getUniqueID()));
2307 // Emit strings into a string section.
2308 void DwarfUnits::emitStrings(const MCSection *StrSection,
2309 const MCSection *OffsetSection = NULL,
2310 const MCSymbol *StrSecSym = NULL) {
2312 if (StringPool.empty()) return;
2314 // Start the dwarf str section.
2315 Asm->OutStreamer.SwitchSection(StrSection);
2317 // Get all of the string pool entries and put them in an array by their ID so
2318 // we can sort them.
2319 SmallVector<std::pair<unsigned,
2320 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2322 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2323 I = StringPool.begin(), E = StringPool.end();
2325 Entries.push_back(std::make_pair(I->second.second, &*I));
2327 array_pod_sort(Entries.begin(), Entries.end());
2329 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2330 // Emit a label for reference from debug information entries.
2331 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2333 // Emit the string itself with a terminating null byte.
2334 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2335 Entries[i].second->getKeyLength()+1));
2338 // If we've got an offset section go ahead and emit that now as well.
2339 if (OffsetSection) {
2340 Asm->OutStreamer.SwitchSection(OffsetSection);
2341 unsigned offset = 0;
2342 unsigned size = 4; // FIXME: DWARF64 is 8.
2343 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2344 Asm->OutStreamer.EmitIntValue(offset, size);
2345 offset += Entries[i].second->getKeyLength() + 1;
2350 // Emit strings into a string section.
2351 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2353 if (AddressPool.empty()) return;
2355 // Start the dwarf addr section.
2356 Asm->OutStreamer.SwitchSection(AddrSection);
2358 // Get all of the address pool entries and put them in an array by their ID so
2359 // we can sort them.
2360 SmallVector<std::pair<unsigned, const MCSymbol *>, 64> Entries;
2362 for (DenseMap<const MCSymbol *, unsigned>::iterator I = AddressPool.begin(),
2363 E = AddressPool.end();
2365 Entries.push_back(std::make_pair(I->second, I->first));
2367 array_pod_sort(Entries.begin(), Entries.end());
2369 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2370 // Emit a label for reference from debug information entries.
2371 if (const MCSymbol *Sym = Entries[i].second)
2372 Asm->EmitLabelReference(Sym, Asm->getDataLayout().getPointerSize());
2374 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2379 // Emit visible names into a debug str section.
2380 void DwarfDebug::emitDebugStr() {
2381 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2382 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2385 // Emit visible names into a debug loc section.
2386 void DwarfDebug::emitDebugLoc() {
2387 if (DotDebugLocEntries.empty())
2390 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2391 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2393 DotDebugLocEntry &Entry = *I;
2394 if (I + 1 != DotDebugLocEntries.end())
2398 // Start the dwarf loc section.
2399 Asm->OutStreamer.SwitchSection(
2400 Asm->getObjFileLowering().getDwarfLocSection());
2401 unsigned char Size = Asm->getDataLayout().getPointerSize();
2402 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2404 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2405 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2406 I != E; ++I, ++index) {
2407 DotDebugLocEntry &Entry = *I;
2408 if (Entry.isMerged()) continue;
2409 if (Entry.isEmpty()) {
2410 Asm->OutStreamer.EmitIntValue(0, Size);
2411 Asm->OutStreamer.EmitIntValue(0, Size);
2412 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2414 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size);
2415 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size);
2416 DIVariable DV(Entry.Variable);
2417 Asm->OutStreamer.AddComment("Loc expr size");
2418 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2419 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2420 Asm->EmitLabelDifference(end, begin, 2);
2421 Asm->OutStreamer.EmitLabel(begin);
2422 if (Entry.isInt()) {
2423 DIBasicType BTy(DV.getType());
2425 (BTy.getEncoding() == dwarf::DW_ATE_signed
2426 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2427 Asm->OutStreamer.AddComment("DW_OP_consts");
2428 Asm->EmitInt8(dwarf::DW_OP_consts);
2429 Asm->EmitSLEB128(Entry.getInt());
2431 Asm->OutStreamer.AddComment("DW_OP_constu");
2432 Asm->EmitInt8(dwarf::DW_OP_constu);
2433 Asm->EmitULEB128(Entry.getInt());
2435 } else if (Entry.isLocation()) {
2436 if (!DV.hasComplexAddress())
2438 Asm->EmitDwarfRegOp(Entry.Loc, DV.isIndirect());
2440 // Complex address entry.
2441 unsigned N = DV.getNumAddrElements();
2443 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2444 if (Entry.Loc.getOffset()) {
2446 Asm->EmitDwarfRegOp(Entry.Loc, DV.isIndirect());
2447 Asm->OutStreamer.AddComment("DW_OP_deref");
2448 Asm->EmitInt8(dwarf::DW_OP_deref);
2449 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2450 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2451 Asm->EmitSLEB128(DV.getAddrElement(1));
2453 // If first address element is OpPlus then emit
2454 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2455 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2456 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2460 Asm->EmitDwarfRegOp(Entry.Loc, DV.isIndirect());
2463 // Emit remaining complex address elements.
2464 for (; i < N; ++i) {
2465 uint64_t Element = DV.getAddrElement(i);
2466 if (Element == DIBuilder::OpPlus) {
2467 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2468 Asm->EmitULEB128(DV.getAddrElement(++i));
2469 } else if (Element == DIBuilder::OpDeref) {
2470 if (!Entry.Loc.isReg())
2471 Asm->EmitInt8(dwarf::DW_OP_deref);
2473 llvm_unreachable("unknown Opcode found in complex address");
2477 // else ... ignore constant fp. There is not any good way to
2478 // to represent them here in dwarf.
2479 Asm->OutStreamer.EmitLabel(end);
2484 // Emit visible names into a debug aranges section.
2485 void DwarfDebug::emitDebugARanges() {
2486 // Start the dwarf aranges section.
2487 Asm->OutStreamer.SwitchSection(
2488 Asm->getObjFileLowering().getDwarfARangesSection());
2491 // Emit visible names into a debug ranges section.
2492 void DwarfDebug::emitDebugRanges() {
2493 // Start the dwarf ranges section.
2494 Asm->OutStreamer.SwitchSection(
2495 Asm->getObjFileLowering().getDwarfRangesSection());
2496 unsigned char Size = Asm->getDataLayout().getPointerSize();
2497 for (SmallVectorImpl<const MCSymbol *>::iterator
2498 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2501 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size);
2503 Asm->OutStreamer.EmitIntValue(0, Size);
2507 // Emit visible names into a debug macinfo section.
2508 void DwarfDebug::emitDebugMacInfo() {
2509 if (const MCSection *LineInfo =
2510 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2511 // Start the dwarf macinfo section.
2512 Asm->OutStreamer.SwitchSection(LineInfo);
2516 // Emit inline info using following format.
2518 // 1. length of section
2519 // 2. Dwarf version number
2522 // Entries (one "entry" for each function that was inlined):
2524 // 1. offset into __debug_str section for MIPS linkage name, if exists;
2525 // otherwise offset into __debug_str for regular function name.
2526 // 2. offset into __debug_str section for regular function name.
2527 // 3. an unsigned LEB128 number indicating the number of distinct inlining
2528 // instances for the function.
2530 // The rest of the entry consists of a {die_offset, low_pc} pair for each
2531 // inlined instance; the die_offset points to the inlined_subroutine die in the
2532 // __debug_info section, and the low_pc is the starting address for the
2533 // inlining instance.
2534 void DwarfDebug::emitDebugInlineInfo() {
2535 if (!Asm->MAI->doesDwarfUseInlineInfoSection())
2541 Asm->OutStreamer.SwitchSection(
2542 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2544 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2545 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2546 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2548 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2550 Asm->OutStreamer.AddComment("Dwarf Version");
2551 Asm->EmitInt16(dwarf::DWARF_VERSION);
2552 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2553 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2555 for (SmallVectorImpl<const MDNode *>::iterator I = InlinedSPNodes.begin(),
2556 E = InlinedSPNodes.end(); I != E; ++I) {
2558 const MDNode *Node = *I;
2559 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2560 = InlineInfo.find(Node);
2561 SmallVectorImpl<InlineInfoLabels> &Labels = II->second;
2562 DISubprogram SP(Node);
2563 StringRef LName = SP.getLinkageName();
2564 StringRef Name = SP.getName();
2566 Asm->OutStreamer.AddComment("MIPS linkage name");
2568 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2569 DwarfStrSectionSym);
2571 Asm->EmitSectionOffset(
2572 InfoHolder.getStringPoolEntry(Function::getRealLinkageName(LName)),
2573 DwarfStrSectionSym);
2575 Asm->OutStreamer.AddComment("Function name");
2576 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2577 DwarfStrSectionSym);
2578 Asm->EmitULEB128(Labels.size(), "Inline count");
2580 for (SmallVectorImpl<InlineInfoLabels>::iterator LI = Labels.begin(),
2581 LE = Labels.end(); LI != LE; ++LI) {
2582 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2583 Asm->EmitInt32(LI->second->getOffset());
2585 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2586 Asm->OutStreamer.EmitSymbolValue(LI->first,
2587 Asm->getDataLayout().getPointerSize());
2591 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2594 // DWARF5 Experimental Separate Dwarf emitters.
2596 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2597 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2598 // DW_AT_ranges_base, DW_AT_addr_base. If DW_AT_ranges is present,
2599 // DW_AT_low_pc and DW_AT_high_pc are not used, and vice versa.
2600 CompileUnit *DwarfDebug::constructSkeletonCU(const MDNode *N) {
2601 DICompileUnit DIUnit(N);
2602 CompilationDir = DIUnit.getDirectory();
2604 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2605 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
2606 DIUnit.getLanguage(), Die, N, Asm,
2607 this, &SkeletonHolder);
2609 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2610 DIUnit.getSplitDebugFilename());
2612 // This should be a unique identifier when we want to build .dwp files.
2613 NewCU->addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8, 0);
2615 // Relocate to the beginning of the addr_base section, else 0 for the
2616 // beginning of the one for this compile unit.
2617 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2618 NewCU->addLabel(Die, dwarf::DW_AT_GNU_addr_base, dwarf::DW_FORM_sec_offset,
2619 DwarfAddrSectionSym);
2621 NewCU->addUInt(Die, dwarf::DW_AT_GNU_addr_base,
2622 dwarf::DW_FORM_sec_offset, 0);
2624 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2625 // into an entity. We're using 0, or a NULL label for this.
2626 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2628 // DW_AT_stmt_list is a offset of line number information for this
2629 // compile unit in debug_line section.
2630 // FIXME: Should handle multiple compile units.
2631 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2632 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
2633 DwarfLineSectionSym);
2635 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset, 0);
2637 if (!CompilationDir.empty())
2638 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2640 SkeletonHolder.addUnit(NewCU);
2641 SkeletonCUs.push_back(NewCU);
2646 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
2647 assert(useSplitDwarf() && "No split dwarf debug info?");
2648 emitAbbrevs(Section, &SkeletonAbbrevs);
2651 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2652 // compile units that would normally be in debug_info.
2653 void DwarfDebug::emitDebugInfoDWO() {
2654 assert(useSplitDwarf() && "No split dwarf debug info?");
2655 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
2656 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2657 DwarfAbbrevDWOSectionSym);
2660 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2661 // abbreviations for the .debug_info.dwo section.
2662 void DwarfDebug::emitDebugAbbrevDWO() {
2663 assert(useSplitDwarf() && "No split dwarf?");
2664 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2668 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2669 // string section and is identical in format to traditional .debug_str
2671 void DwarfDebug::emitDebugStrDWO() {
2672 assert(useSplitDwarf() && "No split dwarf?");
2673 const MCSection *OffSec = Asm->getObjFileLowering()
2674 .getDwarfStrOffDWOSection();
2675 const MCSymbol *StrSym = DwarfStrSectionSym;
2676 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),