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/Constants.h"
20 #include "llvm/Module.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCSection.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetFrameLowering.h"
30 #include "llvm/Target/TargetLoweringObjectFile.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Target/TargetOptions.h"
34 #include "llvm/Analysis/DebugInfo.h"
35 #include "llvm/Analysis/DIBuilder.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/ValueHandle.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/Timer.h"
45 #include "llvm/Support/Path.h"
48 static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print",
50 cl::desc("Disable debug info printing"));
52 static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
53 cl::desc("Make an absence of debug location information explicit."),
56 static cl::opt<bool> DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
57 cl::desc("Output prototype dwarf accelerator tables."),
61 const char *DWARFGroupName = "DWARF Emission";
62 const char *DbgTimerName = "DWARF Debug Writer";
63 } // end anonymous namespace
65 //===----------------------------------------------------------------------===//
67 /// Configuration values for initial hash set sizes (log2).
69 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
73 DIType DbgVariable::getType() const {
74 DIType Ty = Var.getType();
75 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
77 if (Var.isBlockByrefVariable()) {
78 /* Byref variables, in Blocks, are declared by the programmer as
79 "SomeType VarName;", but the compiler creates a
80 __Block_byref_x_VarName struct, and gives the variable VarName
81 either the struct, or a pointer to the struct, as its type. This
82 is necessary for various behind-the-scenes things the compiler
83 needs to do with by-reference variables in blocks.
85 However, as far as the original *programmer* is concerned, the
86 variable should still have type 'SomeType', as originally declared.
88 The following function dives into the __Block_byref_x_VarName
89 struct to find the original type of the variable. This will be
90 passed back to the code generating the type for the Debug
91 Information Entry for the variable 'VarName'. 'VarName' will then
92 have the original type 'SomeType' in its debug information.
94 The original type 'SomeType' will be the type of the field named
95 'VarName' inside the __Block_byref_x_VarName struct.
97 NOTE: In order for this to not completely fail on the debugger
98 side, the Debug Information Entry for the variable VarName needs to
99 have a DW_AT_location that tells the debugger how to unwind through
100 the pointers and __Block_byref_x_VarName struct to find the actual
101 value of the variable. The function addBlockByrefType does this. */
103 unsigned tag = Ty.getTag();
105 if (tag == dwarf::DW_TAG_pointer_type) {
106 DIDerivedType DTy = DIDerivedType(Ty);
107 subType = DTy.getTypeDerivedFrom();
110 DICompositeType blockStruct = DICompositeType(subType);
111 DIArray Elements = blockStruct.getTypeArray();
113 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
114 DIDescriptor Element = Elements.getElement(i);
115 DIDerivedType DT = DIDerivedType(Element);
116 if (getName() == DT.getName())
117 return (DT.getTypeDerivedFrom());
124 } // end llvm namespace
126 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
127 : Asm(A), MMI(Asm->MMI), FirstCU(0),
128 AbbreviationsSet(InitAbbreviationsSetSize),
130 NextStringPoolNumber = 0;
132 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
133 DwarfStrSectionSym = TextSectionSym = 0;
134 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
135 FunctionBeginSym = FunctionEndSym = 0;
137 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
141 DwarfDebug::~DwarfDebug() {
144 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
145 /// temporary label to it if SymbolStem is specified.
146 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
147 const char *SymbolStem = 0) {
148 Asm->OutStreamer.SwitchSection(Section);
149 if (!SymbolStem) return 0;
151 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
152 Asm->OutStreamer.EmitLabel(TmpSym);
156 MCSymbol *DwarfDebug::getStringPool() {
157 return Asm->GetTempSymbol("section_str");
160 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
161 std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
162 if (Entry.first) return Entry.first;
164 Entry.second = NextStringPoolNumber++;
165 return Entry.first = Asm->GetTempSymbol("string", Entry.second);
168 /// assignAbbrevNumber - Define a unique number for the abbreviation.
170 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
171 // Profile the node so that we can make it unique.
175 // Check the set for priors.
176 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
178 // If it's newly added.
179 if (InSet == &Abbrev) {
180 // Add to abbreviation list.
181 Abbreviations.push_back(&Abbrev);
183 // Assign the vector position + 1 as its number.
184 Abbrev.setNumber(Abbreviations.size());
186 // Assign existing abbreviation number.
187 Abbrev.setNumber(InSet->getNumber());
191 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
192 /// printer to not emit usual symbol prefix before the symbol name is used then
193 /// return linkage name after skipping this special LLVM prefix.
194 static StringRef getRealLinkageName(StringRef LinkageName) {
196 if (LinkageName.startswith(StringRef(&One, 1)))
197 return LinkageName.substr(1);
201 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
202 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
203 /// If there are global variables in this scope then create and insert
204 /// DIEs for these variables.
205 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
206 const MDNode *SPNode) {
207 DIE *SPDie = SPCU->getDIE(SPNode);
209 assert(SPDie && "Unable to find subprogram DIE!");
210 DISubprogram SP(SPNode);
212 DISubprogram SPDecl = SP.getFunctionDeclaration();
213 if (!SPDecl.isSubprogram()) {
214 // There is not any need to generate specification DIE for a function
215 // defined at compile unit level. If a function is defined inside another
216 // function then gdb prefers the definition at top level and but does not
217 // expect specification DIE in parent function. So avoid creating
218 // specification DIE for a function defined inside a function.
219 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
220 !SP.getContext().isFile() &&
221 !isSubprogramContext(SP.getContext())) {
222 SPCU->addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
225 DICompositeType SPTy = SP.getType();
226 DIArray Args = SPTy.getTypeArray();
227 unsigned SPTag = SPTy.getTag();
228 if (SPTag == dwarf::DW_TAG_subroutine_type)
229 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
230 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
231 DIType ATy = DIType(DIType(Args.getElement(i)));
232 SPCU->addType(Arg, ATy);
233 if (ATy.isArtificial())
234 SPCU->addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
235 SPDie->addChild(Arg);
237 DIE *SPDeclDie = SPDie;
238 SPDie = new DIE(dwarf::DW_TAG_subprogram);
239 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
244 // Pick up abstract subprogram DIE.
245 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
246 SPDie = new DIE(dwarf::DW_TAG_subprogram);
247 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
248 dwarf::DW_FORM_ref4, AbsSPDIE);
252 SPCU->addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
253 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
254 SPCU->addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
255 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
256 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
257 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
258 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
263 /// constructLexicalScope - Construct new DW_TAG_lexical_block
264 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
265 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
266 LexicalScope *Scope) {
267 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
268 if (Scope->isAbstractScope())
271 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
275 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
276 if (Ranges.size() > 1) {
277 // .debug_range section has not been laid out yet. Emit offset in
278 // .debug_range as a uint, size 4, for now. emitDIE will handle
279 // DW_AT_ranges appropriately.
280 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
281 DebugRangeSymbols.size()
282 * Asm->getTargetData().getPointerSize());
283 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
284 RE = Ranges.end(); RI != RE; ++RI) {
285 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
286 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
288 DebugRangeSymbols.push_back(NULL);
289 DebugRangeSymbols.push_back(NULL);
293 const MCSymbol *Start = getLabelBeforeInsn(RI->first);
294 const MCSymbol *End = getLabelAfterInsn(RI->second);
296 if (End == 0) return 0;
298 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
299 assert(End->isDefined() && "Invalid end label for an inlined scope!");
301 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
302 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
307 /// constructInlinedScopeDIE - This scope represents inlined body of
308 /// a function. Construct DIE to represent this concrete inlined copy
310 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
311 LexicalScope *Scope) {
312 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
313 assert(Ranges.empty() == false &&
314 "LexicalScope does not have instruction markers!");
316 if (!Scope->getScopeNode())
318 DIScope DS(Scope->getScopeNode());
319 DISubprogram InlinedSP = getDISubprogram(DS);
320 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
322 DEBUG(dbgs() << "Unable to find original DIE for inlined subprogram.");
326 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
327 const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
328 const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
330 if (StartLabel == 0 || EndLabel == 0) {
331 assert(0 && "Unexpected Start and End labels for a inlined scope!");
334 assert(StartLabel->isDefined() &&
335 "Invalid starting label for an inlined scope!");
336 assert(EndLabel->isDefined() &&
337 "Invalid end label for an inlined scope!");
339 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
340 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
341 dwarf::DW_FORM_ref4, OriginDIE);
343 if (Ranges.size() > 1) {
344 // .debug_range section has not been laid out yet. Emit offset in
345 // .debug_range as a uint, size 4, for now. emitDIE will handle
346 // DW_AT_ranges appropriately.
347 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
348 DebugRangeSymbols.size()
349 * Asm->getTargetData().getPointerSize());
350 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
351 RE = Ranges.end(); RI != RE; ++RI) {
352 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
353 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
355 DebugRangeSymbols.push_back(NULL);
356 DebugRangeSymbols.push_back(NULL);
358 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
360 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
364 InlinedSubprogramDIEs.insert(OriginDIE);
366 // Track the start label for this inlined function.
367 //.debug_inlined section specification does not clearly state how
368 // to emit inlined scope that is split into multiple instruction ranges.
369 // For now, use first instruction range and emit low_pc/high_pc pair and
370 // corresponding .debug_inlined section entry for this pair.
371 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
372 I = InlineInfo.find(InlinedSP);
374 if (I == InlineInfo.end()) {
375 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
376 InlinedSPNodes.push_back(InlinedSP);
378 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
380 DILocation DL(Scope->getInlinedAt());
381 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, TheCU->getID());
382 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
387 /// constructScopeDIE - Construct a DIE for this scope.
388 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
389 if (!Scope || !Scope->getScopeNode())
392 SmallVector<DIE *, 8> Children;
394 // Collect arguments for current function.
395 if (LScopes.isCurrentFunctionScope(Scope))
396 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
397 if (DbgVariable *ArgDV = CurrentFnArguments[i])
399 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope()))
400 Children.push_back(Arg);
402 // Collect lexical scope children first.
403 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
404 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
406 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope()))
407 Children.push_back(Variable);
408 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
409 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
410 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
411 Children.push_back(Nested);
412 DIScope DS(Scope->getScopeNode());
413 DIE *ScopeDIE = NULL;
414 if (Scope->getInlinedAt())
415 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
416 else if (DS.isSubprogram()) {
417 ProcessedSPNodes.insert(DS);
418 if (Scope->isAbstractScope()) {
419 ScopeDIE = TheCU->getDIE(DS);
420 // Note down abstract DIE.
422 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
425 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
428 // There is no need to emit empty lexical block DIE.
429 if (Children.empty())
431 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
434 if (!ScopeDIE) return NULL;
437 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
438 E = Children.end(); I != E; ++I)
439 ScopeDIE->addChild(*I);
441 if (DS.isSubprogram())
442 TheCU->addPubTypes(DISubprogram(DS));
444 if (DS.isSubprogram() && !Scope->isAbstractScope())
445 TheCU->addAccelName(DISubprogram(DS).getName(), ScopeDIE);
450 /// GetOrCreateSourceID - Look up the source id with the given directory and
451 /// source file names. If none currently exists, create a new id and insert it
452 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
454 unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName,
456 // If FE did not provide a file name, then assume stdin.
457 if (FileName.empty())
458 return GetOrCreateSourceID("<stdin>", StringRef());
460 // TODO: this might not belong here. See if we can factor this better.
461 if (DirName == CompilationDir)
464 unsigned SrcId = SourceIdMap.size()+1;
465 std::pair<std::string, std::string> SourceName =
466 std::make_pair(FileName, DirName);
467 std::pair<std::pair<std::string, std::string>, unsigned> Entry =
468 make_pair(SourceName, SrcId);
470 std::map<std::pair<std::string, std::string>, unsigned>::iterator I;
472 tie(I, NewlyInserted) = SourceIdMap.insert(Entry);
476 // Print out a .file directive to specify files for .loc directives.
477 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, Entry.first.second,
483 /// constructCompileUnit - Create new CompileUnit for the given
484 /// metadata node with tag DW_TAG_compile_unit.
485 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
486 DICompileUnit DIUnit(N);
487 StringRef FN = DIUnit.getFilename();
488 CompilationDir = DIUnit.getDirectory();
489 unsigned ID = GetOrCreateSourceID(FN, CompilationDir);
491 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
492 CompileUnit *NewCU = new CompileUnit(ID, Die, Asm, this);
493 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
494 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
495 DIUnit.getLanguage());
496 NewCU->addString(Die, dwarf::DW_AT_name, FN);
497 // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
498 // simplifies debug range entries.
499 NewCU->addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
500 // DW_AT_stmt_list is a offset of line number information for this
501 // compile unit in debug_line section.
502 if (Asm->MAI->doesDwarfRequireRelocationForSectionOffset())
503 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
504 Asm->GetTempSymbol("section_line"));
506 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
508 if (!CompilationDir.empty())
509 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
510 if (DIUnit.isOptimized())
511 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
513 StringRef Flags = DIUnit.getFlags();
515 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
517 if (unsigned RVer = DIUnit.getRunTimeVersion())
518 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
519 dwarf::DW_FORM_data1, RVer);
523 CUMap.insert(std::make_pair(N, NewCU));
527 static bool isObjCClass(StringRef Name) {
528 return Name.startswith("+") || Name.startswith("-");
531 static bool hasObjCCategory(StringRef Name) {
532 if (!isObjCClass(Name)) return false;
534 size_t pos = Name.find(')');
535 if (pos != std::string::npos) {
536 if (Name[pos+1] != ' ') return false;
542 static void getObjCClassCategory(StringRef In, StringRef &Class,
543 StringRef &Category) {
544 if (!hasObjCCategory(In)) {
545 Class = In.slice(In.find('[') + 1, In.find(' '));
550 Class = In.slice(In.find('[') + 1, In.find('('));
551 Category = In.slice(In.find('[') + 1, In.find(' '));
555 /// construct SubprogramDIE - Construct subprogram DIE.
556 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
558 CompileUnit *&CURef = SPMap[N];
564 if (!SP.isDefinition())
565 // This is a method declaration which will be handled while constructing
569 DISubprogram SPDecl = SP.getFunctionDeclaration();
571 if (SPDecl.isSubprogram()) {
572 DeclDie = TheCU->getOrCreateSubprogramDIE(SPDecl);
575 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
578 // Refer function declaration directly.
579 TheCU->addDIEEntry(SubprogramDie, dwarf::DW_AT_specification,
580 dwarf::DW_FORM_ref4, DeclDie);
584 TheCU->insertDIE(N, SubprogramDie);
586 // Add to context owner.
587 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
590 TheCU->addGlobal(SP.getName(), SubprogramDie);
592 // Add to Accel Names
593 TheCU->addAccelName(SP.getName(), SubprogramDie);
595 // If this is an Objective-C selector name add it to the ObjC accelerator too.
596 if (isObjCClass(SP.getName())) {
597 StringRef Class, Category;
598 getObjCClassCategory(SP.getName(), Class, Category);
599 TheCU->addAccelObjC(Class, SubprogramDie);
601 TheCU->addAccelObjC(Category, SubprogramDie);
607 /// collectInfoFromNamedMDNodes - Collect debug info from named mdnodes such
608 /// as llvm.dbg.enum and llvm.dbg.ty
609 void DwarfDebug::collectInfoFromNamedMDNodes(Module *M) {
610 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp"))
611 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
612 const MDNode *N = NMD->getOperand(i);
613 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
614 constructSubprogramDIE(CU, N);
617 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"))
618 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
619 const MDNode *N = NMD->getOperand(i);
620 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
621 CU->createGlobalVariableDIE(N);
624 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
625 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
626 DIType Ty(NMD->getOperand(i));
627 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
628 CU->getOrCreateTypeDIE(Ty);
631 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
632 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
633 DIType Ty(NMD->getOperand(i));
634 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
635 CU->getOrCreateTypeDIE(Ty);
639 /// collectLegacyDebugInfo - Collect debug info using DebugInfoFinder.
640 /// FIXME - Remove this when dragon-egg and llvm-gcc switch to DIBuilder.
641 bool DwarfDebug::collectLegacyDebugInfo(Module *M) {
642 DebugInfoFinder DbgFinder;
643 DbgFinder.processModule(*M);
645 bool HasDebugInfo = false;
646 // Scan all the compile-units to see if there are any marked as the main
647 // unit. If not, we do not generate debug info.
648 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
649 E = DbgFinder.compile_unit_end(); I != E; ++I) {
650 if (DICompileUnit(*I).isMain()) {
655 if (!HasDebugInfo) return false;
657 // Create all the compile unit DIEs.
658 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
659 E = DbgFinder.compile_unit_end(); I != E; ++I)
660 constructCompileUnit(*I);
662 // Create DIEs for each global variable.
663 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
664 E = DbgFinder.global_variable_end(); I != E; ++I) {
665 const MDNode *N = *I;
666 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
667 CU->createGlobalVariableDIE(N);
670 // Create DIEs for each subprogram.
671 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
672 E = DbgFinder.subprogram_end(); I != E; ++I) {
673 const MDNode *N = *I;
674 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
675 constructSubprogramDIE(CU, N);
681 /// beginModule - Emit all Dwarf sections that should come prior to the
682 /// content. Create global DIEs and emit initial debug info sections.
683 /// This is invoked by the target AsmPrinter.
684 void DwarfDebug::beginModule(Module *M) {
685 if (DisableDebugInfoPrinting)
688 // If module has named metadata anchors then use them, otherwise scan the
689 // module using debug info finder to collect debug info.
690 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
692 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
693 DICompileUnit CUNode(CU_Nodes->getOperand(i));
694 CompileUnit *CU = constructCompileUnit(CUNode);
695 DIArray GVs = CUNode.getGlobalVariables();
696 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
697 CU->createGlobalVariableDIE(GVs.getElement(i));
698 DIArray SPs = CUNode.getSubprograms();
699 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
700 constructSubprogramDIE(CU, SPs.getElement(i));
701 DIArray EnumTypes = CUNode.getEnumTypes();
702 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
703 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
704 DIArray RetainedTypes = CUNode.getRetainedTypes();
705 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
706 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
708 } else if (!collectLegacyDebugInfo(M))
711 collectInfoFromNamedMDNodes(M);
713 // Tell MMI that we have debug info.
714 MMI->setDebugInfoAvailability(true);
716 // Emit initial sections.
719 // Prime section data.
720 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
723 /// endModule - Emit all Dwarf sections that should come after the content.
725 void DwarfDebug::endModule() {
726 if (!FirstCU) return;
727 const Module *M = MMI->getModule();
728 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
730 // Collect info for variables that were optimized out.
731 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
732 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
733 DICompileUnit TheCU(CU_Nodes->getOperand(i));
734 DIArray Subprograms = TheCU.getSubprograms();
735 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
736 DISubprogram SP(Subprograms.getElement(i));
737 if (ProcessedSPNodes.count(SP) != 0) continue;
738 if (!SP.Verify()) continue;
739 if (!SP.isDefinition()) continue;
740 DIArray Variables = SP.getVariables();
741 if (Variables.getNumElements() == 0) continue;
743 LexicalScope *Scope =
744 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
745 DeadFnScopeMap[SP] = Scope;
747 // Construct subprogram DIE and add variables DIEs.
748 CompileUnit *SPCU = CUMap.lookup(TheCU);
749 assert(SPCU && "Unable to find Compile Unit!");
750 constructSubprogramDIE(SPCU, SP);
751 DIE *ScopeDIE = SPCU->getDIE(SP);
752 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
753 DIVariable DV(Variables.getElement(vi));
754 if (!DV.Verify()) continue;
755 DbgVariable *NewVar = new DbgVariable(DV, NULL);
756 if (DIE *VariableDIE =
757 SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
758 ScopeDIE->addChild(VariableDIE);
764 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
765 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
766 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
768 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
771 // Emit DW_AT_containing_type attribute to connect types with their
772 // vtable holding type.
773 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
774 CUE = CUMap.end(); CUI != CUE; ++CUI) {
775 CompileUnit *TheCU = CUI->second;
776 TheCU->constructContainingTypeDIEs();
779 // Standard sections final addresses.
780 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
781 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
782 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
783 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
785 // End text sections.
786 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
787 Asm->OutStreamer.SwitchSection(SectionMap[i]);
788 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
791 // Compute DIE offsets and sizes.
792 computeSizeAndOffsets();
794 // Emit all the DIEs into a debug info section
797 // Corresponding abbreviations into a abbrev section.
800 // Emit info into a dwarf accelerator table sections.
801 if (DwarfAccelTables) {
804 emitAccelNamespaces();
808 // Emit info into a debug pubnames section.
811 // Emit info into a debug pubtypes section.
814 // Emit info into a debug loc section.
817 // Emit info into a debug aranges section.
820 // Emit info into a debug ranges section.
823 // Emit info into a debug macinfo section.
827 emitDebugInlineInfo();
829 // Emit info into a debug str section.
833 DeleteContainerSeconds(DeadFnScopeMap);
835 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
836 E = CUMap.end(); I != E; ++I)
838 FirstCU = NULL; // Reset for the next Module, if any.
841 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
842 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
844 LLVMContext &Ctx = DV->getContext();
845 // More then one inlined variable corresponds to one abstract variable.
846 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
847 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
849 return AbsDbgVariable;
851 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
855 AbsDbgVariable = new DbgVariable(Var, NULL);
856 addScopeVariable(Scope, AbsDbgVariable);
857 AbstractVariables[Var] = AbsDbgVariable;
858 return AbsDbgVariable;
861 /// addCurrentFnArgument - If Var is a current function argument then add
862 /// it to CurrentFnArguments list.
863 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
864 DbgVariable *Var, LexicalScope *Scope) {
865 if (!LScopes.isCurrentFunctionScope(Scope))
867 DIVariable DV = Var->getVariable();
868 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
870 unsigned ArgNo = DV.getArgNumber();
874 size_t Size = CurrentFnArguments.size();
876 CurrentFnArguments.resize(MF->getFunction()->arg_size());
877 // llvm::Function argument size is not good indicator of how many
878 // arguments does the function have at source level.
880 CurrentFnArguments.resize(ArgNo * 2);
881 CurrentFnArguments[ArgNo - 1] = Var;
885 /// collectVariableInfoFromMMITable - Collect variable information from
886 /// side table maintained by MMI.
888 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
889 SmallPtrSet<const MDNode *, 16> &Processed) {
890 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
891 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
892 VE = VMap.end(); VI != VE; ++VI) {
893 const MDNode *Var = VI->first;
895 Processed.insert(Var);
897 const std::pair<unsigned, DebugLoc> &VP = VI->second;
899 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
901 // If variable scope is not found then skip this variable.
905 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
906 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
907 RegVar->setFrameIndex(VP.first);
908 if (!addCurrentFnArgument(MF, RegVar, Scope))
909 addScopeVariable(Scope, RegVar);
911 AbsDbgVariable->setFrameIndex(VP.first);
915 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
916 /// DBG_VALUE instruction, is in a defined reg.
917 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
918 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
919 return MI->getNumOperands() == 3 &&
920 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
921 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
924 /// getDebugLocEntry - Get .debug_loc entry for the instruction range starting
926 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
927 const MCSymbol *FLabel,
928 const MCSymbol *SLabel,
929 const MachineInstr *MI) {
930 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
932 if (MI->getNumOperands() != 3) {
933 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
934 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
936 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
937 MachineLocation MLoc;
938 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
939 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
941 if (MI->getOperand(0).isImm())
942 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
943 if (MI->getOperand(0).isFPImm())
944 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
945 if (MI->getOperand(0).isCImm())
946 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
948 assert(0 && "Unexpected 3 operand DBG_VALUE instruction!");
949 return DotDebugLocEntry();
952 /// collectVariableInfo - Find variables for each lexical scope.
954 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
955 SmallPtrSet<const MDNode *, 16> &Processed) {
957 /// collection info from MMI table.
958 collectVariableInfoFromMMITable(MF, Processed);
960 for (SmallVectorImpl<const MDNode*>::const_iterator
961 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
963 const MDNode *Var = *UVI;
964 if (Processed.count(Var))
967 // History contains relevant DBG_VALUE instructions for Var and instructions
969 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
972 const MachineInstr *MInsn = History.front();
975 LexicalScope *Scope = NULL;
976 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
977 DISubprogram(DV.getContext()).describes(MF->getFunction()))
978 Scope = LScopes.getCurrentFunctionScope();
980 if (DV.getVersion() <= LLVMDebugVersion9)
981 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
983 if (MDNode *IA = DV.getInlinedAt())
984 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
986 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
989 // If variable scope is not found then skip this variable.
993 Processed.insert(DV);
994 assert(MInsn->isDebugValue() && "History must begin with debug value");
995 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
996 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
997 if (!addCurrentFnArgument(MF, RegVar, Scope))
998 addScopeVariable(Scope, RegVar);
1000 AbsVar->setMInsn(MInsn);
1002 // Simple ranges that are fully coalesced.
1003 if (History.size() <= 1 || (History.size() == 2 &&
1004 MInsn->isIdenticalTo(History.back()))) {
1005 RegVar->setMInsn(MInsn);
1009 // handle multiple DBG_VALUE instructions describing one variable.
1010 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1012 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1013 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1014 const MachineInstr *Begin = *HI;
1015 assert(Begin->isDebugValue() && "Invalid History entry");
1017 // Check if DBG_VALUE is truncating a range.
1018 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1019 && !Begin->getOperand(0).getReg())
1022 // Compute the range for a register location.
1023 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1024 const MCSymbol *SLabel = 0;
1027 // If Begin is the last instruction in History then its value is valid
1028 // until the end of the function.
1029 SLabel = FunctionEndSym;
1031 const MachineInstr *End = HI[1];
1032 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1033 << "\t" << *Begin << "\t" << *End << "\n");
1034 if (End->isDebugValue())
1035 SLabel = getLabelBeforeInsn(End);
1037 // End is a normal instruction clobbering the range.
1038 SLabel = getLabelAfterInsn(End);
1039 assert(SLabel && "Forgot label after clobber instruction");
1044 // The value is valid until the next DBG_VALUE or clobber.
1045 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1047 DotDebugLocEntries.push_back(DotDebugLocEntry());
1050 // Collect info for variables that were optimized out.
1051 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1052 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1053 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1054 DIVariable DV(Variables.getElement(i));
1055 if (!DV || !DV.Verify() || !Processed.insert(DV))
1057 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1058 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1062 /// getLabelBeforeInsn - Return Label preceding the instruction.
1063 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1064 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1065 assert(Label && "Didn't insert label before instruction");
1069 /// getLabelAfterInsn - Return Label immediately following the instruction.
1070 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1071 return LabelsAfterInsn.lookup(MI);
1074 /// beginInstruction - Process beginning of an instruction.
1075 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1076 // Check if source location changes, but ignore DBG_VALUE locations.
1077 if (!MI->isDebugValue()) {
1078 DebugLoc DL = MI->getDebugLoc();
1079 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1080 unsigned Flags = DWARF2_FLAG_IS_STMT;
1082 if (DL == PrologEndLoc) {
1083 Flags |= DWARF2_FLAG_PROLOGUE_END;
1084 PrologEndLoc = DebugLoc();
1086 if (!DL.isUnknown()) {
1087 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1088 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1090 recordSourceLine(0, 0, 0, 0);
1094 // Insert labels where requested.
1095 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1096 LabelsBeforeInsn.find(MI);
1099 if (I == LabelsBeforeInsn.end())
1102 // Label already assigned.
1107 PrevLabel = MMI->getContext().CreateTempSymbol();
1108 Asm->OutStreamer.EmitLabel(PrevLabel);
1110 I->second = PrevLabel;
1113 /// endInstruction - Process end of an instruction.
1114 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1115 // Don't create a new label after DBG_VALUE instructions.
1116 // They don't generate code.
1117 if (!MI->isDebugValue())
1120 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1121 LabelsAfterInsn.find(MI);
1124 if (I == LabelsAfterInsn.end())
1127 // Label already assigned.
1131 // We need a label after this instruction.
1133 PrevLabel = MMI->getContext().CreateTempSymbol();
1134 Asm->OutStreamer.EmitLabel(PrevLabel);
1136 I->second = PrevLabel;
1139 /// identifyScopeMarkers() -
1140 /// Each LexicalScope has first instruction and last instruction to mark
1141 /// beginning and end of a scope respectively. Create an inverse map that list
1142 /// scopes starts (and ends) with an instruction. One instruction may start (or
1143 /// end) multiple scopes. Ignore scopes that are not reachable.
1144 void DwarfDebug::identifyScopeMarkers() {
1145 SmallVector<LexicalScope *, 4> WorkList;
1146 WorkList.push_back(LScopes.getCurrentFunctionScope());
1147 while (!WorkList.empty()) {
1148 LexicalScope *S = WorkList.pop_back_val();
1150 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1151 if (!Children.empty())
1152 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1153 SE = Children.end(); SI != SE; ++SI)
1154 WorkList.push_back(*SI);
1156 if (S->isAbstractScope())
1159 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1162 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1163 RE = Ranges.end(); RI != RE; ++RI) {
1164 assert(RI->first && "InsnRange does not have first instruction!");
1165 assert(RI->second && "InsnRange does not have second instruction!");
1166 requestLabelBeforeInsn(RI->first);
1167 requestLabelAfterInsn(RI->second);
1172 /// getScopeNode - Get MDNode for DebugLoc's scope.
1173 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1174 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1175 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1176 return DL.getScope(Ctx);
1179 /// getFnDebugLoc - Walk up the scope chain of given debug loc and find
1180 /// line number info for the function.
1181 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1182 const MDNode *Scope = getScopeNode(DL, Ctx);
1183 DISubprogram SP = getDISubprogram(Scope);
1185 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1189 /// beginFunction - Gather pre-function debug information. Assumes being
1190 /// emitted immediately after the function entry point.
1191 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1192 if (!MMI->hasDebugInfo()) return;
1193 LScopes.initialize(*MF);
1194 if (LScopes.empty()) return;
1195 identifyScopeMarkers();
1197 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1198 Asm->getFunctionNumber());
1199 // Assumes in correct section after the entry point.
1200 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1202 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1204 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1205 /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1206 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1208 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1210 bool AtBlockEntry = true;
1211 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1213 const MachineInstr *MI = II;
1215 if (MI->isDebugValue()) {
1216 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1218 // Keep track of user variables.
1220 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1222 // Variable is in a register, we need to check for clobbers.
1223 if (isDbgValueInDefinedReg(MI))
1224 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1226 // Check the history of this variable.
1227 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1228 if (History.empty()) {
1229 UserVariables.push_back(Var);
1230 // The first mention of a function argument gets the FunctionBeginSym
1231 // label, so arguments are visible when breaking at function entry.
1233 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1234 DISubprogram(getDISubprogram(DV.getContext()))
1235 .describes(MF->getFunction()))
1236 LabelsBeforeInsn[MI] = FunctionBeginSym;
1238 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1239 const MachineInstr *Prev = History.back();
1240 if (Prev->isDebugValue()) {
1241 // Coalesce identical entries at the end of History.
1242 if (History.size() >= 2 &&
1243 Prev->isIdenticalTo(History[History.size() - 2])) {
1244 DEBUG(dbgs() << "Coalesce identical DBG_VALUE entries:\n"
1246 << "\t" << *History[History.size() - 2] << "\n");
1250 // Terminate old register assignments that don't reach MI;
1251 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1252 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1253 isDbgValueInDefinedReg(Prev)) {
1254 // Previous register assignment needs to terminate at the end of
1256 MachineBasicBlock::const_iterator LastMI =
1257 PrevMBB->getLastNonDebugInstr();
1258 if (LastMI == PrevMBB->end()) {
1259 // Drop DBG_VALUE for empty range.
1260 DEBUG(dbgs() << "Drop DBG_VALUE for empty range:\n"
1261 << "\t" << *Prev << "\n");
1265 // Terminate after LastMI.
1266 History.push_back(LastMI);
1271 History.push_back(MI);
1273 // Not a DBG_VALUE instruction.
1275 AtBlockEntry = false;
1277 // First known non DBG_VALUE location marks beginning of function
1279 if (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown())
1280 PrologEndLoc = MI->getDebugLoc();
1282 // Check if the instruction clobbers any registers with debug vars.
1283 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1284 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1285 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1287 for (const unsigned *AI = TRI->getOverlaps(MOI->getReg());
1288 unsigned Reg = *AI; ++AI) {
1289 const MDNode *Var = LiveUserVar[Reg];
1292 // Reg is now clobbered.
1293 LiveUserVar[Reg] = 0;
1295 // Was MD last defined by a DBG_VALUE referring to Reg?
1296 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1297 if (HistI == DbgValues.end())
1299 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1300 if (History.empty())
1302 const MachineInstr *Prev = History.back();
1303 // Sanity-check: Register assignments are terminated at the end of
1305 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1307 // Is the variable still in Reg?
1308 if (!isDbgValueInDefinedReg(Prev) ||
1309 Prev->getOperand(0).getReg() != Reg)
1311 // Var is clobbered. Make sure the next instruction gets a label.
1312 History.push_back(MI);
1319 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1321 SmallVectorImpl<const MachineInstr*> &History = I->second;
1322 if (History.empty())
1325 // Make sure the final register assignments are terminated.
1326 const MachineInstr *Prev = History.back();
1327 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1328 const MachineBasicBlock *PrevMBB = Prev->getParent();
1329 MachineBasicBlock::const_iterator LastMI =
1330 PrevMBB->getLastNonDebugInstr();
1331 if (LastMI == PrevMBB->end())
1332 // Drop DBG_VALUE for empty range.
1335 // Terminate after LastMI.
1336 History.push_back(LastMI);
1339 // Request labels for the full history.
1340 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1341 const MachineInstr *MI = History[i];
1342 if (MI->isDebugValue())
1343 requestLabelBeforeInsn(MI);
1345 requestLabelAfterInsn(MI);
1349 PrevInstLoc = DebugLoc();
1350 PrevLabel = FunctionBeginSym;
1352 // Record beginning of function.
1353 if (!PrologEndLoc.isUnknown()) {
1354 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1355 MF->getFunction()->getContext());
1356 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1357 FnStartDL.getScope(MF->getFunction()->getContext()),
1358 DWARF2_FLAG_IS_STMT);
1362 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1363 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1364 ScopeVariables[LS].push_back(Var);
1365 // Vars.push_back(Var);
1368 /// endFunction - Gather and emit post-function debug information.
1370 void DwarfDebug::endFunction(const MachineFunction *MF) {
1371 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1373 // Define end label for subprogram.
1374 FunctionEndSym = Asm->GetTempSymbol("func_end",
1375 Asm->getFunctionNumber());
1376 // Assumes in correct section after the entry point.
1377 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1379 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1380 collectVariableInfo(MF, ProcessedVars);
1382 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1383 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1384 assert(TheCU && "Unable to find compile unit!");
1386 // Construct abstract scopes.
1387 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1388 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1389 LexicalScope *AScope = AList[i];
1390 DISubprogram SP(AScope->getScopeNode());
1392 // Collect info for variables that were optimized out.
1393 DIArray Variables = SP.getVariables();
1394 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1395 DIVariable DV(Variables.getElement(i));
1396 if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1398 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1399 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1402 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1403 constructScopeDIE(TheCU, AScope);
1406 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1408 if (!DisableFramePointerElim(*MF))
1409 TheCU->addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
1410 dwarf::DW_FORM_flag, 1);
1412 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1413 MMI->getFrameMoves()));
1416 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1417 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1418 DeleteContainerPointers(I->second);
1419 ScopeVariables.clear();
1420 DeleteContainerPointers(CurrentFnArguments);
1421 UserVariables.clear();
1423 AbstractVariables.clear();
1424 LabelsBeforeInsn.clear();
1425 LabelsAfterInsn.clear();
1429 /// recordSourceLine - Register a source line with debug info. Returns the
1430 /// unique label that was emitted and which provides correspondence to
1431 /// the source line list.
1432 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1438 DIDescriptor Scope(S);
1440 if (Scope.isCompileUnit()) {
1441 DICompileUnit CU(S);
1442 Fn = CU.getFilename();
1443 Dir = CU.getDirectory();
1444 } else if (Scope.isFile()) {
1446 Fn = F.getFilename();
1447 Dir = F.getDirectory();
1448 } else if (Scope.isSubprogram()) {
1450 Fn = SP.getFilename();
1451 Dir = SP.getDirectory();
1452 } else if (Scope.isLexicalBlockFile()) {
1453 DILexicalBlockFile DBF(S);
1454 Fn = DBF.getFilename();
1455 Dir = DBF.getDirectory();
1456 } else if (Scope.isLexicalBlock()) {
1457 DILexicalBlock DB(S);
1458 Fn = DB.getFilename();
1459 Dir = DB.getDirectory();
1461 assert(0 && "Unexpected scope info");
1463 Src = GetOrCreateSourceID(Fn, Dir);
1465 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1468 //===----------------------------------------------------------------------===//
1470 //===----------------------------------------------------------------------===//
1472 /// computeSizeAndOffset - Compute the size and offset of a DIE.
1475 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
1476 // Get the children.
1477 const std::vector<DIE *> &Children = Die->getChildren();
1479 // If not last sibling and has children then add sibling offset attribute.
1480 if (!Last && !Children.empty())
1481 Die->addSiblingOffset(DIEValueAllocator);
1483 // Record the abbreviation.
1484 assignAbbrevNumber(Die->getAbbrev());
1486 // Get the abbreviation for this DIE.
1487 unsigned AbbrevNumber = Die->getAbbrevNumber();
1488 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1491 Die->setOffset(Offset);
1493 // Start the size with the size of abbreviation code.
1494 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1496 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1497 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1499 // Size the DIE attribute values.
1500 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1501 // Size attribute value.
1502 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1504 // Size the DIE children if any.
1505 if (!Children.empty()) {
1506 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1507 "Children flag not set");
1509 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1510 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
1512 // End of children marker.
1513 Offset += sizeof(int8_t);
1516 Die->setSize(Offset - Die->getOffset());
1520 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
1522 void DwarfDebug::computeSizeAndOffsets() {
1523 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1524 E = CUMap.end(); I != E; ++I) {
1525 // Compute size of compile unit header.
1527 sizeof(int32_t) + // Length of Compilation Unit Info
1528 sizeof(int16_t) + // DWARF version number
1529 sizeof(int32_t) + // Offset Into Abbrev. Section
1530 sizeof(int8_t); // Pointer Size (in bytes)
1531 computeSizeAndOffset(I->second->getCUDie(), Offset, true);
1535 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
1536 /// the start of each one.
1537 void DwarfDebug::EmitSectionLabels() {
1538 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1540 // Dwarf sections base addresses.
1541 DwarfInfoSectionSym =
1542 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1543 DwarfAbbrevSectionSym =
1544 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1545 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
1547 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1548 EmitSectionSym(Asm, MacroInfo);
1550 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1551 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
1552 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1553 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1554 DwarfStrSectionSym =
1555 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
1556 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1559 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
1560 "section_debug_loc");
1562 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1563 EmitSectionSym(Asm, TLOF.getDataSection());
1566 /// emitDIE - Recursively emits a debug information entry.
1568 void DwarfDebug::emitDIE(DIE *Die) {
1569 // Get the abbreviation for this DIE.
1570 unsigned AbbrevNumber = Die->getAbbrevNumber();
1571 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1573 // Emit the code (index) for the abbreviation.
1574 if (Asm->isVerbose())
1575 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1576 Twine::utohexstr(Die->getOffset()) + ":0x" +
1577 Twine::utohexstr(Die->getSize()) + " " +
1578 dwarf::TagString(Abbrev->getTag()));
1579 Asm->EmitULEB128(AbbrevNumber);
1581 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1582 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1584 // Emit the DIE attribute values.
1585 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1586 unsigned Attr = AbbrevData[i].getAttribute();
1587 unsigned Form = AbbrevData[i].getForm();
1588 assert(Form && "Too many attributes for DIE (check abbreviation)");
1590 if (Asm->isVerbose())
1591 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1594 case dwarf::DW_AT_sibling:
1595 Asm->EmitInt32(Die->getSiblingOffset());
1597 case dwarf::DW_AT_abstract_origin: {
1598 DIEEntry *E = cast<DIEEntry>(Values[i]);
1599 DIE *Origin = E->getEntry();
1600 unsigned Addr = Origin->getOffset();
1601 Asm->EmitInt32(Addr);
1604 case dwarf::DW_AT_ranges: {
1605 // DW_AT_range Value encodes offset in debug_range section.
1606 DIEInteger *V = cast<DIEInteger>(Values[i]);
1608 if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
1609 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1613 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1615 DwarfDebugRangeSectionSym,
1620 case dwarf::DW_AT_location: {
1621 if (DIELabel *L = dyn_cast<DIELabel>(Values[i]))
1622 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1624 Values[i]->EmitValue(Asm, Form);
1627 case dwarf::DW_AT_accessibility: {
1628 if (Asm->isVerbose()) {
1629 DIEInteger *V = cast<DIEInteger>(Values[i]);
1630 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1632 Values[i]->EmitValue(Asm, Form);
1636 // Emit an attribute using the defined form.
1637 Values[i]->EmitValue(Asm, Form);
1642 // Emit the DIE children if any.
1643 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1644 const std::vector<DIE *> &Children = Die->getChildren();
1646 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1647 emitDIE(Children[j]);
1649 if (Asm->isVerbose())
1650 Asm->OutStreamer.AddComment("End Of Children Mark");
1655 /// emitDebugInfo - Emit the debug info section.
1657 void DwarfDebug::emitDebugInfo() {
1658 // Start debug info section.
1659 Asm->OutStreamer.SwitchSection(
1660 Asm->getObjFileLowering().getDwarfInfoSection());
1661 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1662 E = CUMap.end(); I != E; ++I) {
1663 CompileUnit *TheCU = I->second;
1664 DIE *Die = TheCU->getCUDie();
1666 // Emit the compile units header.
1667 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
1670 // Emit size of content not including length itself
1671 unsigned ContentSize = Die->getSize() +
1672 sizeof(int16_t) + // DWARF version number
1673 sizeof(int32_t) + // Offset Into Abbrev. Section
1674 sizeof(int8_t); // Pointer Size (in bytes)
1676 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1677 Asm->EmitInt32(ContentSize);
1678 Asm->OutStreamer.AddComment("DWARF version number");
1679 Asm->EmitInt16(dwarf::DWARF_VERSION);
1680 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1681 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
1682 DwarfAbbrevSectionSym);
1683 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1684 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1687 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
1691 /// emitAbbreviations - Emit the abbreviation section.
1693 void DwarfDebug::emitAbbreviations() const {
1694 // Check to see if it is worth the effort.
1695 if (!Abbreviations.empty()) {
1696 // Start the debug abbrev section.
1697 Asm->OutStreamer.SwitchSection(
1698 Asm->getObjFileLowering().getDwarfAbbrevSection());
1700 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
1702 // For each abbrevation.
1703 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1704 // Get abbreviation data
1705 const DIEAbbrev *Abbrev = Abbreviations[i];
1707 // Emit the abbrevations code (base 1 index.)
1708 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1710 // Emit the abbreviations data.
1714 // Mark end of abbreviations.
1715 Asm->EmitULEB128(0, "EOM(3)");
1717 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
1721 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
1722 /// the line matrix.
1724 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1725 // Define last address of section.
1726 Asm->OutStreamer.AddComment("Extended Op");
1729 Asm->OutStreamer.AddComment("Op size");
1730 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
1731 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1732 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1734 Asm->OutStreamer.AddComment("Section end label");
1736 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1737 Asm->getTargetData().getPointerSize(),
1740 // Mark end of matrix.
1741 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1747 /// emitAccelNames - Emit visible names into a hashed accelerator table
1749 void DwarfDebug::emitAccelNames() {
1750 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1751 dwarf::DW_FORM_data4));
1752 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1753 E = CUMap.end(); I != E; ++I) {
1754 CompileUnit *TheCU = I->second;
1755 const StringMap<DIE*> &Names = TheCU->getAccelNames();
1756 for (StringMap<DIE*>::const_iterator
1757 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1758 const char *Name = GI->getKeyData();
1759 DIE *Entity = GI->second;
1760 AT.AddName(Name, Entity);
1764 AT.FinalizeTable(Asm, "Names");
1765 Asm->OutStreamer.SwitchSection(
1766 Asm->getObjFileLowering().getDwarfAccelNamesSection());
1767 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1768 Asm->OutStreamer.EmitLabel(SectionBegin);
1770 // Emit the full data.
1771 AT.Emit(Asm, SectionBegin, this);
1774 /// emitAccelObjC - Emit objective C classes and categories into a hashed
1775 /// accelerator table section.
1776 void DwarfDebug::emitAccelObjC() {
1777 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1778 dwarf::DW_FORM_data4));
1779 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1780 E = CUMap.end(); I != E; ++I) {
1781 CompileUnit *TheCU = I->second;
1782 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
1783 for (StringMap<std::vector<DIE*> >::const_iterator
1784 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1785 const char *Name = GI->getKeyData();
1786 std::vector<DIE *> Entities = GI->second;
1787 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1788 DE = Entities.end(); DI != DE; ++DI)
1789 AT.AddName(Name, (*DI));
1793 AT.FinalizeTable(Asm, "ObjC");
1794 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1795 .getDwarfAccelObjCSection());
1796 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
1797 Asm->OutStreamer.EmitLabel(SectionBegin);
1799 // Emit the full data.
1800 AT.Emit(Asm, SectionBegin, this);
1803 /// emitAccelNamespace - Emit namespace dies into a hashed accelerator
1805 void DwarfDebug::emitAccelNamespaces() {
1806 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1807 dwarf::DW_FORM_data4));
1808 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1809 E = CUMap.end(); I != E; ++I) {
1810 CompileUnit *TheCU = I->second;
1811 const StringMap<DIE*> &Names = TheCU->getAccelNamespace();
1812 for (StringMap<DIE*>::const_iterator
1813 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1814 const char *Name = GI->getKeyData();
1815 DIE *Entity = GI->second;
1816 AT.AddName(Name, Entity);
1820 AT.FinalizeTable(Asm, "namespac");
1821 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1822 .getDwarfAccelNamespaceSection());
1823 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
1824 Asm->OutStreamer.EmitLabel(SectionBegin);
1826 // Emit the full data.
1827 AT.Emit(Asm, SectionBegin, this);
1830 /// emitAccelTypes() - Emit type dies into a hashed accelerator table.
1831 void DwarfDebug::emitAccelTypes() {
1832 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1833 dwarf::DW_FORM_data4));
1834 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1835 E = CUMap.end(); I != E; ++I) {
1836 CompileUnit *TheCU = I->second;
1837 const StringMap<DIE*> &Names = TheCU->getAccelTypes();
1838 for (StringMap<DIE*>::const_iterator
1839 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1840 const char *Name = GI->getKeyData();
1841 DIE *Entity = GI->second;
1842 AT.AddName(Name, Entity);
1846 AT.FinalizeTable(Asm, "types");
1847 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1848 .getDwarfAccelTypesSection());
1849 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
1850 Asm->OutStreamer.EmitLabel(SectionBegin);
1852 // Emit the full data.
1853 AT.Emit(Asm, SectionBegin, this);
1856 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1858 void DwarfDebug::emitDebugPubNames() {
1859 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1860 E = CUMap.end(); I != E; ++I) {
1861 CompileUnit *TheCU = I->second;
1862 // Start the dwarf pubnames section.
1863 Asm->OutStreamer.SwitchSection(
1864 Asm->getObjFileLowering().getDwarfPubNamesSection());
1866 Asm->OutStreamer.AddComment("Length of Public Names Info");
1867 Asm->EmitLabelDifference(
1868 Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
1869 Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
1871 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
1874 Asm->OutStreamer.AddComment("DWARF Version");
1875 Asm->EmitInt16(dwarf::DWARF_VERSION);
1877 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1878 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1879 DwarfInfoSectionSym);
1881 Asm->OutStreamer.AddComment("Compilation Unit Length");
1882 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1883 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1886 const StringMap<DIE*> &Globals = TheCU->getGlobals();
1887 for (StringMap<DIE*>::const_iterator
1888 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1889 const char *Name = GI->getKeyData();
1890 DIE *Entity = GI->second;
1892 Asm->OutStreamer.AddComment("DIE offset");
1893 Asm->EmitInt32(Entity->getOffset());
1895 if (Asm->isVerbose())
1896 Asm->OutStreamer.AddComment("External Name");
1897 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
1900 Asm->OutStreamer.AddComment("End Mark");
1902 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
1907 void DwarfDebug::emitDebugPubTypes() {
1908 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1909 E = CUMap.end(); I != E; ++I) {
1910 CompileUnit *TheCU = I->second;
1911 // Start the dwarf pubtypes section.
1912 Asm->OutStreamer.SwitchSection(
1913 Asm->getObjFileLowering().getDwarfPubTypesSection());
1914 Asm->OutStreamer.AddComment("Length of Public Types Info");
1915 Asm->EmitLabelDifference(
1916 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
1917 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
1919 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
1922 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
1923 Asm->EmitInt16(dwarf::DWARF_VERSION);
1925 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1926 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1927 DwarfInfoSectionSym);
1929 Asm->OutStreamer.AddComment("Compilation Unit Length");
1930 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1931 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1934 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
1935 for (StringMap<DIE*>::const_iterator
1936 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1937 const char *Name = GI->getKeyData();
1938 DIE *Entity = GI->second;
1940 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
1941 Asm->EmitInt32(Entity->getOffset());
1943 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
1944 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
1947 Asm->OutStreamer.AddComment("End Mark");
1949 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
1954 /// emitDebugStr - Emit visible names into a debug str section.
1956 void DwarfDebug::emitDebugStr() {
1957 // Check to see if it is worth the effort.
1958 if (StringPool.empty()) return;
1960 // Start the dwarf str section.
1961 Asm->OutStreamer.SwitchSection(
1962 Asm->getObjFileLowering().getDwarfStrSection());
1964 // Get all of the string pool entries and put them in an array by their ID so
1965 // we can sort them.
1966 SmallVector<std::pair<unsigned,
1967 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
1969 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
1970 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
1971 Entries.push_back(std::make_pair(I->second.second, &*I));
1973 array_pod_sort(Entries.begin(), Entries.end());
1975 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
1976 // Emit a label for reference from debug information entries.
1977 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
1979 // Emit the string itself.
1980 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
1981 Asm->OutStreamer.EmitZeros(1, 0);
1985 /// emitDebugLoc - Emit visible names into a debug loc section.
1987 void DwarfDebug::emitDebugLoc() {
1988 if (DotDebugLocEntries.empty())
1991 for (SmallVector<DotDebugLocEntry, 4>::iterator
1992 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1994 DotDebugLocEntry &Entry = *I;
1995 if (I + 1 != DotDebugLocEntries.end())
1999 // Start the dwarf loc section.
2000 Asm->OutStreamer.SwitchSection(
2001 Asm->getObjFileLowering().getDwarfLocSection());
2002 unsigned char Size = Asm->getTargetData().getPointerSize();
2003 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2005 for (SmallVector<DotDebugLocEntry, 4>::iterator
2006 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2007 I != E; ++I, ++index) {
2008 DotDebugLocEntry &Entry = *I;
2009 if (Entry.isMerged()) continue;
2010 if (Entry.isEmpty()) {
2011 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2012 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2013 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2015 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
2016 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
2017 DIVariable DV(Entry.Variable);
2018 Asm->OutStreamer.AddComment("Loc expr size");
2019 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2020 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2021 Asm->EmitLabelDifference(end, begin, 2);
2022 Asm->OutStreamer.EmitLabel(begin);
2023 if (Entry.isInt()) {
2024 DIBasicType BTy(DV.getType());
2026 (BTy.getEncoding() == dwarf::DW_ATE_signed
2027 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2028 Asm->OutStreamer.AddComment("DW_OP_consts");
2029 Asm->EmitInt8(dwarf::DW_OP_consts);
2030 Asm->EmitSLEB128(Entry.getInt());
2032 Asm->OutStreamer.AddComment("DW_OP_constu");
2033 Asm->EmitInt8(dwarf::DW_OP_constu);
2034 Asm->EmitULEB128(Entry.getInt());
2036 } else if (Entry.isLocation()) {
2037 if (!DV.hasComplexAddress())
2039 Asm->EmitDwarfRegOp(Entry.Loc);
2041 // Complex address entry.
2042 unsigned N = DV.getNumAddrElements();
2044 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2045 if (Entry.Loc.getOffset()) {
2047 Asm->EmitDwarfRegOp(Entry.Loc);
2048 Asm->OutStreamer.AddComment("DW_OP_deref");
2049 Asm->EmitInt8(dwarf::DW_OP_deref);
2050 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2051 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2052 Asm->EmitSLEB128(DV.getAddrElement(1));
2054 // If first address element is OpPlus then emit
2055 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2056 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2057 Asm->EmitDwarfRegOp(Loc);
2061 Asm->EmitDwarfRegOp(Entry.Loc);
2064 // Emit remaining complex address elements.
2065 for (; i < N; ++i) {
2066 uint64_t Element = DV.getAddrElement(i);
2067 if (Element == DIBuilder::OpPlus) {
2068 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2069 Asm->EmitULEB128(DV.getAddrElement(++i));
2070 } else if (Element == DIBuilder::OpDeref)
2071 Asm->EmitInt8(dwarf::DW_OP_deref);
2072 else llvm_unreachable("unknown Opcode found in complex address");
2076 // else ... ignore constant fp. There is not any good way to
2077 // to represent them here in dwarf.
2078 Asm->OutStreamer.EmitLabel(end);
2083 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2085 void DwarfDebug::EmitDebugARanges() {
2086 // Start the dwarf aranges section.
2087 Asm->OutStreamer.SwitchSection(
2088 Asm->getObjFileLowering().getDwarfARangesSection());
2091 /// emitDebugRanges - Emit visible names into a debug ranges section.
2093 void DwarfDebug::emitDebugRanges() {
2094 // Start the dwarf ranges section.
2095 Asm->OutStreamer.SwitchSection(
2096 Asm->getObjFileLowering().getDwarfRangesSection());
2097 unsigned char Size = Asm->getTargetData().getPointerSize();
2098 for (SmallVector<const MCSymbol *, 8>::iterator
2099 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2102 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
2104 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2108 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2110 void DwarfDebug::emitDebugMacInfo() {
2111 if (const MCSection *LineInfo =
2112 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2113 // Start the dwarf macinfo section.
2114 Asm->OutStreamer.SwitchSection(LineInfo);
2118 /// emitDebugInlineInfo - Emit inline info using following format.
2120 /// 1. length of section
2121 /// 2. Dwarf version number
2122 /// 3. address size.
2124 /// Entries (one "entry" for each function that was inlined):
2126 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2127 /// otherwise offset into __debug_str for regular function name.
2128 /// 2. offset into __debug_str section for regular function name.
2129 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2130 /// instances for the function.
2132 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2133 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2134 /// __debug_info section, and the low_pc is the starting address for the
2135 /// inlining instance.
2136 void DwarfDebug::emitDebugInlineInfo() {
2137 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
2143 Asm->OutStreamer.SwitchSection(
2144 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2146 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2147 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2148 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2150 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2152 Asm->OutStreamer.AddComment("Dwarf Version");
2153 Asm->EmitInt16(dwarf::DWARF_VERSION);
2154 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2155 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2157 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2158 E = InlinedSPNodes.end(); I != E; ++I) {
2160 const MDNode *Node = *I;
2161 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2162 = InlineInfo.find(Node);
2163 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2164 DISubprogram SP(Node);
2165 StringRef LName = SP.getLinkageName();
2166 StringRef Name = SP.getName();
2168 Asm->OutStreamer.AddComment("MIPS linkage name");
2169 if (LName.empty()) {
2170 Asm->OutStreamer.EmitBytes(Name, 0);
2171 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
2173 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2174 DwarfStrSectionSym);
2176 Asm->OutStreamer.AddComment("Function name");
2177 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2178 Asm->EmitULEB128(Labels.size(), "Inline count");
2180 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2181 LE = Labels.end(); LI != LE; ++LI) {
2182 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2183 Asm->EmitInt32(LI->second->getOffset());
2185 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2186 Asm->OutStreamer.EmitSymbolValue(LI->first,
2187 Asm->getTargetData().getPointerSize(),0);
2191 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));