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 "DwarfCompileUnit.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Module.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCSection.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetFrameLowering.h"
29 #include "llvm/Target/TargetLoweringObjectFile.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Analysis/DebugInfo.h"
34 #include "llvm/Analysis/DIBuilder.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/ValueHandle.h"
42 #include "llvm/Support/FormattedStream.h"
43 #include "llvm/Support/Timer.h"
44 #include "llvm/Support/Path.h"
47 static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print",
49 cl::desc("Disable debug info printing"));
51 static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
52 cl::desc("Make an absence of debug location information explicit."),
56 const char *DWARFGroupName = "DWARF Emission";
57 const char *DbgTimerName = "DWARF Debug Writer";
58 } // end anonymous namespace
60 //===----------------------------------------------------------------------===//
62 /// Configuration values for initial hash set sizes (log2).
64 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
68 DIType DbgVariable::getType() const {
69 DIType Ty = Var.getType();
70 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
72 if (Var.isBlockByrefVariable()) {
73 /* Byref variables, in Blocks, are declared by the programmer as
74 "SomeType VarName;", but the compiler creates a
75 __Block_byref_x_VarName struct, and gives the variable VarName
76 either the struct, or a pointer to the struct, as its type. This
77 is necessary for various behind-the-scenes things the compiler
78 needs to do with by-reference variables in blocks.
80 However, as far as the original *programmer* is concerned, the
81 variable should still have type 'SomeType', as originally declared.
83 The following function dives into the __Block_byref_x_VarName
84 struct to find the original type of the variable. This will be
85 passed back to the code generating the type for the Debug
86 Information Entry for the variable 'VarName'. 'VarName' will then
87 have the original type 'SomeType' in its debug information.
89 The original type 'SomeType' will be the type of the field named
90 'VarName' inside the __Block_byref_x_VarName struct.
92 NOTE: In order for this to not completely fail on the debugger
93 side, the Debug Information Entry for the variable VarName needs to
94 have a DW_AT_location that tells the debugger how to unwind through
95 the pointers and __Block_byref_x_VarName struct to find the actual
96 value of the variable. The function addBlockByrefType does this. */
98 unsigned tag = Ty.getTag();
100 if (tag == dwarf::DW_TAG_pointer_type) {
101 DIDerivedType DTy = DIDerivedType(Ty);
102 subType = DTy.getTypeDerivedFrom();
105 DICompositeType blockStruct = DICompositeType(subType);
106 DIArray Elements = blockStruct.getTypeArray();
108 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
109 DIDescriptor Element = Elements.getElement(i);
110 DIDerivedType DT = DIDerivedType(Element);
111 if (getName() == DT.getName())
112 return (DT.getTypeDerivedFrom());
119 } // end llvm namespace
121 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
122 : Asm(A), MMI(Asm->MMI), FirstCU(0),
123 AbbreviationsSet(InitAbbreviationsSetSize),
125 NextStringPoolNumber = 0;
127 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
128 DwarfStrSectionSym = TextSectionSym = 0;
129 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
130 FunctionBeginSym = FunctionEndSym = 0;
132 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
136 DwarfDebug::~DwarfDebug() {
139 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
140 std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
141 if (Entry.first) return Entry.first;
143 Entry.second = NextStringPoolNumber++;
144 return Entry.first = Asm->GetTempSymbol("string", Entry.second);
148 /// assignAbbrevNumber - Define a unique number for the abbreviation.
150 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
151 // Profile the node so that we can make it unique.
155 // Check the set for priors.
156 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
158 // If it's newly added.
159 if (InSet == &Abbrev) {
160 // Add to abbreviation list.
161 Abbreviations.push_back(&Abbrev);
163 // Assign the vector position + 1 as its number.
164 Abbrev.setNumber(Abbreviations.size());
166 // Assign existing abbreviation number.
167 Abbrev.setNumber(InSet->getNumber());
171 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
172 /// printer to not emit usual symbol prefix before the symbol name is used then
173 /// return linkage name after skipping this special LLVM prefix.
174 static StringRef getRealLinkageName(StringRef LinkageName) {
176 if (LinkageName.startswith(StringRef(&One, 1)))
177 return LinkageName.substr(1);
181 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
182 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
183 /// If there are global variables in this scope then create and insert
184 /// DIEs for these variables.
185 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
186 const MDNode *SPNode) {
187 DIE *SPDie = SPCU->getDIE(SPNode);
189 assert(SPDie && "Unable to find subprogram DIE!");
190 DISubprogram SP(SPNode);
192 DISubprogram SPDecl = SP.getFunctionDeclaration();
193 if (SPDecl.isSubprogram())
194 // Refer function declaration directly.
195 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
196 SPCU->getOrCreateSubprogramDIE(SPDecl));
198 // There is not any need to generate specification DIE for a function
199 // defined at compile unit level. If a function is defined inside another
200 // function then gdb prefers the definition at top level and but does not
201 // expect specification DIE in parent function. So avoid creating
202 // specification DIE for a function defined inside a function.
203 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
204 !SP.getContext().isFile() &&
205 !isSubprogramContext(SP.getContext())) {
206 SPCU-> addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
209 DICompositeType SPTy = SP.getType();
210 DIArray Args = SPTy.getTypeArray();
211 unsigned SPTag = SPTy.getTag();
212 if (SPTag == dwarf::DW_TAG_subroutine_type)
213 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
214 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
215 DIType ATy = DIType(DIType(Args.getElement(i)));
216 SPCU->addType(Arg, ATy);
217 if (ATy.isArtificial())
218 SPCU->addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
219 SPDie->addChild(Arg);
221 DIE *SPDeclDie = SPDie;
222 SPDie = new DIE(dwarf::DW_TAG_subprogram);
223 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
228 // Pick up abstract subprogram DIE.
229 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
230 SPDie = new DIE(dwarf::DW_TAG_subprogram);
231 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
232 dwarf::DW_FORM_ref4, AbsSPDIE);
236 SPCU->addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
237 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
238 SPCU->addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
239 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
240 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
241 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
242 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
247 /// constructLexicalScope - Construct new DW_TAG_lexical_block
248 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
249 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
250 LexicalScope *Scope) {
252 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
253 if (Scope->isAbstractScope())
256 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
260 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
261 if (Ranges.size() > 1) {
262 // .debug_range section has not been laid out yet. Emit offset in
263 // .debug_range as a uint, size 4, for now. emitDIE will handle
264 // DW_AT_ranges appropriately.
265 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
266 DebugRangeSymbols.size()
267 * Asm->getTargetData().getPointerSize());
268 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
269 RE = Ranges.end(); RI != RE; ++RI) {
270 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
271 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
273 DebugRangeSymbols.push_back(NULL);
274 DebugRangeSymbols.push_back(NULL);
278 const MCSymbol *Start = getLabelBeforeInsn(RI->first);
279 const MCSymbol *End = getLabelAfterInsn(RI->second);
281 if (End == 0) return 0;
283 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
284 assert(End->isDefined() && "Invalid end label for an inlined scope!");
286 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
287 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
292 /// constructInlinedScopeDIE - This scope represents inlined body of
293 /// a function. Construct DIE to represent this concrete inlined copy
295 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
296 LexicalScope *Scope) {
298 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
299 assert (Ranges.empty() == false
300 && "LexicalScope does not have instruction markers!");
302 if (!Scope->getScopeNode())
304 DIScope DS(Scope->getScopeNode());
305 DISubprogram InlinedSP = getDISubprogram(DS);
306 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
308 DEBUG(dbgs() << "Unable to find original DIE for inlined subprogram.");
312 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
313 const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
314 const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
316 if (StartLabel == 0 || EndLabel == 0) {
317 assert (0 && "Unexpected Start and End labels for a inlined scope!");
320 assert(StartLabel->isDefined() &&
321 "Invalid starting label for an inlined scope!");
322 assert(EndLabel->isDefined() &&
323 "Invalid end label for an inlined scope!");
325 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
326 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
327 dwarf::DW_FORM_ref4, OriginDIE);
329 if (Ranges.size() > 1) {
330 // .debug_range section has not been laid out yet. Emit offset in
331 // .debug_range as a uint, size 4, for now. emitDIE will handle
332 // DW_AT_ranges appropriately.
333 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
334 DebugRangeSymbols.size()
335 * Asm->getTargetData().getPointerSize());
336 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
337 RE = Ranges.end(); RI != RE; ++RI) {
338 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
339 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
341 DebugRangeSymbols.push_back(NULL);
342 DebugRangeSymbols.push_back(NULL);
344 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
346 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
350 InlinedSubprogramDIEs.insert(OriginDIE);
352 // Track the start label for this inlined function.
353 //.debug_inlined section specification does not clearly state how
354 // to emit inlined scope that is split into multiple instruction ranges.
355 // For now, use first instruction range and emit low_pc/high_pc pair and
356 // corresponding .debug_inlined section entry for this pair.
357 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
358 I = InlineInfo.find(InlinedSP);
360 if (I == InlineInfo.end()) {
361 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel,
363 InlinedSPNodes.push_back(InlinedSP);
365 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
367 DILocation DL(Scope->getInlinedAt());
368 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, TheCU->getID());
369 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
374 /// constructScopeDIE - Construct a DIE for this scope.
375 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
376 if (!Scope || !Scope->getScopeNode())
379 SmallVector <DIE *, 8> Children;
381 // Collect arguments for current function.
382 if (LScopes.isCurrentFunctionScope(Scope))
383 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
384 if (DbgVariable *ArgDV = CurrentFnArguments[i])
386 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope()))
387 Children.push_back(Arg);
389 // Collect lexical scope childrens first.
390 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
391 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
393 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope()))
394 Children.push_back(Variable);
395 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
396 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
397 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
398 Children.push_back(Nested);
399 DIScope DS(Scope->getScopeNode());
400 DIE *ScopeDIE = NULL;
401 if (Scope->getInlinedAt())
402 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
403 else if (DS.isSubprogram()) {
404 ProcessedSPNodes.insert(DS);
405 if (Scope->isAbstractScope()) {
406 ScopeDIE = TheCU->getDIE(DS);
407 // Note down abstract DIE.
409 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
412 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
415 // There is no need to emit empty lexical block DIE.
416 if (Children.empty())
418 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
421 if (!ScopeDIE) return NULL;
424 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
425 E = Children.end(); I != E; ++I)
426 ScopeDIE->addChild(*I);
428 if (DS.isSubprogram())
429 TheCU->addPubTypes(DISubprogram(DS));
434 /// GetOrCreateSourceID - Look up the source id with the given directory and
435 /// source file names. If none currently exists, create a new id and insert it
436 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
439 unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName,
441 // If FE did not provide a file name, then assume stdin.
442 if (FileName.empty())
443 return GetOrCreateSourceID("<stdin>", StringRef());
445 // MCStream expects full path name as filename.
446 if (!DirName.empty() && !sys::path::is_absolute(FileName)) {
447 SmallString<128> FullPathName = DirName;
448 sys::path::append(FullPathName, FileName);
449 // Here FullPathName will be copied into StringMap by GetOrCreateSourceID.
450 return GetOrCreateSourceID(StringRef(FullPathName), StringRef());
453 StringMapEntry<unsigned> &Entry = SourceIdMap.GetOrCreateValue(FileName);
454 if (Entry.getValue())
455 return Entry.getValue();
457 unsigned SrcId = SourceIdMap.size();
458 Entry.setValue(SrcId);
460 // Print out a .file directive to specify files for .loc directives.
461 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, Entry.getKey());
466 /// constructCompileUnit - Create new CompileUnit for the given
467 /// metadata node with tag DW_TAG_compile_unit.
468 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
469 DICompileUnit DIUnit(N);
470 StringRef FN = DIUnit.getFilename();
471 StringRef Dir = DIUnit.getDirectory();
472 unsigned ID = GetOrCreateSourceID(FN, Dir);
474 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
475 CompileUnit *NewCU = new CompileUnit(ID, Die, Asm, this);
476 NewCU->addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
477 DIUnit.getProducer());
478 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
479 DIUnit.getLanguage());
480 NewCU->addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
481 // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
482 // simplifies debug range entries.
483 NewCU->addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
484 // DW_AT_stmt_list is a offset of line number information for this
485 // compile unit in debug_line section.
486 if(Asm->MAI->doesDwarfRequireRelocationForSectionOffset())
487 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
488 Asm->GetTempSymbol("section_line"));
490 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
493 NewCU->addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
494 if (DIUnit.isOptimized())
495 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
497 StringRef Flags = DIUnit.getFlags();
499 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string,
502 unsigned RVer = DIUnit.getRunTimeVersion();
504 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
505 dwarf::DW_FORM_data1, RVer);
509 CUMap.insert(std::make_pair(N, NewCU));
513 /// constructGlobalVariableDIE - Construct global variable DIE.
514 void DwarfDebug::constructGlobalVariableDIE(CompileUnit *TheCU,
516 DIGlobalVariable GV(N);
518 // If debug information is malformed then ignore it.
519 if (GV.Verify() == false)
522 TheCU->createGlobalVariableDIE(N);
526 /// construct SubprogramDIE - Construct subprogram DIE.
527 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
530 if (!SP.isDefinition())
531 // This is a method declaration which will be handled while constructing
535 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
538 TheCU->insertDIE(N, SubprogramDie);
540 // Add to context owner.
541 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
544 TheCU->addGlobal(SP.getName(), SubprogramDie);
550 /// collectInfoFromNamedMDNodes - Collect debug info from named mdnodes such
551 /// as llvm.dbg.enum and llvm.dbg.ty
552 void DwarfDebug::collectInfoFromNamedMDNodes(Module *M) {
553 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp"))
554 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
555 const MDNode *N = NMD->getOperand(i);
556 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
557 constructSubprogramDIE(CU, N);
560 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"))
561 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
562 const MDNode *N = NMD->getOperand(i);
563 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
564 constructGlobalVariableDIE(CU, N);
567 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
568 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
569 DIType Ty(NMD->getOperand(i));
570 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
571 CU->getOrCreateTypeDIE(Ty);
574 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
575 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
576 DIType Ty(NMD->getOperand(i));
577 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
578 CU->getOrCreateTypeDIE(Ty);
582 /// collectLegacyDebugInfo - Collect debug info using DebugInfoFinder.
583 /// FIXME - Remove this when dragon-egg and llvm-gcc switch to DIBuilder.
584 bool DwarfDebug::collectLegacyDebugInfo(Module *M) {
585 DebugInfoFinder DbgFinder;
586 DbgFinder.processModule(*M);
588 bool HasDebugInfo = false;
589 // Scan all the compile-units to see if there are any marked as the main
590 // unit. If not, we do not generate debug info.
591 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
592 E = DbgFinder.compile_unit_end(); I != E; ++I) {
593 if (DICompileUnit(*I).isMain()) {
598 if (!HasDebugInfo) return false;
600 // Create all the compile unit DIEs.
601 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
602 E = DbgFinder.compile_unit_end(); I != E; ++I)
603 constructCompileUnit(*I);
605 // Create DIEs for each global variable.
606 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
607 E = DbgFinder.global_variable_end(); I != E; ++I) {
608 const MDNode *N = *I;
609 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
610 constructGlobalVariableDIE(CU, N);
613 // Create DIEs for each subprogram.
614 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
615 E = DbgFinder.subprogram_end(); I != E; ++I) {
616 const MDNode *N = *I;
617 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
618 constructSubprogramDIE(CU, N);
624 /// beginModule - Emit all Dwarf sections that should come prior to the
625 /// content. Create global DIEs and emit initial debug info sections.
626 /// This is invoked by the target AsmPrinter.
627 void DwarfDebug::beginModule(Module *M) {
628 if (DisableDebugInfoPrinting)
631 // If module has named metadata anchors then use them, otherwise scan the
632 // module using debug info finder to collect debug info.
633 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
635 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
636 DICompileUnit CUNode(CU_Nodes->getOperand(i));
637 CompileUnit *CU = constructCompileUnit(CUNode);
638 DIArray GVs = CUNode.getGlobalVariables();
639 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
640 constructGlobalVariableDIE(CU, GVs.getElement(i));
641 DIArray SPs = CUNode.getSubprograms();
642 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
643 constructSubprogramDIE(CU, SPs.getElement(i));
644 DIArray EnumTypes = CUNode.getEnumTypes();
645 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
646 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
647 DIArray RetainedTypes = CUNode.getRetainedTypes();
648 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
649 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
651 } else if (!collectLegacyDebugInfo(M))
654 collectInfoFromNamedMDNodes(M);
656 // Tell MMI that we have debug info.
657 MMI->setDebugInfoAvailability(true);
659 // Emit initial sections.
662 // Prime section data.
663 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
666 /// endModule - Emit all Dwarf sections that should come after the content.
668 void DwarfDebug::endModule() {
669 if (!FirstCU) return;
670 const Module *M = MMI->getModule();
671 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
673 // Collect info for variables that were optimized out.
674 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
675 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
676 DICompileUnit TheCU(CU_Nodes->getOperand(i));
677 DIArray Subprograms = TheCU.getSubprograms();
678 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
679 DISubprogram SP(Subprograms.getElement(i));
680 if (ProcessedSPNodes.count(SP) != 0) continue;
681 if (!SP.Verify()) continue;
682 if (!SP.isDefinition()) continue;
683 StringRef FName = SP.getLinkageName();
685 FName = SP.getName();
686 NamedMDNode *NMD = getFnSpecificMDNode(*(MMI->getModule()), FName);
688 unsigned E = NMD->getNumOperands();
690 LexicalScope *Scope =
691 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
692 DeadFnScopeMap[SP] = Scope;
694 // Construct subprogram DIE and add variables DIEs.
695 SmallVector<DbgVariable, 8> Variables;
696 for (unsigned I = 0; I != E; ++I) {
697 DIVariable DV(NMD->getOperand(I));
698 if (!DV.Verify()) continue;
699 Variables.push_back(DbgVariable(DV, NULL));
701 CompileUnit *SPCU = CUMap.lookup(TheCU);
702 assert (SPCU && "Unable to find Compile Unit!");
703 constructSubprogramDIE(SPCU, SP);
704 DIE *ScopeDIE = SPCU->getDIE(SP);
705 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
706 if (DIE *VariableDIE =
707 SPCU->constructVariableDIE(&Variables[i], Scope->isAbstractScope()))
708 ScopeDIE->addChild(VariableDIE);
714 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
715 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
716 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
718 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
721 // Emit DW_AT_containing_type attribute to connect types with their
722 // vtable holding type.
723 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
724 CUE = CUMap.end(); CUI != CUE; ++CUI) {
725 CompileUnit *TheCU = CUI->second;
726 TheCU->constructContainingTypeDIEs();
729 // Standard sections final addresses.
730 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
731 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
732 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
733 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
735 // End text sections.
736 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
737 Asm->OutStreamer.SwitchSection(SectionMap[i]);
738 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
741 // Compute DIE offsets and sizes.
742 computeSizeAndOffsets();
744 // Emit all the DIEs into a debug info section
747 // Corresponding abbreviations into a abbrev section.
750 // Emit info into a debug pubnames section.
753 // Emit info into a debug pubtypes section.
756 // Emit info into a debug loc section.
759 // Emit info into a debug aranges section.
762 // Emit info into a debug ranges section.
765 // Emit info into a debug macinfo section.
769 emitDebugInlineInfo();
771 // Emit info into a debug str section.
775 DeleteContainerSeconds(DeadFnScopeMap);
777 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
778 E = CUMap.end(); I != E; ++I)
780 FirstCU = NULL; // Reset for the next Module, if any.
783 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
784 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
786 LLVMContext &Ctx = DV->getContext();
787 // More then one inlined variable corresponds to one abstract variable.
788 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
789 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
791 return AbsDbgVariable;
793 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
797 AbsDbgVariable = new DbgVariable(Var, NULL);
798 addScopeVariable(Scope, AbsDbgVariable);
799 AbstractVariables[Var] = AbsDbgVariable;
800 return AbsDbgVariable;
803 /// addCurrentFnArgument - If Var is a current function argument then add
804 /// it to CurrentFnArguments list.
805 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
806 DbgVariable *Var, LexicalScope *Scope) {
807 if (!LScopes.isCurrentFunctionScope(Scope))
809 DIVariable DV = Var->getVariable();
810 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
812 unsigned ArgNo = DV.getArgNumber();
816 size_t Size = CurrentFnArguments.size();
818 CurrentFnArguments.resize(MF->getFunction()->arg_size());
819 // llvm::Function argument size is not good indicator of how many
820 // arguments does the function have at source level.
822 CurrentFnArguments.resize(ArgNo * 2);
823 CurrentFnArguments[ArgNo - 1] = Var;
827 /// collectVariableInfoFromMMITable - Collect variable information from
828 /// side table maintained by MMI.
830 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
831 SmallPtrSet<const MDNode *, 16> &Processed) {
832 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
833 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
834 VE = VMap.end(); VI != VE; ++VI) {
835 const MDNode *Var = VI->first;
837 Processed.insert(Var);
839 const std::pair<unsigned, DebugLoc> &VP = VI->second;
841 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
843 // If variable scope is not found then skip this variable.
847 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
848 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
849 RegVar->setFrameIndex(VP.first);
850 if (!addCurrentFnArgument(MF, RegVar, Scope))
851 addScopeVariable(Scope, RegVar);
853 AbsDbgVariable->setFrameIndex(VP.first);
857 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
858 /// DBG_VALUE instruction, is in a defined reg.
859 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
860 assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
861 return MI->getNumOperands() == 3 &&
862 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
863 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
866 /// getDebugLocEntry - Get .debug_loc entry for the instruction range starting
868 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
869 const MCSymbol *FLabel,
870 const MCSymbol *SLabel,
871 const MachineInstr *MI) {
872 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
874 if (MI->getNumOperands() != 3) {
875 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
876 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
878 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
879 MachineLocation MLoc;
880 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
881 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
883 if (MI->getOperand(0).isImm())
884 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
885 if (MI->getOperand(0).isFPImm())
886 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
887 if (MI->getOperand(0).isCImm())
888 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
890 assert (0 && "Unexpected 3 operand DBG_VALUE instruction!");
891 return DotDebugLocEntry();
894 /// collectVariableInfo - Find variables for each lexical scope.
896 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
897 SmallPtrSet<const MDNode *, 16> &Processed) {
899 /// collection info from MMI table.
900 collectVariableInfoFromMMITable(MF, Processed);
902 for (SmallVectorImpl<const MDNode*>::const_iterator
903 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
905 const MDNode *Var = *UVI;
906 if (Processed.count(Var))
909 // History contains relevant DBG_VALUE instructions for Var and instructions
911 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
914 const MachineInstr *MInsn = History.front();
917 LexicalScope *Scope = NULL;
918 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
919 DISubprogram(DV.getContext()).describes(MF->getFunction()))
920 Scope = LScopes.getCurrentFunctionScope();
922 if (DV.getVersion() <= LLVMDebugVersion9)
923 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
925 if (MDNode *IA = DV.getInlinedAt())
926 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
928 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
931 // If variable scope is not found then skip this variable.
935 Processed.insert(DV);
936 assert(MInsn->isDebugValue() && "History must begin with debug value");
937 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
938 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
939 if (!addCurrentFnArgument(MF, RegVar, Scope))
940 addScopeVariable(Scope, RegVar);
942 AbsVar->setMInsn(MInsn);
944 // Simple ranges that are fully coalesced.
945 if (History.size() <= 1 || (History.size() == 2 &&
946 MInsn->isIdenticalTo(History.back()))) {
947 RegVar->setMInsn(MInsn);
951 // handle multiple DBG_VALUE instructions describing one variable.
952 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
954 for (SmallVectorImpl<const MachineInstr*>::const_iterator
955 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
956 const MachineInstr *Begin = *HI;
957 assert(Begin->isDebugValue() && "Invalid History entry");
959 // Check if DBG_VALUE is truncating a range.
960 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
961 && !Begin->getOperand(0).getReg())
964 // Compute the range for a register location.
965 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
966 const MCSymbol *SLabel = 0;
969 // If Begin is the last instruction in History then its value is valid
970 // until the end of the function.
971 SLabel = FunctionEndSym;
973 const MachineInstr *End = HI[1];
974 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
975 << "\t" << *Begin << "\t" << *End << "\n");
976 if (End->isDebugValue())
977 SLabel = getLabelBeforeInsn(End);
979 // End is a normal instruction clobbering the range.
980 SLabel = getLabelAfterInsn(End);
981 assert(SLabel && "Forgot label after clobber instruction");
986 // The value is valid until the next DBG_VALUE or clobber.
987 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel, Begin));
989 DotDebugLocEntries.push_back(DotDebugLocEntry());
992 // Collect info for variables that were optimized out.
993 const Function *F = MF->getFunction();
994 if (NamedMDNode *NMD = getFnSpecificMDNode(*(F->getParent()), F->getName())) {
995 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
996 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
997 if (!DV || !Processed.insert(DV))
999 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1000 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1005 /// getLabelBeforeInsn - Return Label preceding the instruction.
1006 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1007 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1008 assert(Label && "Didn't insert label before instruction");
1012 /// getLabelAfterInsn - Return Label immediately following the instruction.
1013 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1014 return LabelsAfterInsn.lookup(MI);
1017 /// beginInstruction - Process beginning of an instruction.
1018 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1019 // Check if source location changes, but ignore DBG_VALUE locations.
1020 if (!MI->isDebugValue()) {
1021 DebugLoc DL = MI->getDebugLoc();
1022 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1023 unsigned Flags = DWARF2_FLAG_IS_STMT;
1025 if (DL == PrologEndLoc) {
1026 Flags |= DWARF2_FLAG_PROLOGUE_END;
1027 PrologEndLoc = DebugLoc();
1029 if (!DL.isUnknown()) {
1030 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1031 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1033 recordSourceLine(0, 0, 0, 0);
1037 // Insert labels where requested.
1038 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1039 LabelsBeforeInsn.find(MI);
1042 if (I == LabelsBeforeInsn.end())
1045 // Label already assigned.
1050 PrevLabel = MMI->getContext().CreateTempSymbol();
1051 Asm->OutStreamer.EmitLabel(PrevLabel);
1053 I->second = PrevLabel;
1056 /// endInstruction - Process end of an instruction.
1057 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1058 // Don't create a new label after DBG_VALUE instructions.
1059 // They don't generate code.
1060 if (!MI->isDebugValue())
1063 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1064 LabelsAfterInsn.find(MI);
1067 if (I == LabelsAfterInsn.end())
1070 // Label already assigned.
1074 // We need a label after this instruction.
1076 PrevLabel = MMI->getContext().CreateTempSymbol();
1077 Asm->OutStreamer.EmitLabel(PrevLabel);
1079 I->second = PrevLabel;
1082 /// identifyScopeMarkers() -
1083 /// Each LexicalScope has first instruction and last instruction to mark
1084 /// beginning and end of a scope respectively. Create an inverse map that list
1085 /// scopes starts (and ends) with an instruction. One instruction may start (or
1086 /// end) multiple scopes. Ignore scopes that are not reachable.
1087 void DwarfDebug::identifyScopeMarkers() {
1088 SmallVector<LexicalScope *, 4> WorkList;
1089 WorkList.push_back(LScopes.getCurrentFunctionScope());
1090 while (!WorkList.empty()) {
1091 LexicalScope *S = WorkList.pop_back_val();
1093 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1094 if (!Children.empty())
1095 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1096 SE = Children.end(); SI != SE; ++SI)
1097 WorkList.push_back(*SI);
1099 if (S->isAbstractScope())
1102 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1105 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1106 RE = Ranges.end(); RI != RE; ++RI) {
1107 assert(RI->first && "InsnRange does not have first instruction!");
1108 assert(RI->second && "InsnRange does not have second instruction!");
1109 requestLabelBeforeInsn(RI->first);
1110 requestLabelAfterInsn(RI->second);
1115 /// getScopeNode - Get MDNode for DebugLoc's scope.
1116 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1117 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1118 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1119 return DL.getScope(Ctx);
1122 /// getFnDebugLoc - Walk up the scope chain of given debug loc and find
1123 /// line number info for the function.
1124 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1125 const MDNode *Scope = getScopeNode(DL, Ctx);
1126 DISubprogram SP = getDISubprogram(Scope);
1128 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1132 /// beginFunction - Gather pre-function debug information. Assumes being
1133 /// emitted immediately after the function entry point.
1134 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1135 if (!MMI->hasDebugInfo()) return;
1136 LScopes.initialize(*MF);
1137 if (LScopes.empty()) return;
1138 identifyScopeMarkers();
1140 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1141 Asm->getFunctionNumber());
1142 // Assumes in correct section after the entry point.
1143 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1145 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1147 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1148 /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1149 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1151 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1153 bool AtBlockEntry = true;
1154 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1156 const MachineInstr *MI = II;
1158 if (MI->isDebugValue()) {
1159 assert (MI->getNumOperands() > 1 && "Invalid machine instruction!");
1161 // Keep track of user variables.
1163 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1165 // Variable is in a register, we need to check for clobbers.
1166 if (isDbgValueInDefinedReg(MI))
1167 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1169 // Check the history of this variable.
1170 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1171 if (History.empty()) {
1172 UserVariables.push_back(Var);
1173 // The first mention of a function argument gets the FunctionBeginSym
1174 // label, so arguments are visible when breaking at function entry.
1176 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1177 DISubprogram(getDISubprogram(DV.getContext()))
1178 .describes(MF->getFunction()))
1179 LabelsBeforeInsn[MI] = FunctionBeginSym;
1181 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1182 const MachineInstr *Prev = History.back();
1183 if (Prev->isDebugValue()) {
1184 // Coalesce identical entries at the end of History.
1185 if (History.size() >= 2 &&
1186 Prev->isIdenticalTo(History[History.size() - 2])) {
1187 DEBUG(dbgs() << "Coalesce identical DBG_VALUE entries:\n"
1189 << "\t" << *History[History.size() - 2] << "\n");
1193 // Terminate old register assignments that don't reach MI;
1194 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1195 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1196 isDbgValueInDefinedReg(Prev)) {
1197 // Previous register assignment needs to terminate at the end of
1199 MachineBasicBlock::const_iterator LastMI =
1200 PrevMBB->getLastNonDebugInstr();
1201 if (LastMI == PrevMBB->end()) {
1202 // Drop DBG_VALUE for empty range.
1203 DEBUG(dbgs() << "Drop DBG_VALUE for empty range:\n"
1204 << "\t" << *Prev << "\n");
1208 // Terminate after LastMI.
1209 History.push_back(LastMI);
1214 History.push_back(MI);
1216 // Not a DBG_VALUE instruction.
1218 AtBlockEntry = false;
1220 // First known non DBG_VALUE location marks beginning of function
1222 if (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown())
1223 PrologEndLoc = MI->getDebugLoc();
1225 // Check if the instruction clobbers any registers with debug vars.
1226 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1227 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1228 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1230 for (const unsigned *AI = TRI->getOverlaps(MOI->getReg());
1231 unsigned Reg = *AI; ++AI) {
1232 const MDNode *Var = LiveUserVar[Reg];
1235 // Reg is now clobbered.
1236 LiveUserVar[Reg] = 0;
1238 // Was MD last defined by a DBG_VALUE referring to Reg?
1239 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1240 if (HistI == DbgValues.end())
1242 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1243 if (History.empty())
1245 const MachineInstr *Prev = History.back();
1246 // Sanity-check: Register assignments are terminated at the end of
1248 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1250 // Is the variable still in Reg?
1251 if (!isDbgValueInDefinedReg(Prev) ||
1252 Prev->getOperand(0).getReg() != Reg)
1254 // Var is clobbered. Make sure the next instruction gets a label.
1255 History.push_back(MI);
1262 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1264 SmallVectorImpl<const MachineInstr*> &History = I->second;
1265 if (History.empty())
1268 // Make sure the final register assignments are terminated.
1269 const MachineInstr *Prev = History.back();
1270 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1271 const MachineBasicBlock *PrevMBB = Prev->getParent();
1272 MachineBasicBlock::const_iterator LastMI =
1273 PrevMBB->getLastNonDebugInstr();
1274 if (LastMI == PrevMBB->end())
1275 // Drop DBG_VALUE for empty range.
1278 // Terminate after LastMI.
1279 History.push_back(LastMI);
1282 // Request labels for the full history.
1283 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1284 const MachineInstr *MI = History[i];
1285 if (MI->isDebugValue())
1286 requestLabelBeforeInsn(MI);
1288 requestLabelAfterInsn(MI);
1292 PrevInstLoc = DebugLoc();
1293 PrevLabel = FunctionBeginSym;
1295 // Record beginning of function.
1296 if (!PrologEndLoc.isUnknown()) {
1297 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1298 MF->getFunction()->getContext());
1299 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1300 FnStartDL.getScope(MF->getFunction()->getContext()),
1301 DWARF2_FLAG_IS_STMT);
1305 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1306 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1307 ScopeVariables[LS].push_back(Var);
1308 // Vars.push_back(Var);
1311 /// endFunction - Gather and emit post-function debug information.
1313 void DwarfDebug::endFunction(const MachineFunction *MF) {
1314 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1316 // Define end label for subprogram.
1317 FunctionEndSym = Asm->GetTempSymbol("func_end",
1318 Asm->getFunctionNumber());
1319 // Assumes in correct section after the entry point.
1320 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1322 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1323 collectVariableInfo(MF, ProcessedVars);
1325 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1326 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1327 assert (TheCU && "Unable to find compile unit!");
1329 // Construct abstract scopes.
1330 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1331 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1332 LexicalScope *AScope = AList[i];
1333 DISubprogram SP(AScope->getScopeNode());
1335 // Collect info for variables that were optimized out.
1336 StringRef FName = SP.getLinkageName();
1338 FName = SP.getName();
1339 if (NamedMDNode *NMD =
1340 getFnSpecificMDNode(*(MF->getFunction()->getParent()), FName)) {
1341 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1342 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
1343 if (!DV || !ProcessedVars.insert(DV))
1345 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1346 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1350 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1351 constructScopeDIE(TheCU, AScope);
1354 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1356 if (!DisableFramePointerElim(*MF))
1357 TheCU->addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
1358 dwarf::DW_FORM_flag, 1);
1360 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1361 MMI->getFrameMoves()));
1364 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1365 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1366 DeleteContainerPointers(I->second);
1367 ScopeVariables.clear();
1368 DeleteContainerPointers(CurrentFnArguments);
1369 UserVariables.clear();
1371 AbstractVariables.clear();
1372 LabelsBeforeInsn.clear();
1373 LabelsAfterInsn.clear();
1377 /// recordSourceLine - Register a source line with debug info. Returns the
1378 /// unique label that was emitted and which provides correspondence to
1379 /// the source line list.
1380 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1386 DIDescriptor Scope(S);
1388 if (Scope.isCompileUnit()) {
1389 DICompileUnit CU(S);
1390 Fn = CU.getFilename();
1391 Dir = CU.getDirectory();
1392 } else if (Scope.isFile()) {
1394 Fn = F.getFilename();
1395 Dir = F.getDirectory();
1396 } else if (Scope.isSubprogram()) {
1398 Fn = SP.getFilename();
1399 Dir = SP.getDirectory();
1400 } else if (Scope.isLexicalBlock()) {
1401 DILexicalBlock DB(S);
1402 Fn = DB.getFilename();
1403 Dir = DB.getDirectory();
1405 assert(0 && "Unexpected scope info");
1407 Src = GetOrCreateSourceID(Fn, Dir);
1409 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1412 //===----------------------------------------------------------------------===//
1414 //===----------------------------------------------------------------------===//
1416 /// computeSizeAndOffset - Compute the size and offset of a DIE.
1419 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
1420 // Get the children.
1421 const std::vector<DIE *> &Children = Die->getChildren();
1423 // If not last sibling and has children then add sibling offset attribute.
1424 if (!Last && !Children.empty())
1425 Die->addSiblingOffset(DIEValueAllocator);
1427 // Record the abbreviation.
1428 assignAbbrevNumber(Die->getAbbrev());
1430 // Get the abbreviation for this DIE.
1431 unsigned AbbrevNumber = Die->getAbbrevNumber();
1432 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1435 Die->setOffset(Offset);
1437 // Start the size with the size of abbreviation code.
1438 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1440 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1441 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1443 // Size the DIE attribute values.
1444 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1445 // Size attribute value.
1446 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1448 // Size the DIE children if any.
1449 if (!Children.empty()) {
1450 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1451 "Children flag not set");
1453 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1454 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
1456 // End of children marker.
1457 Offset += sizeof(int8_t);
1460 Die->setSize(Offset - Die->getOffset());
1464 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
1466 void DwarfDebug::computeSizeAndOffsets() {
1467 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1468 E = CUMap.end(); I != E; ++I) {
1469 // Compute size of compile unit header.
1471 sizeof(int32_t) + // Length of Compilation Unit Info
1472 sizeof(int16_t) + // DWARF version number
1473 sizeof(int32_t) + // Offset Into Abbrev. Section
1474 sizeof(int8_t); // Pointer Size (in bytes)
1475 computeSizeAndOffset(I->second->getCUDie(), Offset, true);
1479 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
1480 /// temporary label to it if SymbolStem is specified.
1481 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
1482 const char *SymbolStem = 0) {
1483 Asm->OutStreamer.SwitchSection(Section);
1484 if (!SymbolStem) return 0;
1486 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
1487 Asm->OutStreamer.EmitLabel(TmpSym);
1491 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
1492 /// the start of each one.
1493 void DwarfDebug::EmitSectionLabels() {
1494 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1496 // Dwarf sections base addresses.
1497 DwarfInfoSectionSym =
1498 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1499 DwarfAbbrevSectionSym =
1500 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1501 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
1503 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1504 EmitSectionSym(Asm, MacroInfo);
1506 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1507 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
1508 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1509 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1510 DwarfStrSectionSym =
1511 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
1512 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1515 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
1516 "section_debug_loc");
1518 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1519 EmitSectionSym(Asm, TLOF.getDataSection());
1522 /// emitDIE - Recursively emits a debug information entry.
1524 void DwarfDebug::emitDIE(DIE *Die) {
1525 // Get the abbreviation for this DIE.
1526 unsigned AbbrevNumber = Die->getAbbrevNumber();
1527 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1529 // Emit the code (index) for the abbreviation.
1530 if (Asm->isVerbose())
1531 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1532 Twine::utohexstr(Die->getOffset()) + ":0x" +
1533 Twine::utohexstr(Die->getSize()) + " " +
1534 dwarf::TagString(Abbrev->getTag()));
1535 Asm->EmitULEB128(AbbrevNumber);
1537 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1538 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1540 // Emit the DIE attribute values.
1541 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1542 unsigned Attr = AbbrevData[i].getAttribute();
1543 unsigned Form = AbbrevData[i].getForm();
1544 assert(Form && "Too many attributes for DIE (check abbreviation)");
1546 if (Asm->isVerbose())
1547 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1550 case dwarf::DW_AT_sibling:
1551 Asm->EmitInt32(Die->getSiblingOffset());
1553 case dwarf::DW_AT_abstract_origin: {
1554 DIEEntry *E = cast<DIEEntry>(Values[i]);
1555 DIE *Origin = E->getEntry();
1556 unsigned Addr = Origin->getOffset();
1557 Asm->EmitInt32(Addr);
1560 case dwarf::DW_AT_ranges: {
1561 // DW_AT_range Value encodes offset in debug_range section.
1562 DIEInteger *V = cast<DIEInteger>(Values[i]);
1564 if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
1565 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1569 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1571 DwarfDebugRangeSectionSym,
1576 case dwarf::DW_AT_location: {
1577 if (DIELabel *L = dyn_cast<DIELabel>(Values[i]))
1578 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1580 Values[i]->EmitValue(Asm, Form);
1583 case dwarf::DW_AT_accessibility: {
1584 if (Asm->isVerbose()) {
1585 DIEInteger *V = cast<DIEInteger>(Values[i]);
1586 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1588 Values[i]->EmitValue(Asm, Form);
1592 // Emit an attribute using the defined form.
1593 Values[i]->EmitValue(Asm, Form);
1598 // Emit the DIE children if any.
1599 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1600 const std::vector<DIE *> &Children = Die->getChildren();
1602 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1603 emitDIE(Children[j]);
1605 if (Asm->isVerbose())
1606 Asm->OutStreamer.AddComment("End Of Children Mark");
1611 /// emitDebugInfo - Emit the debug info section.
1613 void DwarfDebug::emitDebugInfo() {
1614 // Start debug info section.
1615 Asm->OutStreamer.SwitchSection(
1616 Asm->getObjFileLowering().getDwarfInfoSection());
1617 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1618 E = CUMap.end(); I != E; ++I) {
1619 CompileUnit *TheCU = I->second;
1620 DIE *Die = TheCU->getCUDie();
1622 // Emit the compile units header.
1623 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
1626 // Emit size of content not including length itself
1627 unsigned ContentSize = Die->getSize() +
1628 sizeof(int16_t) + // DWARF version number
1629 sizeof(int32_t) + // Offset Into Abbrev. Section
1630 sizeof(int8_t); // Pointer Size (in bytes)
1632 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1633 Asm->EmitInt32(ContentSize);
1634 Asm->OutStreamer.AddComment("DWARF version number");
1635 Asm->EmitInt16(dwarf::DWARF_VERSION);
1636 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1637 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
1638 DwarfAbbrevSectionSym);
1639 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1640 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1643 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
1647 /// emitAbbreviations - Emit the abbreviation section.
1649 void DwarfDebug::emitAbbreviations() const {
1650 // Check to see if it is worth the effort.
1651 if (!Abbreviations.empty()) {
1652 // Start the debug abbrev section.
1653 Asm->OutStreamer.SwitchSection(
1654 Asm->getObjFileLowering().getDwarfAbbrevSection());
1656 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
1658 // For each abbrevation.
1659 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1660 // Get abbreviation data
1661 const DIEAbbrev *Abbrev = Abbreviations[i];
1663 // Emit the abbrevations code (base 1 index.)
1664 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1666 // Emit the abbreviations data.
1670 // Mark end of abbreviations.
1671 Asm->EmitULEB128(0, "EOM(3)");
1673 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
1677 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
1678 /// the line matrix.
1680 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1681 // Define last address of section.
1682 Asm->OutStreamer.AddComment("Extended Op");
1685 Asm->OutStreamer.AddComment("Op size");
1686 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
1687 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1688 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1690 Asm->OutStreamer.AddComment("Section end label");
1692 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1693 Asm->getTargetData().getPointerSize(),
1696 // Mark end of matrix.
1697 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1703 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1705 void DwarfDebug::emitDebugPubNames() {
1706 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1707 E = CUMap.end(); I != E; ++I) {
1708 CompileUnit *TheCU = I->second;
1709 // Start the dwarf pubnames section.
1710 Asm->OutStreamer.SwitchSection(
1711 Asm->getObjFileLowering().getDwarfPubNamesSection());
1713 Asm->OutStreamer.AddComment("Length of Public Names Info");
1714 Asm->EmitLabelDifference(
1715 Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
1716 Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
1718 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
1721 Asm->OutStreamer.AddComment("DWARF Version");
1722 Asm->EmitInt16(dwarf::DWARF_VERSION);
1724 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1725 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1726 DwarfInfoSectionSym);
1728 Asm->OutStreamer.AddComment("Compilation Unit Length");
1729 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1730 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1733 const StringMap<DIE*> &Globals = TheCU->getGlobals();
1734 for (StringMap<DIE*>::const_iterator
1735 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1736 const char *Name = GI->getKeyData();
1737 DIE *Entity = GI->second;
1739 Asm->OutStreamer.AddComment("DIE offset");
1740 Asm->EmitInt32(Entity->getOffset());
1742 if (Asm->isVerbose())
1743 Asm->OutStreamer.AddComment("External Name");
1744 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
1747 Asm->OutStreamer.AddComment("End Mark");
1749 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
1754 void DwarfDebug::emitDebugPubTypes() {
1755 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1756 E = CUMap.end(); I != E; ++I) {
1757 CompileUnit *TheCU = I->second;
1758 // Start the dwarf pubnames section.
1759 Asm->OutStreamer.SwitchSection(
1760 Asm->getObjFileLowering().getDwarfPubTypesSection());
1761 Asm->OutStreamer.AddComment("Length of Public Types Info");
1762 Asm->EmitLabelDifference(
1763 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
1764 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
1766 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
1769 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
1770 Asm->EmitInt16(dwarf::DWARF_VERSION);
1772 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1773 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1774 DwarfInfoSectionSym);
1776 Asm->OutStreamer.AddComment("Compilation Unit Length");
1777 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1778 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1781 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
1782 for (StringMap<DIE*>::const_iterator
1783 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1784 const char *Name = GI->getKeyData();
1785 DIE *Entity = GI->second;
1787 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
1788 Asm->EmitInt32(Entity->getOffset());
1790 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
1791 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
1794 Asm->OutStreamer.AddComment("End Mark");
1796 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
1801 /// emitDebugStr - Emit visible names into a debug str section.
1803 void DwarfDebug::emitDebugStr() {
1804 // Check to see if it is worth the effort.
1805 if (StringPool.empty()) return;
1807 // Start the dwarf str section.
1808 Asm->OutStreamer.SwitchSection(
1809 Asm->getObjFileLowering().getDwarfStrSection());
1811 // Get all of the string pool entries and put them in an array by their ID so
1812 // we can sort them.
1813 SmallVector<std::pair<unsigned,
1814 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
1816 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
1817 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
1818 Entries.push_back(std::make_pair(I->second.second, &*I));
1820 array_pod_sort(Entries.begin(), Entries.end());
1822 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
1823 // Emit a label for reference from debug information entries.
1824 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
1826 // Emit the string itself.
1827 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
1831 /// emitDebugLoc - Emit visible names into a debug loc section.
1833 void DwarfDebug::emitDebugLoc() {
1834 if (DotDebugLocEntries.empty())
1837 for (SmallVector<DotDebugLocEntry, 4>::iterator
1838 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1840 DotDebugLocEntry &Entry = *I;
1841 if (I + 1 != DotDebugLocEntries.end())
1845 // Start the dwarf loc section.
1846 Asm->OutStreamer.SwitchSection(
1847 Asm->getObjFileLowering().getDwarfLocSection());
1848 unsigned char Size = Asm->getTargetData().getPointerSize();
1849 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
1851 for (SmallVector<DotDebugLocEntry, 4>::iterator
1852 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1853 I != E; ++I, ++index) {
1854 DotDebugLocEntry &Entry = *I;
1855 if (Entry.isMerged()) continue;
1856 if (Entry.isEmpty()) {
1857 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1858 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1859 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
1861 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
1862 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
1863 DIVariable DV(Entry.Variable);
1864 Asm->OutStreamer.AddComment("Loc expr size");
1865 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1866 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1867 Asm->EmitLabelDifference(end, begin, 2);
1868 Asm->OutStreamer.EmitLabel(begin);
1869 if (Entry.isInt()) {
1870 DIBasicType BTy(DV.getType());
1872 (BTy.getEncoding() == dwarf::DW_ATE_signed
1873 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
1874 Asm->OutStreamer.AddComment("DW_OP_consts");
1875 Asm->EmitInt8(dwarf::DW_OP_consts);
1876 Asm->EmitSLEB128(Entry.getInt());
1878 Asm->OutStreamer.AddComment("DW_OP_constu");
1879 Asm->EmitInt8(dwarf::DW_OP_constu);
1880 Asm->EmitULEB128(Entry.getInt());
1882 } else if (Entry.isLocation()) {
1883 if (!DV.hasComplexAddress())
1885 Asm->EmitDwarfRegOp(Entry.Loc);
1887 // Complex address entry.
1888 unsigned N = DV.getNumAddrElements();
1890 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
1891 if (Entry.Loc.getOffset()) {
1893 Asm->EmitDwarfRegOp(Entry.Loc);
1894 Asm->OutStreamer.AddComment("DW_OP_deref");
1895 Asm->EmitInt8(dwarf::DW_OP_deref);
1896 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
1897 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
1898 Asm->EmitSLEB128(DV.getAddrElement(1));
1900 // If first address element is OpPlus then emit
1901 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
1902 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
1903 Asm->EmitDwarfRegOp(Loc);
1907 Asm->EmitDwarfRegOp(Entry.Loc);
1910 // Emit remaining complex address elements.
1911 for (; i < N; ++i) {
1912 uint64_t Element = DV.getAddrElement(i);
1913 if (Element == DIBuilder::OpPlus) {
1914 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
1915 Asm->EmitULEB128(DV.getAddrElement(++i));
1916 } else if (Element == DIBuilder::OpDeref)
1917 Asm->EmitInt8(dwarf::DW_OP_deref);
1918 else llvm_unreachable("unknown Opcode found in complex address");
1922 // else ... ignore constant fp. There is not any good way to
1923 // to represent them here in dwarf.
1924 Asm->OutStreamer.EmitLabel(end);
1929 /// EmitDebugARanges - Emit visible names into a debug aranges section.
1931 void DwarfDebug::EmitDebugARanges() {
1932 // Start the dwarf aranges section.
1933 Asm->OutStreamer.SwitchSection(
1934 Asm->getObjFileLowering().getDwarfARangesSection());
1937 /// emitDebugRanges - Emit visible names into a debug ranges section.
1939 void DwarfDebug::emitDebugRanges() {
1940 // Start the dwarf ranges section.
1941 Asm->OutStreamer.SwitchSection(
1942 Asm->getObjFileLowering().getDwarfRangesSection());
1943 unsigned char Size = Asm->getTargetData().getPointerSize();
1944 for (SmallVector<const MCSymbol *, 8>::iterator
1945 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
1948 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
1950 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1954 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
1956 void DwarfDebug::emitDebugMacInfo() {
1957 if (const MCSection *LineInfo =
1958 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
1959 // Start the dwarf macinfo section.
1960 Asm->OutStreamer.SwitchSection(LineInfo);
1964 /// emitDebugInlineInfo - Emit inline info using following format.
1966 /// 1. length of section
1967 /// 2. Dwarf version number
1968 /// 3. address size.
1970 /// Entries (one "entry" for each function that was inlined):
1972 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
1973 /// otherwise offset into __debug_str for regular function name.
1974 /// 2. offset into __debug_str section for regular function name.
1975 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
1976 /// instances for the function.
1978 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
1979 /// inlined instance; the die_offset points to the inlined_subroutine die in the
1980 /// __debug_info section, and the low_pc is the starting address for the
1981 /// inlining instance.
1982 void DwarfDebug::emitDebugInlineInfo() {
1983 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
1989 Asm->OutStreamer.SwitchSection(
1990 Asm->getObjFileLowering().getDwarfDebugInlineSection());
1992 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
1993 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
1994 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
1996 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
1998 Asm->OutStreamer.AddComment("Dwarf Version");
1999 Asm->EmitInt16(dwarf::DWARF_VERSION);
2000 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2001 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2003 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2004 E = InlinedSPNodes.end(); I != E; ++I) {
2006 const MDNode *Node = *I;
2007 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2008 = InlineInfo.find(Node);
2009 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2010 DISubprogram SP(Node);
2011 StringRef LName = SP.getLinkageName();
2012 StringRef Name = SP.getName();
2014 Asm->OutStreamer.AddComment("MIPS linkage name");
2015 if (LName.empty()) {
2016 Asm->OutStreamer.EmitBytes(Name, 0);
2017 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
2019 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2020 DwarfStrSectionSym);
2022 Asm->OutStreamer.AddComment("Function name");
2023 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2024 Asm->EmitULEB128(Labels.size(), "Inline count");
2026 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2027 LE = Labels.end(); LI != LE; ++LI) {
2028 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2029 Asm->EmitInt32(LI->second->getOffset());
2031 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2032 Asm->OutStreamer.EmitSymbolValue(LI->first,
2033 Asm->getTargetData().getPointerSize(),0);
2037 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));