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 if (Name == "") return false;
529 return Name[0] == '+' || Name[0] == '-';
532 static bool hasObjCCategory(StringRef Name) {
533 if (Name[0] != '+' && Name[0] != '-')
536 size_t pos = Name.find(')');
537 if (pos != std::string::npos) {
538 if (Name[pos+1] != ' ') return false;
545 static void getObjCClassCategory(StringRef In, StringRef &Class,
546 StringRef &Category) {
547 if (!hasObjCCategory(In)) {
548 Class = In.slice(In.find('[') + 1, In.find(' '));
553 Class = In.slice(In.find('[') + 1, In.find('('));
554 Category = In.slice(In.find('[') + 1, In.find(' '));
558 /// construct SubprogramDIE - Construct subprogram DIE.
559 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
561 CompileUnit *&CURef = SPMap[N];
567 if (!SP.isDefinition())
568 // This is a method declaration which will be handled while constructing
572 DISubprogram SPDecl = SP.getFunctionDeclaration();
574 if (SPDecl.isSubprogram()) {
575 DeclDie = TheCU->getOrCreateSubprogramDIE(SPDecl);
578 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
581 // Refer function declaration directly.
582 TheCU->addDIEEntry(SubprogramDie, dwarf::DW_AT_specification,
583 dwarf::DW_FORM_ref4, DeclDie);
587 TheCU->insertDIE(N, SubprogramDie);
589 // Add to context owner.
590 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
593 TheCU->addGlobal(SP.getName(), SubprogramDie);
595 // Add to Accel Names
596 TheCU->addAccelName(SP.getName(), SubprogramDie);
598 // If this is an Objective-C selector name add it to the ObjC accelerator too.
599 if (isObjCClass(SP.getName())) {
600 StringRef Class, Category;
601 getObjCClassCategory(SP.getName(), Class, Category);
602 TheCU->addAccelObjC(Class, SubprogramDie);
604 TheCU->addAccelObjC(Category, SubprogramDie);
610 /// collectInfoFromNamedMDNodes - Collect debug info from named mdnodes such
611 /// as llvm.dbg.enum and llvm.dbg.ty
612 void DwarfDebug::collectInfoFromNamedMDNodes(Module *M) {
613 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp"))
614 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
615 const MDNode *N = NMD->getOperand(i);
616 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
617 constructSubprogramDIE(CU, N);
620 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"))
621 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
622 const MDNode *N = NMD->getOperand(i);
623 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
624 CU->createGlobalVariableDIE(N);
627 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
628 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
629 DIType Ty(NMD->getOperand(i));
630 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
631 CU->getOrCreateTypeDIE(Ty);
634 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
635 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
636 DIType Ty(NMD->getOperand(i));
637 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
638 CU->getOrCreateTypeDIE(Ty);
642 /// collectLegacyDebugInfo - Collect debug info using DebugInfoFinder.
643 /// FIXME - Remove this when dragon-egg and llvm-gcc switch to DIBuilder.
644 bool DwarfDebug::collectLegacyDebugInfo(Module *M) {
645 DebugInfoFinder DbgFinder;
646 DbgFinder.processModule(*M);
648 bool HasDebugInfo = false;
649 // Scan all the compile-units to see if there are any marked as the main
650 // unit. If not, we do not generate debug info.
651 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
652 E = DbgFinder.compile_unit_end(); I != E; ++I) {
653 if (DICompileUnit(*I).isMain()) {
658 if (!HasDebugInfo) return false;
660 // Create all the compile unit DIEs.
661 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
662 E = DbgFinder.compile_unit_end(); I != E; ++I)
663 constructCompileUnit(*I);
665 // Create DIEs for each global variable.
666 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
667 E = DbgFinder.global_variable_end(); I != E; ++I) {
668 const MDNode *N = *I;
669 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
670 CU->createGlobalVariableDIE(N);
673 // Create DIEs for each subprogram.
674 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
675 E = DbgFinder.subprogram_end(); I != E; ++I) {
676 const MDNode *N = *I;
677 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
678 constructSubprogramDIE(CU, N);
684 /// beginModule - Emit all Dwarf sections that should come prior to the
685 /// content. Create global DIEs and emit initial debug info sections.
686 /// This is invoked by the target AsmPrinter.
687 void DwarfDebug::beginModule(Module *M) {
688 if (DisableDebugInfoPrinting)
691 // If module has named metadata anchors then use them, otherwise scan the
692 // module using debug info finder to collect debug info.
693 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
695 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
696 DICompileUnit CUNode(CU_Nodes->getOperand(i));
697 CompileUnit *CU = constructCompileUnit(CUNode);
698 DIArray GVs = CUNode.getGlobalVariables();
699 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
700 CU->createGlobalVariableDIE(GVs.getElement(i));
701 DIArray SPs = CUNode.getSubprograms();
702 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
703 constructSubprogramDIE(CU, SPs.getElement(i));
704 DIArray EnumTypes = CUNode.getEnumTypes();
705 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
706 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
707 DIArray RetainedTypes = CUNode.getRetainedTypes();
708 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
709 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
711 } else if (!collectLegacyDebugInfo(M))
714 collectInfoFromNamedMDNodes(M);
716 // Tell MMI that we have debug info.
717 MMI->setDebugInfoAvailability(true);
719 // Emit initial sections.
722 // Prime section data.
723 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
726 /// endModule - Emit all Dwarf sections that should come after the content.
728 void DwarfDebug::endModule() {
729 if (!FirstCU) return;
730 const Module *M = MMI->getModule();
731 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
733 // Collect info for variables that were optimized out.
734 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
735 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
736 DICompileUnit TheCU(CU_Nodes->getOperand(i));
737 DIArray Subprograms = TheCU.getSubprograms();
738 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
739 DISubprogram SP(Subprograms.getElement(i));
740 if (ProcessedSPNodes.count(SP) != 0) continue;
741 if (!SP.Verify()) continue;
742 if (!SP.isDefinition()) continue;
743 DIArray Variables = SP.getVariables();
744 if (Variables.getNumElements() == 0) continue;
746 LexicalScope *Scope =
747 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
748 DeadFnScopeMap[SP] = Scope;
750 // Construct subprogram DIE and add variables DIEs.
751 CompileUnit *SPCU = CUMap.lookup(TheCU);
752 assert(SPCU && "Unable to find Compile Unit!");
753 constructSubprogramDIE(SPCU, SP);
754 DIE *ScopeDIE = SPCU->getDIE(SP);
755 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
756 DIVariable DV(Variables.getElement(vi));
757 if (!DV.Verify()) continue;
758 DbgVariable *NewVar = new DbgVariable(DV, NULL);
759 if (DIE *VariableDIE =
760 SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
761 ScopeDIE->addChild(VariableDIE);
767 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
768 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
769 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
771 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
774 // Emit DW_AT_containing_type attribute to connect types with their
775 // vtable holding type.
776 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
777 CUE = CUMap.end(); CUI != CUE; ++CUI) {
778 CompileUnit *TheCU = CUI->second;
779 TheCU->constructContainingTypeDIEs();
782 // Standard sections final addresses.
783 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
784 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
785 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
786 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
788 // End text sections.
789 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
790 Asm->OutStreamer.SwitchSection(SectionMap[i]);
791 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
794 // Compute DIE offsets and sizes.
795 computeSizeAndOffsets();
797 // Emit all the DIEs into a debug info section
800 // Corresponding abbreviations into a abbrev section.
803 // Emit info into a dwarf accelerator table sections.
804 if (DwarfAccelTables) {
807 emitAccelNamespaces();
811 // Emit info into a debug pubnames section.
814 // Emit info into a debug pubtypes section.
817 // Emit info into a debug loc section.
820 // Emit info into a debug aranges section.
823 // Emit info into a debug ranges section.
826 // Emit info into a debug macinfo section.
830 emitDebugInlineInfo();
832 // Emit info into a debug str section.
836 DeleteContainerSeconds(DeadFnScopeMap);
838 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
839 E = CUMap.end(); I != E; ++I)
841 FirstCU = NULL; // Reset for the next Module, if any.
844 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
845 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
847 LLVMContext &Ctx = DV->getContext();
848 // More then one inlined variable corresponds to one abstract variable.
849 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
850 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
852 return AbsDbgVariable;
854 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
858 AbsDbgVariable = new DbgVariable(Var, NULL);
859 addScopeVariable(Scope, AbsDbgVariable);
860 AbstractVariables[Var] = AbsDbgVariable;
861 return AbsDbgVariable;
864 /// addCurrentFnArgument - If Var is a current function argument then add
865 /// it to CurrentFnArguments list.
866 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
867 DbgVariable *Var, LexicalScope *Scope) {
868 if (!LScopes.isCurrentFunctionScope(Scope))
870 DIVariable DV = Var->getVariable();
871 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
873 unsigned ArgNo = DV.getArgNumber();
877 size_t Size = CurrentFnArguments.size();
879 CurrentFnArguments.resize(MF->getFunction()->arg_size());
880 // llvm::Function argument size is not good indicator of how many
881 // arguments does the function have at source level.
883 CurrentFnArguments.resize(ArgNo * 2);
884 CurrentFnArguments[ArgNo - 1] = Var;
888 /// collectVariableInfoFromMMITable - Collect variable information from
889 /// side table maintained by MMI.
891 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
892 SmallPtrSet<const MDNode *, 16> &Processed) {
893 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
894 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
895 VE = VMap.end(); VI != VE; ++VI) {
896 const MDNode *Var = VI->first;
898 Processed.insert(Var);
900 const std::pair<unsigned, DebugLoc> &VP = VI->second;
902 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
904 // If variable scope is not found then skip this variable.
908 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
909 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
910 RegVar->setFrameIndex(VP.first);
911 if (!addCurrentFnArgument(MF, RegVar, Scope))
912 addScopeVariable(Scope, RegVar);
914 AbsDbgVariable->setFrameIndex(VP.first);
918 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
919 /// DBG_VALUE instruction, is in a defined reg.
920 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
921 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
922 return MI->getNumOperands() == 3 &&
923 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
924 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
927 /// getDebugLocEntry - Get .debug_loc entry for the instruction range starting
929 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
930 const MCSymbol *FLabel,
931 const MCSymbol *SLabel,
932 const MachineInstr *MI) {
933 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
935 if (MI->getNumOperands() != 3) {
936 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
937 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
939 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
940 MachineLocation MLoc;
941 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
942 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
944 if (MI->getOperand(0).isImm())
945 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
946 if (MI->getOperand(0).isFPImm())
947 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
948 if (MI->getOperand(0).isCImm())
949 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
951 assert(0 && "Unexpected 3 operand DBG_VALUE instruction!");
952 return DotDebugLocEntry();
955 /// collectVariableInfo - Find variables for each lexical scope.
957 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
958 SmallPtrSet<const MDNode *, 16> &Processed) {
960 /// collection info from MMI table.
961 collectVariableInfoFromMMITable(MF, Processed);
963 for (SmallVectorImpl<const MDNode*>::const_iterator
964 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
966 const MDNode *Var = *UVI;
967 if (Processed.count(Var))
970 // History contains relevant DBG_VALUE instructions for Var and instructions
972 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
975 const MachineInstr *MInsn = History.front();
978 LexicalScope *Scope = NULL;
979 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
980 DISubprogram(DV.getContext()).describes(MF->getFunction()))
981 Scope = LScopes.getCurrentFunctionScope();
983 if (DV.getVersion() <= LLVMDebugVersion9)
984 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
986 if (MDNode *IA = DV.getInlinedAt())
987 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
989 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
992 // If variable scope is not found then skip this variable.
996 Processed.insert(DV);
997 assert(MInsn->isDebugValue() && "History must begin with debug value");
998 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
999 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1000 if (!addCurrentFnArgument(MF, RegVar, Scope))
1001 addScopeVariable(Scope, RegVar);
1003 AbsVar->setMInsn(MInsn);
1005 // Simple ranges that are fully coalesced.
1006 if (History.size() <= 1 || (History.size() == 2 &&
1007 MInsn->isIdenticalTo(History.back()))) {
1008 RegVar->setMInsn(MInsn);
1012 // handle multiple DBG_VALUE instructions describing one variable.
1013 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1015 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1016 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1017 const MachineInstr *Begin = *HI;
1018 assert(Begin->isDebugValue() && "Invalid History entry");
1020 // Check if DBG_VALUE is truncating a range.
1021 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1022 && !Begin->getOperand(0).getReg())
1025 // Compute the range for a register location.
1026 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1027 const MCSymbol *SLabel = 0;
1030 // If Begin is the last instruction in History then its value is valid
1031 // until the end of the function.
1032 SLabel = FunctionEndSym;
1034 const MachineInstr *End = HI[1];
1035 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1036 << "\t" << *Begin << "\t" << *End << "\n");
1037 if (End->isDebugValue())
1038 SLabel = getLabelBeforeInsn(End);
1040 // End is a normal instruction clobbering the range.
1041 SLabel = getLabelAfterInsn(End);
1042 assert(SLabel && "Forgot label after clobber instruction");
1047 // The value is valid until the next DBG_VALUE or clobber.
1048 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1050 DotDebugLocEntries.push_back(DotDebugLocEntry());
1053 // Collect info for variables that were optimized out.
1054 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1055 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1056 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1057 DIVariable DV(Variables.getElement(i));
1058 if (!DV || !DV.Verify() || !Processed.insert(DV))
1060 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1061 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1065 /// getLabelBeforeInsn - Return Label preceding the instruction.
1066 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1067 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1068 assert(Label && "Didn't insert label before instruction");
1072 /// getLabelAfterInsn - Return Label immediately following the instruction.
1073 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1074 return LabelsAfterInsn.lookup(MI);
1077 /// beginInstruction - Process beginning of an instruction.
1078 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1079 // Check if source location changes, but ignore DBG_VALUE locations.
1080 if (!MI->isDebugValue()) {
1081 DebugLoc DL = MI->getDebugLoc();
1082 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1083 unsigned Flags = DWARF2_FLAG_IS_STMT;
1085 if (DL == PrologEndLoc) {
1086 Flags |= DWARF2_FLAG_PROLOGUE_END;
1087 PrologEndLoc = DebugLoc();
1089 if (!DL.isUnknown()) {
1090 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1091 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1093 recordSourceLine(0, 0, 0, 0);
1097 // Insert labels where requested.
1098 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1099 LabelsBeforeInsn.find(MI);
1102 if (I == LabelsBeforeInsn.end())
1105 // Label already assigned.
1110 PrevLabel = MMI->getContext().CreateTempSymbol();
1111 Asm->OutStreamer.EmitLabel(PrevLabel);
1113 I->second = PrevLabel;
1116 /// endInstruction - Process end of an instruction.
1117 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1118 // Don't create a new label after DBG_VALUE instructions.
1119 // They don't generate code.
1120 if (!MI->isDebugValue())
1123 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1124 LabelsAfterInsn.find(MI);
1127 if (I == LabelsAfterInsn.end())
1130 // Label already assigned.
1134 // We need a label after this instruction.
1136 PrevLabel = MMI->getContext().CreateTempSymbol();
1137 Asm->OutStreamer.EmitLabel(PrevLabel);
1139 I->second = PrevLabel;
1142 /// identifyScopeMarkers() -
1143 /// Each LexicalScope has first instruction and last instruction to mark
1144 /// beginning and end of a scope respectively. Create an inverse map that list
1145 /// scopes starts (and ends) with an instruction. One instruction may start (or
1146 /// end) multiple scopes. Ignore scopes that are not reachable.
1147 void DwarfDebug::identifyScopeMarkers() {
1148 SmallVector<LexicalScope *, 4> WorkList;
1149 WorkList.push_back(LScopes.getCurrentFunctionScope());
1150 while (!WorkList.empty()) {
1151 LexicalScope *S = WorkList.pop_back_val();
1153 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1154 if (!Children.empty())
1155 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1156 SE = Children.end(); SI != SE; ++SI)
1157 WorkList.push_back(*SI);
1159 if (S->isAbstractScope())
1162 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1165 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1166 RE = Ranges.end(); RI != RE; ++RI) {
1167 assert(RI->first && "InsnRange does not have first instruction!");
1168 assert(RI->second && "InsnRange does not have second instruction!");
1169 requestLabelBeforeInsn(RI->first);
1170 requestLabelAfterInsn(RI->second);
1175 /// getScopeNode - Get MDNode for DebugLoc's scope.
1176 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1177 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1178 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1179 return DL.getScope(Ctx);
1182 /// getFnDebugLoc - Walk up the scope chain of given debug loc and find
1183 /// line number info for the function.
1184 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1185 const MDNode *Scope = getScopeNode(DL, Ctx);
1186 DISubprogram SP = getDISubprogram(Scope);
1188 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1192 /// beginFunction - Gather pre-function debug information. Assumes being
1193 /// emitted immediately after the function entry point.
1194 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1195 if (!MMI->hasDebugInfo()) return;
1196 LScopes.initialize(*MF);
1197 if (LScopes.empty()) return;
1198 identifyScopeMarkers();
1200 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1201 Asm->getFunctionNumber());
1202 // Assumes in correct section after the entry point.
1203 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1205 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1207 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1208 /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1209 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1211 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1213 bool AtBlockEntry = true;
1214 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1216 const MachineInstr *MI = II;
1218 if (MI->isDebugValue()) {
1219 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1221 // Keep track of user variables.
1223 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1225 // Variable is in a register, we need to check for clobbers.
1226 if (isDbgValueInDefinedReg(MI))
1227 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1229 // Check the history of this variable.
1230 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1231 if (History.empty()) {
1232 UserVariables.push_back(Var);
1233 // The first mention of a function argument gets the FunctionBeginSym
1234 // label, so arguments are visible when breaking at function entry.
1236 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1237 DISubprogram(getDISubprogram(DV.getContext()))
1238 .describes(MF->getFunction()))
1239 LabelsBeforeInsn[MI] = FunctionBeginSym;
1241 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1242 const MachineInstr *Prev = History.back();
1243 if (Prev->isDebugValue()) {
1244 // Coalesce identical entries at the end of History.
1245 if (History.size() >= 2 &&
1246 Prev->isIdenticalTo(History[History.size() - 2])) {
1247 DEBUG(dbgs() << "Coalesce identical DBG_VALUE entries:\n"
1249 << "\t" << *History[History.size() - 2] << "\n");
1253 // Terminate old register assignments that don't reach MI;
1254 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1255 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1256 isDbgValueInDefinedReg(Prev)) {
1257 // Previous register assignment needs to terminate at the end of
1259 MachineBasicBlock::const_iterator LastMI =
1260 PrevMBB->getLastNonDebugInstr();
1261 if (LastMI == PrevMBB->end()) {
1262 // Drop DBG_VALUE for empty range.
1263 DEBUG(dbgs() << "Drop DBG_VALUE for empty range:\n"
1264 << "\t" << *Prev << "\n");
1268 // Terminate after LastMI.
1269 History.push_back(LastMI);
1274 History.push_back(MI);
1276 // Not a DBG_VALUE instruction.
1278 AtBlockEntry = false;
1280 // First known non DBG_VALUE location marks beginning of function
1282 if (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown())
1283 PrologEndLoc = MI->getDebugLoc();
1285 // Check if the instruction clobbers any registers with debug vars.
1286 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1287 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1288 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1290 for (const unsigned *AI = TRI->getOverlaps(MOI->getReg());
1291 unsigned Reg = *AI; ++AI) {
1292 const MDNode *Var = LiveUserVar[Reg];
1295 // Reg is now clobbered.
1296 LiveUserVar[Reg] = 0;
1298 // Was MD last defined by a DBG_VALUE referring to Reg?
1299 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1300 if (HistI == DbgValues.end())
1302 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1303 if (History.empty())
1305 const MachineInstr *Prev = History.back();
1306 // Sanity-check: Register assignments are terminated at the end of
1308 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1310 // Is the variable still in Reg?
1311 if (!isDbgValueInDefinedReg(Prev) ||
1312 Prev->getOperand(0).getReg() != Reg)
1314 // Var is clobbered. Make sure the next instruction gets a label.
1315 History.push_back(MI);
1322 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1324 SmallVectorImpl<const MachineInstr*> &History = I->second;
1325 if (History.empty())
1328 // Make sure the final register assignments are terminated.
1329 const MachineInstr *Prev = History.back();
1330 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1331 const MachineBasicBlock *PrevMBB = Prev->getParent();
1332 MachineBasicBlock::const_iterator LastMI =
1333 PrevMBB->getLastNonDebugInstr();
1334 if (LastMI == PrevMBB->end())
1335 // Drop DBG_VALUE for empty range.
1338 // Terminate after LastMI.
1339 History.push_back(LastMI);
1342 // Request labels for the full history.
1343 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1344 const MachineInstr *MI = History[i];
1345 if (MI->isDebugValue())
1346 requestLabelBeforeInsn(MI);
1348 requestLabelAfterInsn(MI);
1352 PrevInstLoc = DebugLoc();
1353 PrevLabel = FunctionBeginSym;
1355 // Record beginning of function.
1356 if (!PrologEndLoc.isUnknown()) {
1357 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1358 MF->getFunction()->getContext());
1359 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1360 FnStartDL.getScope(MF->getFunction()->getContext()),
1361 DWARF2_FLAG_IS_STMT);
1365 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1366 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1367 ScopeVariables[LS].push_back(Var);
1368 // Vars.push_back(Var);
1371 /// endFunction - Gather and emit post-function debug information.
1373 void DwarfDebug::endFunction(const MachineFunction *MF) {
1374 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1376 // Define end label for subprogram.
1377 FunctionEndSym = Asm->GetTempSymbol("func_end",
1378 Asm->getFunctionNumber());
1379 // Assumes in correct section after the entry point.
1380 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1382 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1383 collectVariableInfo(MF, ProcessedVars);
1385 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1386 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1387 assert(TheCU && "Unable to find compile unit!");
1389 // Construct abstract scopes.
1390 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1391 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1392 LexicalScope *AScope = AList[i];
1393 DISubprogram SP(AScope->getScopeNode());
1395 // Collect info for variables that were optimized out.
1396 DIArray Variables = SP.getVariables();
1397 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1398 DIVariable DV(Variables.getElement(i));
1399 if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1401 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1402 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1405 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1406 constructScopeDIE(TheCU, AScope);
1409 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1411 if (!DisableFramePointerElim(*MF))
1412 TheCU->addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
1413 dwarf::DW_FORM_flag, 1);
1415 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1416 MMI->getFrameMoves()));
1419 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1420 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1421 DeleteContainerPointers(I->second);
1422 ScopeVariables.clear();
1423 DeleteContainerPointers(CurrentFnArguments);
1424 UserVariables.clear();
1426 AbstractVariables.clear();
1427 LabelsBeforeInsn.clear();
1428 LabelsAfterInsn.clear();
1432 /// recordSourceLine - Register a source line with debug info. Returns the
1433 /// unique label that was emitted and which provides correspondence to
1434 /// the source line list.
1435 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1441 DIDescriptor Scope(S);
1443 if (Scope.isCompileUnit()) {
1444 DICompileUnit CU(S);
1445 Fn = CU.getFilename();
1446 Dir = CU.getDirectory();
1447 } else if (Scope.isFile()) {
1449 Fn = F.getFilename();
1450 Dir = F.getDirectory();
1451 } else if (Scope.isSubprogram()) {
1453 Fn = SP.getFilename();
1454 Dir = SP.getDirectory();
1455 } else if (Scope.isLexicalBlockFile()) {
1456 DILexicalBlockFile DBF(S);
1457 Fn = DBF.getFilename();
1458 Dir = DBF.getDirectory();
1459 } else if (Scope.isLexicalBlock()) {
1460 DILexicalBlock DB(S);
1461 Fn = DB.getFilename();
1462 Dir = DB.getDirectory();
1464 assert(0 && "Unexpected scope info");
1466 Src = GetOrCreateSourceID(Fn, Dir);
1468 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1471 //===----------------------------------------------------------------------===//
1473 //===----------------------------------------------------------------------===//
1475 /// computeSizeAndOffset - Compute the size and offset of a DIE.
1478 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
1479 // Get the children.
1480 const std::vector<DIE *> &Children = Die->getChildren();
1482 // If not last sibling and has children then add sibling offset attribute.
1483 if (!Last && !Children.empty())
1484 Die->addSiblingOffset(DIEValueAllocator);
1486 // Record the abbreviation.
1487 assignAbbrevNumber(Die->getAbbrev());
1489 // Get the abbreviation for this DIE.
1490 unsigned AbbrevNumber = Die->getAbbrevNumber();
1491 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1494 Die->setOffset(Offset);
1496 // Start the size with the size of abbreviation code.
1497 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1499 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1500 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1502 // Size the DIE attribute values.
1503 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1504 // Size attribute value.
1505 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1507 // Size the DIE children if any.
1508 if (!Children.empty()) {
1509 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1510 "Children flag not set");
1512 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1513 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
1515 // End of children marker.
1516 Offset += sizeof(int8_t);
1519 Die->setSize(Offset - Die->getOffset());
1523 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
1525 void DwarfDebug::computeSizeAndOffsets() {
1526 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1527 E = CUMap.end(); I != E; ++I) {
1528 // Compute size of compile unit header.
1530 sizeof(int32_t) + // Length of Compilation Unit Info
1531 sizeof(int16_t) + // DWARF version number
1532 sizeof(int32_t) + // Offset Into Abbrev. Section
1533 sizeof(int8_t); // Pointer Size (in bytes)
1534 computeSizeAndOffset(I->second->getCUDie(), Offset, true);
1538 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
1539 /// the start of each one.
1540 void DwarfDebug::EmitSectionLabels() {
1541 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1543 // Dwarf sections base addresses.
1544 DwarfInfoSectionSym =
1545 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1546 DwarfAbbrevSectionSym =
1547 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1548 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
1550 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1551 EmitSectionSym(Asm, MacroInfo);
1553 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1554 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
1555 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1556 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1557 DwarfStrSectionSym =
1558 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
1559 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1562 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
1563 "section_debug_loc");
1565 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1566 EmitSectionSym(Asm, TLOF.getDataSection());
1569 /// emitDIE - Recursively emits a debug information entry.
1571 void DwarfDebug::emitDIE(DIE *Die) {
1572 // Get the abbreviation for this DIE.
1573 unsigned AbbrevNumber = Die->getAbbrevNumber();
1574 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1576 // Emit the code (index) for the abbreviation.
1577 if (Asm->isVerbose())
1578 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1579 Twine::utohexstr(Die->getOffset()) + ":0x" +
1580 Twine::utohexstr(Die->getSize()) + " " +
1581 dwarf::TagString(Abbrev->getTag()));
1582 Asm->EmitULEB128(AbbrevNumber);
1584 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1585 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1587 // Emit the DIE attribute values.
1588 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1589 unsigned Attr = AbbrevData[i].getAttribute();
1590 unsigned Form = AbbrevData[i].getForm();
1591 assert(Form && "Too many attributes for DIE (check abbreviation)");
1593 if (Asm->isVerbose())
1594 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1597 case dwarf::DW_AT_sibling:
1598 Asm->EmitInt32(Die->getSiblingOffset());
1600 case dwarf::DW_AT_abstract_origin: {
1601 DIEEntry *E = cast<DIEEntry>(Values[i]);
1602 DIE *Origin = E->getEntry();
1603 unsigned Addr = Origin->getOffset();
1604 Asm->EmitInt32(Addr);
1607 case dwarf::DW_AT_ranges: {
1608 // DW_AT_range Value encodes offset in debug_range section.
1609 DIEInteger *V = cast<DIEInteger>(Values[i]);
1611 if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
1612 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1616 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1618 DwarfDebugRangeSectionSym,
1623 case dwarf::DW_AT_location: {
1624 if (DIELabel *L = dyn_cast<DIELabel>(Values[i]))
1625 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1627 Values[i]->EmitValue(Asm, Form);
1630 case dwarf::DW_AT_accessibility: {
1631 if (Asm->isVerbose()) {
1632 DIEInteger *V = cast<DIEInteger>(Values[i]);
1633 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1635 Values[i]->EmitValue(Asm, Form);
1639 // Emit an attribute using the defined form.
1640 Values[i]->EmitValue(Asm, Form);
1645 // Emit the DIE children if any.
1646 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1647 const std::vector<DIE *> &Children = Die->getChildren();
1649 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1650 emitDIE(Children[j]);
1652 if (Asm->isVerbose())
1653 Asm->OutStreamer.AddComment("End Of Children Mark");
1658 /// emitDebugInfo - Emit the debug info section.
1660 void DwarfDebug::emitDebugInfo() {
1661 // Start debug info section.
1662 Asm->OutStreamer.SwitchSection(
1663 Asm->getObjFileLowering().getDwarfInfoSection());
1664 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1665 E = CUMap.end(); I != E; ++I) {
1666 CompileUnit *TheCU = I->second;
1667 DIE *Die = TheCU->getCUDie();
1669 // Emit the compile units header.
1670 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
1673 // Emit size of content not including length itself
1674 unsigned ContentSize = Die->getSize() +
1675 sizeof(int16_t) + // DWARF version number
1676 sizeof(int32_t) + // Offset Into Abbrev. Section
1677 sizeof(int8_t); // Pointer Size (in bytes)
1679 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1680 Asm->EmitInt32(ContentSize);
1681 Asm->OutStreamer.AddComment("DWARF version number");
1682 Asm->EmitInt16(dwarf::DWARF_VERSION);
1683 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1684 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
1685 DwarfAbbrevSectionSym);
1686 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1687 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1690 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
1694 /// emitAbbreviations - Emit the abbreviation section.
1696 void DwarfDebug::emitAbbreviations() const {
1697 // Check to see if it is worth the effort.
1698 if (!Abbreviations.empty()) {
1699 // Start the debug abbrev section.
1700 Asm->OutStreamer.SwitchSection(
1701 Asm->getObjFileLowering().getDwarfAbbrevSection());
1703 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
1705 // For each abbrevation.
1706 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1707 // Get abbreviation data
1708 const DIEAbbrev *Abbrev = Abbreviations[i];
1710 // Emit the abbrevations code (base 1 index.)
1711 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1713 // Emit the abbreviations data.
1717 // Mark end of abbreviations.
1718 Asm->EmitULEB128(0, "EOM(3)");
1720 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
1724 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
1725 /// the line matrix.
1727 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1728 // Define last address of section.
1729 Asm->OutStreamer.AddComment("Extended Op");
1732 Asm->OutStreamer.AddComment("Op size");
1733 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
1734 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1735 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1737 Asm->OutStreamer.AddComment("Section end label");
1739 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1740 Asm->getTargetData().getPointerSize(),
1743 // Mark end of matrix.
1744 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1750 /// emitAccelNames - Emit visible names into a hashed accelerator table
1752 void DwarfDebug::emitAccelNames() {
1753 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1754 dwarf::DW_FORM_data4));
1755 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1756 E = CUMap.end(); I != E; ++I) {
1757 CompileUnit *TheCU = I->second;
1758 const StringMap<DIE*> &Names = TheCU->getAccelNames();
1759 for (StringMap<DIE*>::const_iterator
1760 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1761 const char *Name = GI->getKeyData();
1762 DIE *Entity = GI->second;
1763 AT.AddName(Name, Entity);
1767 AT.FinalizeTable(Asm, "Names");
1768 Asm->OutStreamer.SwitchSection(
1769 Asm->getObjFileLowering().getDwarfAccelNamesSection());
1770 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1771 Asm->OutStreamer.EmitLabel(SectionBegin);
1773 // Emit the full data.
1774 AT.Emit(Asm, SectionBegin, this);
1777 /// emitAccelObjC - Emit objective C classes and categories into a hashed
1778 /// accelerator table section.
1779 void DwarfDebug::emitAccelObjC() {
1780 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1781 dwarf::DW_FORM_data4));
1782 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1783 E = CUMap.end(); I != E; ++I) {
1784 CompileUnit *TheCU = I->second;
1785 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
1786 for (StringMap<std::vector<DIE*> >::const_iterator
1787 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1788 const char *Name = GI->getKeyData();
1789 std::vector<DIE *> Entities = GI->second;
1790 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1791 DE = Entities.end(); DI != DE; ++DI)
1792 AT.AddName(Name, (*DI));
1796 AT.FinalizeTable(Asm, "ObjC");
1797 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1798 .getDwarfAccelObjCSection());
1799 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
1800 Asm->OutStreamer.EmitLabel(SectionBegin);
1802 // Emit the full data.
1803 AT.Emit(Asm, SectionBegin, this);
1806 /// emitAccelNamespace - Emit namespace dies into a hashed accelerator
1808 void DwarfDebug::emitAccelNamespaces() {
1809 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1810 dwarf::DW_FORM_data4));
1811 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1812 E = CUMap.end(); I != E; ++I) {
1813 CompileUnit *TheCU = I->second;
1814 const StringMap<DIE*> &Names = TheCU->getAccelNamespace();
1815 for (StringMap<DIE*>::const_iterator
1816 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1817 const char *Name = GI->getKeyData();
1818 DIE *Entity = GI->second;
1819 AT.AddName(Name, Entity);
1823 AT.FinalizeTable(Asm, "namespac");
1824 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1825 .getDwarfAccelNamespaceSection());
1826 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
1827 Asm->OutStreamer.EmitLabel(SectionBegin);
1829 // Emit the full data.
1830 AT.Emit(Asm, SectionBegin, this);
1833 /// emitAccelTypes() - Emit type dies into a hashed accelerator table.
1834 void DwarfDebug::emitAccelTypes() {
1835 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1836 dwarf::DW_FORM_data4));
1837 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1838 E = CUMap.end(); I != E; ++I) {
1839 CompileUnit *TheCU = I->second;
1840 const StringMap<DIE*> &Names = TheCU->getGlobalTypes();
1841 //TODO: TheCU->getAccelTypes();
1842 for (StringMap<DIE*>::const_iterator
1843 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1844 const char *Name = GI->getKeyData();
1845 DIE *Entity = GI->second;
1846 AT.AddName(Name, Entity);
1850 AT.FinalizeTable(Asm, "types");
1851 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1852 .getDwarfAccelTypesSection());
1853 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
1854 Asm->OutStreamer.EmitLabel(SectionBegin);
1856 // Emit the full data.
1857 AT.Emit(Asm, SectionBegin, this);
1860 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1862 void DwarfDebug::emitDebugPubNames() {
1863 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1864 E = CUMap.end(); I != E; ++I) {
1865 CompileUnit *TheCU = I->second;
1866 // Start the dwarf pubnames section.
1867 Asm->OutStreamer.SwitchSection(
1868 Asm->getObjFileLowering().getDwarfPubNamesSection());
1870 Asm->OutStreamer.AddComment("Length of Public Names Info");
1871 Asm->EmitLabelDifference(
1872 Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
1873 Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
1875 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
1878 Asm->OutStreamer.AddComment("DWARF Version");
1879 Asm->EmitInt16(dwarf::DWARF_VERSION);
1881 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1882 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1883 DwarfInfoSectionSym);
1885 Asm->OutStreamer.AddComment("Compilation Unit Length");
1886 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1887 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1890 const StringMap<DIE*> &Globals = TheCU->getGlobals();
1891 for (StringMap<DIE*>::const_iterator
1892 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1893 const char *Name = GI->getKeyData();
1894 DIE *Entity = GI->second;
1896 Asm->OutStreamer.AddComment("DIE offset");
1897 Asm->EmitInt32(Entity->getOffset());
1899 if (Asm->isVerbose())
1900 Asm->OutStreamer.AddComment("External Name");
1901 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
1904 Asm->OutStreamer.AddComment("End Mark");
1906 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
1911 void DwarfDebug::emitDebugPubTypes() {
1912 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1913 E = CUMap.end(); I != E; ++I) {
1914 CompileUnit *TheCU = I->second;
1915 // Start the dwarf pubtypes section.
1916 Asm->OutStreamer.SwitchSection(
1917 Asm->getObjFileLowering().getDwarfPubTypesSection());
1918 Asm->OutStreamer.AddComment("Length of Public Types Info");
1919 Asm->EmitLabelDifference(
1920 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
1921 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
1923 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
1926 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
1927 Asm->EmitInt16(dwarf::DWARF_VERSION);
1929 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1930 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1931 DwarfInfoSectionSym);
1933 Asm->OutStreamer.AddComment("Compilation Unit Length");
1934 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1935 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1938 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
1939 for (StringMap<DIE*>::const_iterator
1940 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1941 const char *Name = GI->getKeyData();
1942 DIE *Entity = GI->second;
1944 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
1945 Asm->EmitInt32(Entity->getOffset());
1947 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
1948 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
1951 Asm->OutStreamer.AddComment("End Mark");
1953 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
1958 /// emitDebugStr - Emit visible names into a debug str section.
1960 void DwarfDebug::emitDebugStr() {
1961 // Check to see if it is worth the effort.
1962 if (StringPool.empty()) return;
1964 // Start the dwarf str section.
1965 Asm->OutStreamer.SwitchSection(
1966 Asm->getObjFileLowering().getDwarfStrSection());
1968 // Get all of the string pool entries and put them in an array by their ID so
1969 // we can sort them.
1970 SmallVector<std::pair<unsigned,
1971 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
1973 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
1974 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
1975 Entries.push_back(std::make_pair(I->second.second, &*I));
1977 array_pod_sort(Entries.begin(), Entries.end());
1979 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
1980 // Emit a label for reference from debug information entries.
1981 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
1983 // Emit the string itself.
1984 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
1985 Asm->OutStreamer.EmitZeros(1, 0);
1989 /// emitDebugLoc - Emit visible names into a debug loc section.
1991 void DwarfDebug::emitDebugLoc() {
1992 if (DotDebugLocEntries.empty())
1995 for (SmallVector<DotDebugLocEntry, 4>::iterator
1996 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1998 DotDebugLocEntry &Entry = *I;
1999 if (I + 1 != DotDebugLocEntries.end())
2003 // Start the dwarf loc section.
2004 Asm->OutStreamer.SwitchSection(
2005 Asm->getObjFileLowering().getDwarfLocSection());
2006 unsigned char Size = Asm->getTargetData().getPointerSize();
2007 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2009 for (SmallVector<DotDebugLocEntry, 4>::iterator
2010 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2011 I != E; ++I, ++index) {
2012 DotDebugLocEntry &Entry = *I;
2013 if (Entry.isMerged()) continue;
2014 if (Entry.isEmpty()) {
2015 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2016 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2017 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2019 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
2020 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
2021 DIVariable DV(Entry.Variable);
2022 Asm->OutStreamer.AddComment("Loc expr size");
2023 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2024 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2025 Asm->EmitLabelDifference(end, begin, 2);
2026 Asm->OutStreamer.EmitLabel(begin);
2027 if (Entry.isInt()) {
2028 DIBasicType BTy(DV.getType());
2030 (BTy.getEncoding() == dwarf::DW_ATE_signed
2031 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2032 Asm->OutStreamer.AddComment("DW_OP_consts");
2033 Asm->EmitInt8(dwarf::DW_OP_consts);
2034 Asm->EmitSLEB128(Entry.getInt());
2036 Asm->OutStreamer.AddComment("DW_OP_constu");
2037 Asm->EmitInt8(dwarf::DW_OP_constu);
2038 Asm->EmitULEB128(Entry.getInt());
2040 } else if (Entry.isLocation()) {
2041 if (!DV.hasComplexAddress())
2043 Asm->EmitDwarfRegOp(Entry.Loc);
2045 // Complex address entry.
2046 unsigned N = DV.getNumAddrElements();
2048 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2049 if (Entry.Loc.getOffset()) {
2051 Asm->EmitDwarfRegOp(Entry.Loc);
2052 Asm->OutStreamer.AddComment("DW_OP_deref");
2053 Asm->EmitInt8(dwarf::DW_OP_deref);
2054 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2055 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2056 Asm->EmitSLEB128(DV.getAddrElement(1));
2058 // If first address element is OpPlus then emit
2059 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2060 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2061 Asm->EmitDwarfRegOp(Loc);
2065 Asm->EmitDwarfRegOp(Entry.Loc);
2068 // Emit remaining complex address elements.
2069 for (; i < N; ++i) {
2070 uint64_t Element = DV.getAddrElement(i);
2071 if (Element == DIBuilder::OpPlus) {
2072 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2073 Asm->EmitULEB128(DV.getAddrElement(++i));
2074 } else if (Element == DIBuilder::OpDeref)
2075 Asm->EmitInt8(dwarf::DW_OP_deref);
2076 else llvm_unreachable("unknown Opcode found in complex address");
2080 // else ... ignore constant fp. There is not any good way to
2081 // to represent them here in dwarf.
2082 Asm->OutStreamer.EmitLabel(end);
2087 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2089 void DwarfDebug::EmitDebugARanges() {
2090 // Start the dwarf aranges section.
2091 Asm->OutStreamer.SwitchSection(
2092 Asm->getObjFileLowering().getDwarfARangesSection());
2095 /// emitDebugRanges - Emit visible names into a debug ranges section.
2097 void DwarfDebug::emitDebugRanges() {
2098 // Start the dwarf ranges section.
2099 Asm->OutStreamer.SwitchSection(
2100 Asm->getObjFileLowering().getDwarfRangesSection());
2101 unsigned char Size = Asm->getTargetData().getPointerSize();
2102 for (SmallVector<const MCSymbol *, 8>::iterator
2103 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2106 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
2108 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2112 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2114 void DwarfDebug::emitDebugMacInfo() {
2115 if (const MCSection *LineInfo =
2116 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2117 // Start the dwarf macinfo section.
2118 Asm->OutStreamer.SwitchSection(LineInfo);
2122 /// emitDebugInlineInfo - Emit inline info using following format.
2124 /// 1. length of section
2125 /// 2. Dwarf version number
2126 /// 3. address size.
2128 /// Entries (one "entry" for each function that was inlined):
2130 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2131 /// otherwise offset into __debug_str for regular function name.
2132 /// 2. offset into __debug_str section for regular function name.
2133 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2134 /// instances for the function.
2136 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2137 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2138 /// __debug_info section, and the low_pc is the starting address for the
2139 /// inlining instance.
2140 void DwarfDebug::emitDebugInlineInfo() {
2141 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
2147 Asm->OutStreamer.SwitchSection(
2148 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2150 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2151 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2152 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2154 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2156 Asm->OutStreamer.AddComment("Dwarf Version");
2157 Asm->EmitInt16(dwarf::DWARF_VERSION);
2158 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2159 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2161 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2162 E = InlinedSPNodes.end(); I != E; ++I) {
2164 const MDNode *Node = *I;
2165 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2166 = InlineInfo.find(Node);
2167 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2168 DISubprogram SP(Node);
2169 StringRef LName = SP.getLinkageName();
2170 StringRef Name = SP.getName();
2172 Asm->OutStreamer.AddComment("MIPS linkage name");
2173 if (LName.empty()) {
2174 Asm->OutStreamer.EmitBytes(Name, 0);
2175 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
2177 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2178 DwarfStrSectionSym);
2180 Asm->OutStreamer.AddComment("Function name");
2181 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2182 Asm->EmitULEB128(Labels.size(), "Inline count");
2184 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2185 LE = Labels.end(); LI != LE; ++LI) {
2186 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2187 Asm->EmitInt32(LI->second->getOffset());
2189 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2190 Asm->OutStreamer.EmitSymbolValue(LI->first,
2191 Asm->getTargetData().getPointerSize(),0);
2195 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));