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 void 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));
512 /// getCompileUnit - Get CompileUnit DIE.
513 CompileUnit *DwarfDebug::getCompileUnit(const MDNode *N) const {
514 assert (N && "Invalid DwarfDebug::getCompileUnit argument!");
516 const MDNode *CUNode = NULL;
517 if (D.isCompileUnit())
519 else if (D.isSubprogram())
520 CUNode = DISubprogram(N).getCompileUnit();
522 CUNode = DIType(N).getCompileUnit();
523 else if (D.isGlobalVariable())
524 CUNode = DIGlobalVariable(N).getCompileUnit();
525 else if (D.isVariable())
526 CUNode = DIVariable(N).getCompileUnit();
527 else if (D.isNameSpace())
528 CUNode = DINameSpace(N).getCompileUnit();
530 CUNode = DIFile(N).getCompileUnit();
534 DenseMap<const MDNode *, CompileUnit *>::const_iterator I
535 = CUMap.find(CUNode);
536 if (I == CUMap.end())
541 /// constructGlobalVariableDIE - Construct global variable DIE.
542 void DwarfDebug::constructGlobalVariableDIE(CompileUnit *TheCU,
544 DIGlobalVariable GV(N);
546 // If debug information is malformed then ignore it.
547 if (GV.Verify() == false)
550 TheCU->createGlobalVariableDIE(N);
554 /// construct SubprogramDIE - Construct subprogram DIE.
555 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
558 if (!SP.isDefinition())
559 // This is a method declaration which will be handled while constructing
563 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
566 TheCU->insertDIE(N, SubprogramDie);
568 // Add to context owner.
569 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
572 TheCU->addGlobal(SP.getName(), SubprogramDie);
577 /// collectInfoFromNamedMDNodes - Collect debug info from named mdnodes such
578 /// as llvm.dbg.enum and llvm.dbg.ty
579 void DwarfDebug::collectInfoFromNamedMDNodes(Module *M) {
580 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
581 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
582 DIType Ty(NMD->getOperand(i));
583 getCompileUnit(Ty)->getOrCreateTypeDIE(Ty);
586 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
587 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
588 DIType Ty(NMD->getOperand(i));
589 getCompileUnit(Ty)->getOrCreateTypeDIE(Ty);
593 /// collectLegacyDebugInfo - Collect debug info using DebugInfoFinder.
594 /// FIXME - Remove this when dragon-egg and llvm-gcc switch to DIBuilder.
595 bool DwarfDebug::collectLegacyDebugInfo(Module *M) {
596 DebugInfoFinder DbgFinder;
597 DbgFinder.processModule(*M);
599 bool HasDebugInfo = false;
600 // Scan all the compile-units to see if there are any marked as the main
601 // unit. If not, we do not generate debug info.
602 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
603 E = DbgFinder.compile_unit_end(); I != E; ++I) {
604 if (DICompileUnit(*I).isMain()) {
609 if (!HasDebugInfo) return false;
611 // Create all the compile unit DIEs.
612 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
613 E = DbgFinder.compile_unit_end(); I != E; ++I)
614 constructCompileUnit(*I);
616 // Create DIEs for each global variable.
617 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
618 E = DbgFinder.global_variable_end(); I != E; ++I) {
619 const MDNode *N = *I;
620 constructGlobalVariableDIE(getCompileUnit(N), N);
623 // Create DIEs for each subprogram.
624 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
625 E = DbgFinder.subprogram_end(); I != E; ++I) {
626 const MDNode *N = *I;
627 constructSubprogramDIE(getCompileUnit(N), N);
633 /// beginModule - Emit all Dwarf sections that should come prior to the
634 /// content. Create global DIEs and emit initial debug info sections.
635 /// This is invoked by the target AsmPrinter.
636 void DwarfDebug::beginModule(Module *M) {
637 if (DisableDebugInfoPrinting)
640 // If module has named metadata anchors then use them, otherwise scan the
641 // module using debug info finder to collect debug info.
642 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
645 NamedMDNode *GV_Nodes = M->getNamedMetadata("llvm.dbg.gv");
646 NamedMDNode *SP_Nodes = M->getNamedMetadata("llvm.dbg.sp");
647 if (!GV_Nodes && !SP_Nodes)
648 // If there are not any global variables or any functions then
649 // there is not any debug info in this module.
652 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i)
653 constructCompileUnit(CU_Nodes->getOperand(i));
656 for (unsigned i = 0, e = GV_Nodes->getNumOperands(); i != e; ++i) {
657 const MDNode *N = GV_Nodes->getOperand(i);
658 constructGlobalVariableDIE(getCompileUnit(N), N);
662 for (unsigned i = 0, e = SP_Nodes->getNumOperands(); i != e; ++i) {
663 const MDNode *N = SP_Nodes->getOperand(i);
664 constructSubprogramDIE(getCompileUnit(N), N);
667 } else if (!collectLegacyDebugInfo(M))
670 collectInfoFromNamedMDNodes(M);
672 // Tell MMI that we have debug info.
673 MMI->setDebugInfoAvailability(true);
675 // Emit initial sections.
678 // Prime section data.
679 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
682 /// endModule - Emit all Dwarf sections that should come after the content.
684 void DwarfDebug::endModule() {
685 if (!FirstCU) return;
686 const Module *M = MMI->getModule();
687 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
688 if (NamedMDNode *AllSPs = M->getNamedMetadata("llvm.dbg.sp")) {
689 for (unsigned SI = 0, SE = AllSPs->getNumOperands(); SI != SE; ++SI) {
690 if (ProcessedSPNodes.count(AllSPs->getOperand(SI)) != 0) continue;
691 DISubprogram SP(AllSPs->getOperand(SI));
692 if (!SP.Verify()) continue;
694 // Collect info for variables that were optimized out.
695 if (!SP.isDefinition()) continue;
696 StringRef FName = SP.getLinkageName();
698 FName = SP.getName();
699 NamedMDNode *NMD = getFnSpecificMDNode(*(MMI->getModule()), FName);
701 unsigned E = NMD->getNumOperands();
703 LexicalScope *Scope = new LexicalScope(NULL, DIDescriptor(SP), NULL,
705 DeadFnScopeMap[SP] = Scope;
706 SmallVector<DbgVariable, 8> Variables;
707 for (unsigned I = 0; I != E; ++I) {
708 DIVariable DV(NMD->getOperand(I));
709 if (!DV.Verify()) continue;
710 Variables.push_back(DbgVariable(DV, NULL));
713 // Construct subprogram DIE and add variables DIEs.
714 CompileUnit *SPCU = getCompileUnit(SP);
715 constructSubprogramDIE(SPCU, SP);
716 DIE *ScopeDIE = SPCU->getDIE(SP);
717 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
718 if (DIE *VariableDIE =
719 SPCU->constructVariableDIE(&Variables[i], Scope->isAbstractScope()))
720 ScopeDIE->addChild(VariableDIE);
725 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
726 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
727 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
729 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
732 // Emit DW_AT_containing_type attribute to connect types with their
733 // vtable holding type.
734 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
735 CUE = CUMap.end(); CUI != CUE; ++CUI) {
736 CompileUnit *TheCU = CUI->second;
737 TheCU->constructContainingTypeDIEs();
740 // Standard sections final addresses.
741 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
742 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
743 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
744 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
746 // End text sections.
747 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
748 Asm->OutStreamer.SwitchSection(SectionMap[i]);
749 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
752 // Compute DIE offsets and sizes.
753 computeSizeAndOffsets();
755 // Emit all the DIEs into a debug info section
758 // Corresponding abbreviations into a abbrev section.
761 // Emit info into a debug pubnames section.
764 // Emit info into a debug pubtypes section.
767 // Emit info into a debug loc section.
770 // Emit info into a debug aranges section.
773 // Emit info into a debug ranges section.
776 // Emit info into a debug macinfo section.
780 emitDebugInlineInfo();
782 // Emit info into a debug str section.
786 DeleteContainerSeconds(DeadFnScopeMap);
787 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
788 E = CUMap.end(); I != E; ++I)
790 FirstCU = NULL; // Reset for the next Module, if any.
793 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
794 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
796 LLVMContext &Ctx = DV->getContext();
797 // More then one inlined variable corresponds to one abstract variable.
798 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
799 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
801 return AbsDbgVariable;
803 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
807 AbsDbgVariable = new DbgVariable(Var, NULL);
808 addScopeVariable(Scope, AbsDbgVariable);
809 AbstractVariables[Var] = AbsDbgVariable;
810 return AbsDbgVariable;
813 /// addCurrentFnArgument - If Var is a current function argument then add
814 /// it to CurrentFnArguments list.
815 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
816 DbgVariable *Var, LexicalScope *Scope) {
817 if (!LScopes.isCurrentFunctionScope(Scope))
819 DIVariable DV = Var->getVariable();
820 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
822 unsigned ArgNo = DV.getArgNumber();
826 size_t Size = CurrentFnArguments.size();
828 CurrentFnArguments.resize(MF->getFunction()->arg_size());
829 // llvm::Function argument size is not good indicator of how many
830 // arguments does the function have at source level.
832 CurrentFnArguments.resize(ArgNo * 2);
833 CurrentFnArguments[ArgNo - 1] = Var;
837 /// collectVariableInfoFromMMITable - Collect variable information from
838 /// side table maintained by MMI.
840 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
841 SmallPtrSet<const MDNode *, 16> &Processed) {
842 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
843 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
844 VE = VMap.end(); VI != VE; ++VI) {
845 const MDNode *Var = VI->first;
847 Processed.insert(Var);
849 const std::pair<unsigned, DebugLoc> &VP = VI->second;
851 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
853 // If variable scope is not found then skip this variable.
857 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
858 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
859 RegVar->setFrameIndex(VP.first);
860 if (!addCurrentFnArgument(MF, RegVar, Scope))
861 addScopeVariable(Scope, RegVar);
863 AbsDbgVariable->setFrameIndex(VP.first);
867 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
868 /// DBG_VALUE instruction, is in a defined reg.
869 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
870 assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
871 return MI->getNumOperands() == 3 &&
872 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
873 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
876 /// getDebugLocEntry - Get .debug_loc entry for the instruction range starting
878 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
879 const MCSymbol *FLabel,
880 const MCSymbol *SLabel,
881 const MachineInstr *MI) {
882 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
884 if (MI->getNumOperands() != 3) {
885 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
886 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
888 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
889 MachineLocation MLoc;
890 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
891 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
893 if (MI->getOperand(0).isImm())
894 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
895 if (MI->getOperand(0).isFPImm())
896 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
897 if (MI->getOperand(0).isCImm())
898 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
900 assert (0 && "Unexpected 3 operand DBG_VALUE instruction!");
901 return DotDebugLocEntry();
904 /// collectVariableInfo - Find variables for each lexical scope.
906 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
907 SmallPtrSet<const MDNode *, 16> &Processed) {
909 /// collection info from MMI table.
910 collectVariableInfoFromMMITable(MF, Processed);
912 for (SmallVectorImpl<const MDNode*>::const_iterator
913 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
915 const MDNode *Var = *UVI;
916 if (Processed.count(Var))
919 // History contains relevant DBG_VALUE instructions for Var and instructions
921 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
924 const MachineInstr *MInsn = History.front();
927 LexicalScope *Scope = NULL;
928 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
929 DISubprogram(DV.getContext()).describes(MF->getFunction()))
930 Scope = LScopes.getCurrentFunctionScope();
932 if (DV.getVersion() <= LLVMDebugVersion9)
933 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
935 if (MDNode *IA = DV.getInlinedAt())
936 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
938 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
941 // If variable scope is not found then skip this variable.
945 Processed.insert(DV);
946 assert(MInsn->isDebugValue() && "History must begin with debug value");
947 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
948 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
949 if (!addCurrentFnArgument(MF, RegVar, Scope))
950 addScopeVariable(Scope, RegVar);
952 AbsVar->setMInsn(MInsn);
954 // Simple ranges that are fully coalesced.
955 if (History.size() <= 1 || (History.size() == 2 &&
956 MInsn->isIdenticalTo(History.back()))) {
957 RegVar->setMInsn(MInsn);
961 // handle multiple DBG_VALUE instructions describing one variable.
962 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
964 for (SmallVectorImpl<const MachineInstr*>::const_iterator
965 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
966 const MachineInstr *Begin = *HI;
967 assert(Begin->isDebugValue() && "Invalid History entry");
969 // Check if DBG_VALUE is truncating a range.
970 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
971 && !Begin->getOperand(0).getReg())
974 // Compute the range for a register location.
975 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
976 const MCSymbol *SLabel = 0;
979 // If Begin is the last instruction in History then its value is valid
980 // until the end of the function.
981 SLabel = FunctionEndSym;
983 const MachineInstr *End = HI[1];
984 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
985 << "\t" << *Begin << "\t" << *End << "\n");
986 if (End->isDebugValue())
987 SLabel = getLabelBeforeInsn(End);
989 // End is a normal instruction clobbering the range.
990 SLabel = getLabelAfterInsn(End);
991 assert(SLabel && "Forgot label after clobber instruction");
996 // The value is valid until the next DBG_VALUE or clobber.
997 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel, Begin));
999 DotDebugLocEntries.push_back(DotDebugLocEntry());
1002 // Collect info for variables that were optimized out.
1003 const Function *F = MF->getFunction();
1004 if (NamedMDNode *NMD = getFnSpecificMDNode(*(F->getParent()), F->getName())) {
1005 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1006 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
1007 if (!DV || !Processed.insert(DV))
1009 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1010 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1015 /// getLabelBeforeInsn - Return Label preceding the instruction.
1016 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1017 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1018 assert(Label && "Didn't insert label before instruction");
1022 /// getLabelAfterInsn - Return Label immediately following the instruction.
1023 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1024 return LabelsAfterInsn.lookup(MI);
1027 /// beginInstruction - Process beginning of an instruction.
1028 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1029 // Check if source location changes, but ignore DBG_VALUE locations.
1030 if (!MI->isDebugValue()) {
1031 DebugLoc DL = MI->getDebugLoc();
1032 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1033 unsigned Flags = DWARF2_FLAG_IS_STMT;
1035 if (DL == PrologEndLoc) {
1036 Flags |= DWARF2_FLAG_PROLOGUE_END;
1037 PrologEndLoc = DebugLoc();
1039 if (!DL.isUnknown()) {
1040 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1041 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1043 recordSourceLine(0, 0, 0, 0);
1047 // Insert labels where requested.
1048 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1049 LabelsBeforeInsn.find(MI);
1052 if (I == LabelsBeforeInsn.end())
1055 // Label already assigned.
1060 PrevLabel = MMI->getContext().CreateTempSymbol();
1061 Asm->OutStreamer.EmitLabel(PrevLabel);
1063 I->second = PrevLabel;
1066 /// endInstruction - Process end of an instruction.
1067 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1068 // Don't create a new label after DBG_VALUE instructions.
1069 // They don't generate code.
1070 if (!MI->isDebugValue())
1073 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1074 LabelsAfterInsn.find(MI);
1077 if (I == LabelsAfterInsn.end())
1080 // Label already assigned.
1084 // We need a label after this instruction.
1086 PrevLabel = MMI->getContext().CreateTempSymbol();
1087 Asm->OutStreamer.EmitLabel(PrevLabel);
1089 I->second = PrevLabel;
1092 /// identifyScopeMarkers() -
1093 /// Each LexicalScope has first instruction and last instruction to mark
1094 /// beginning and end of a scope respectively. Create an inverse map that list
1095 /// scopes starts (and ends) with an instruction. One instruction may start (or
1096 /// end) multiple scopes. Ignore scopes that are not reachable.
1097 void DwarfDebug::identifyScopeMarkers() {
1098 SmallVector<LexicalScope *, 4> WorkList;
1099 WorkList.push_back(LScopes.getCurrentFunctionScope());
1100 while (!WorkList.empty()) {
1101 LexicalScope *S = WorkList.pop_back_val();
1103 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1104 if (!Children.empty())
1105 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1106 SE = Children.end(); SI != SE; ++SI)
1107 WorkList.push_back(*SI);
1109 if (S->isAbstractScope())
1112 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1115 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1116 RE = Ranges.end(); RI != RE; ++RI) {
1117 assert(RI->first && "InsnRange does not have first instruction!");
1118 assert(RI->second && "InsnRange does not have second instruction!");
1119 requestLabelBeforeInsn(RI->first);
1120 requestLabelAfterInsn(RI->second);
1125 /// getScopeNode - Get MDNode for DebugLoc's scope.
1126 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1127 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1128 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1129 return DL.getScope(Ctx);
1132 /// getFnDebugLoc - Walk up the scope chain of given debug loc and find
1133 /// line number info for the function.
1134 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1135 const MDNode *Scope = getScopeNode(DL, Ctx);
1136 DISubprogram SP = getDISubprogram(Scope);
1138 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1142 /// beginFunction - Gather pre-function debug information. Assumes being
1143 /// emitted immediately after the function entry point.
1144 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1145 if (!MMI->hasDebugInfo()) return;
1146 LScopes.initialize(*MF);
1147 if (LScopes.empty()) return;
1148 identifyScopeMarkers();
1150 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1151 Asm->getFunctionNumber());
1152 // Assumes in correct section after the entry point.
1153 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1155 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1157 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1158 /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1159 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1161 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1163 bool AtBlockEntry = true;
1164 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1166 const MachineInstr *MI = II;
1168 if (MI->isDebugValue()) {
1169 assert (MI->getNumOperands() > 1 && "Invalid machine instruction!");
1171 // Keep track of user variables.
1173 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1175 // Variable is in a register, we need to check for clobbers.
1176 if (isDbgValueInDefinedReg(MI))
1177 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1179 // Check the history of this variable.
1180 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1181 if (History.empty()) {
1182 UserVariables.push_back(Var);
1183 // The first mention of a function argument gets the FunctionBeginSym
1184 // label, so arguments are visible when breaking at function entry.
1186 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1187 DISubprogram(getDISubprogram(DV.getContext()))
1188 .describes(MF->getFunction()))
1189 LabelsBeforeInsn[MI] = FunctionBeginSym;
1191 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1192 const MachineInstr *Prev = History.back();
1193 if (Prev->isDebugValue()) {
1194 // Coalesce identical entries at the end of History.
1195 if (History.size() >= 2 &&
1196 Prev->isIdenticalTo(History[History.size() - 2])) {
1197 DEBUG(dbgs() << "Coalesce identical DBG_VALUE entries:\n"
1199 << "\t" << *History[History.size() - 2] << "\n");
1203 // Terminate old register assignments that don't reach MI;
1204 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1205 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1206 isDbgValueInDefinedReg(Prev)) {
1207 // Previous register assignment needs to terminate at the end of
1209 MachineBasicBlock::const_iterator LastMI =
1210 PrevMBB->getLastNonDebugInstr();
1211 if (LastMI == PrevMBB->end()) {
1212 // Drop DBG_VALUE for empty range.
1213 DEBUG(dbgs() << "Drop DBG_VALUE for empty range:\n"
1214 << "\t" << *Prev << "\n");
1218 // Terminate after LastMI.
1219 History.push_back(LastMI);
1224 History.push_back(MI);
1226 // Not a DBG_VALUE instruction.
1228 AtBlockEntry = false;
1230 // First known non DBG_VALUE location marks beginning of function
1232 if (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown())
1233 PrologEndLoc = MI->getDebugLoc();
1235 // Check if the instruction clobbers any registers with debug vars.
1236 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1237 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1238 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1240 for (const unsigned *AI = TRI->getOverlaps(MOI->getReg());
1241 unsigned Reg = *AI; ++AI) {
1242 const MDNode *Var = LiveUserVar[Reg];
1245 // Reg is now clobbered.
1246 LiveUserVar[Reg] = 0;
1248 // Was MD last defined by a DBG_VALUE referring to Reg?
1249 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1250 if (HistI == DbgValues.end())
1252 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1253 if (History.empty())
1255 const MachineInstr *Prev = History.back();
1256 // Sanity-check: Register assignments are terminated at the end of
1258 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1260 // Is the variable still in Reg?
1261 if (!isDbgValueInDefinedReg(Prev) ||
1262 Prev->getOperand(0).getReg() != Reg)
1264 // Var is clobbered. Make sure the next instruction gets a label.
1265 History.push_back(MI);
1272 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1274 SmallVectorImpl<const MachineInstr*> &History = I->second;
1275 if (History.empty())
1278 // Make sure the final register assignments are terminated.
1279 const MachineInstr *Prev = History.back();
1280 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1281 const MachineBasicBlock *PrevMBB = Prev->getParent();
1282 MachineBasicBlock::const_iterator LastMI =
1283 PrevMBB->getLastNonDebugInstr();
1284 if (LastMI == PrevMBB->end())
1285 // Drop DBG_VALUE for empty range.
1288 // Terminate after LastMI.
1289 History.push_back(LastMI);
1292 // Request labels for the full history.
1293 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1294 const MachineInstr *MI = History[i];
1295 if (MI->isDebugValue())
1296 requestLabelBeforeInsn(MI);
1298 requestLabelAfterInsn(MI);
1302 PrevInstLoc = DebugLoc();
1303 PrevLabel = FunctionBeginSym;
1305 // Record beginning of function.
1306 if (!PrologEndLoc.isUnknown()) {
1307 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1308 MF->getFunction()->getContext());
1309 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1310 FnStartDL.getScope(MF->getFunction()->getContext()),
1311 DWARF2_FLAG_IS_STMT);
1315 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1316 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1317 ScopeVariables[LS].push_back(Var);
1318 // Vars.push_back(Var);
1321 /// endFunction - Gather and emit post-function debug information.
1323 void DwarfDebug::endFunction(const MachineFunction *MF) {
1324 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1326 // Define end label for subprogram.
1327 FunctionEndSym = Asm->GetTempSymbol("func_end",
1328 Asm->getFunctionNumber());
1329 // Assumes in correct section after the entry point.
1330 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1332 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1333 collectVariableInfo(MF, ProcessedVars);
1335 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1336 CompileUnit *TheCU = getCompileUnit(FnScope->getScopeNode());
1338 // Construct abstract scopes.
1339 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1340 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1341 LexicalScope *AScope = AList[i];
1342 DISubprogram SP(AScope->getScopeNode());
1344 // Collect info for variables that were optimized out.
1345 StringRef FName = SP.getLinkageName();
1347 FName = SP.getName();
1348 if (NamedMDNode *NMD =
1349 getFnSpecificMDNode(*(MF->getFunction()->getParent()), FName)) {
1350 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1351 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
1352 if (!DV || !ProcessedVars.insert(DV))
1354 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1355 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1359 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1360 constructScopeDIE(TheCU, AScope);
1363 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1365 if (!DisableFramePointerElim(*MF))
1366 TheCU->addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
1367 dwarf::DW_FORM_flag, 1);
1369 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1370 MMI->getFrameMoves()));
1373 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1374 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1375 DeleteContainerPointers(I->second);
1376 ScopeVariables.clear();
1377 DeleteContainerPointers(CurrentFnArguments);
1378 UserVariables.clear();
1380 AbstractVariables.clear();
1381 LabelsBeforeInsn.clear();
1382 LabelsAfterInsn.clear();
1386 /// recordSourceLine - Register a source line with debug info. Returns the
1387 /// unique label that was emitted and which provides correspondence to
1388 /// the source line list.
1389 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1395 DIDescriptor Scope(S);
1397 if (Scope.isCompileUnit()) {
1398 DICompileUnit CU(S);
1399 Fn = CU.getFilename();
1400 Dir = CU.getDirectory();
1401 } else if (Scope.isFile()) {
1403 Fn = F.getFilename();
1404 Dir = F.getDirectory();
1405 } else if (Scope.isSubprogram()) {
1407 Fn = SP.getFilename();
1408 Dir = SP.getDirectory();
1409 } else if (Scope.isLexicalBlock()) {
1410 DILexicalBlock DB(S);
1411 Fn = DB.getFilename();
1412 Dir = DB.getDirectory();
1414 assert(0 && "Unexpected scope info");
1416 Src = GetOrCreateSourceID(Fn, Dir);
1418 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1421 //===----------------------------------------------------------------------===//
1423 //===----------------------------------------------------------------------===//
1425 /// computeSizeAndOffset - Compute the size and offset of a DIE.
1428 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
1429 // Get the children.
1430 const std::vector<DIE *> &Children = Die->getChildren();
1432 // If not last sibling and has children then add sibling offset attribute.
1433 if (!Last && !Children.empty())
1434 Die->addSiblingOffset(DIEValueAllocator);
1436 // Record the abbreviation.
1437 assignAbbrevNumber(Die->getAbbrev());
1439 // Get the abbreviation for this DIE.
1440 unsigned AbbrevNumber = Die->getAbbrevNumber();
1441 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1444 Die->setOffset(Offset);
1446 // Start the size with the size of abbreviation code.
1447 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1449 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1450 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1452 // Size the DIE attribute values.
1453 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1454 // Size attribute value.
1455 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1457 // Size the DIE children if any.
1458 if (!Children.empty()) {
1459 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1460 "Children flag not set");
1462 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1463 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
1465 // End of children marker.
1466 Offset += sizeof(int8_t);
1469 Die->setSize(Offset - Die->getOffset());
1473 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
1475 void DwarfDebug::computeSizeAndOffsets() {
1476 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1477 E = CUMap.end(); I != E; ++I) {
1478 // Compute size of compile unit header.
1480 sizeof(int32_t) + // Length of Compilation Unit Info
1481 sizeof(int16_t) + // DWARF version number
1482 sizeof(int32_t) + // Offset Into Abbrev. Section
1483 sizeof(int8_t); // Pointer Size (in bytes)
1484 computeSizeAndOffset(I->second->getCUDie(), Offset, true);
1488 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
1489 /// temporary label to it if SymbolStem is specified.
1490 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
1491 const char *SymbolStem = 0) {
1492 Asm->OutStreamer.SwitchSection(Section);
1493 if (!SymbolStem) return 0;
1495 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
1496 Asm->OutStreamer.EmitLabel(TmpSym);
1500 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
1501 /// the start of each one.
1502 void DwarfDebug::EmitSectionLabels() {
1503 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1505 // Dwarf sections base addresses.
1506 DwarfInfoSectionSym =
1507 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1508 DwarfAbbrevSectionSym =
1509 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1510 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
1512 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1513 EmitSectionSym(Asm, MacroInfo);
1515 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1516 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
1517 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1518 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1519 DwarfStrSectionSym =
1520 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
1521 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1524 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
1525 "section_debug_loc");
1527 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1528 EmitSectionSym(Asm, TLOF.getDataSection());
1531 /// emitDIE - Recursively emits a debug information entry.
1533 void DwarfDebug::emitDIE(DIE *Die) {
1534 // Get the abbreviation for this DIE.
1535 unsigned AbbrevNumber = Die->getAbbrevNumber();
1536 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1538 // Emit the code (index) for the abbreviation.
1539 if (Asm->isVerbose())
1540 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1541 Twine::utohexstr(Die->getOffset()) + ":0x" +
1542 Twine::utohexstr(Die->getSize()) + " " +
1543 dwarf::TagString(Abbrev->getTag()));
1544 Asm->EmitULEB128(AbbrevNumber);
1546 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1547 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1549 // Emit the DIE attribute values.
1550 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1551 unsigned Attr = AbbrevData[i].getAttribute();
1552 unsigned Form = AbbrevData[i].getForm();
1553 assert(Form && "Too many attributes for DIE (check abbreviation)");
1555 if (Asm->isVerbose())
1556 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1559 case dwarf::DW_AT_sibling:
1560 Asm->EmitInt32(Die->getSiblingOffset());
1562 case dwarf::DW_AT_abstract_origin: {
1563 DIEEntry *E = cast<DIEEntry>(Values[i]);
1564 DIE *Origin = E->getEntry();
1565 unsigned Addr = Origin->getOffset();
1566 Asm->EmitInt32(Addr);
1569 case dwarf::DW_AT_ranges: {
1570 // DW_AT_range Value encodes offset in debug_range section.
1571 DIEInteger *V = cast<DIEInteger>(Values[i]);
1573 if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
1574 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1578 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1580 DwarfDebugRangeSectionSym,
1585 case dwarf::DW_AT_location: {
1586 if (DIELabel *L = dyn_cast<DIELabel>(Values[i]))
1587 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1589 Values[i]->EmitValue(Asm, Form);
1592 case dwarf::DW_AT_accessibility: {
1593 if (Asm->isVerbose()) {
1594 DIEInteger *V = cast<DIEInteger>(Values[i]);
1595 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1597 Values[i]->EmitValue(Asm, Form);
1601 // Emit an attribute using the defined form.
1602 Values[i]->EmitValue(Asm, Form);
1607 // Emit the DIE children if any.
1608 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1609 const std::vector<DIE *> &Children = Die->getChildren();
1611 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1612 emitDIE(Children[j]);
1614 if (Asm->isVerbose())
1615 Asm->OutStreamer.AddComment("End Of Children Mark");
1620 /// emitDebugInfo - Emit the debug info section.
1622 void DwarfDebug::emitDebugInfo() {
1623 // Start debug info section.
1624 Asm->OutStreamer.SwitchSection(
1625 Asm->getObjFileLowering().getDwarfInfoSection());
1626 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1627 E = CUMap.end(); I != E; ++I) {
1628 CompileUnit *TheCU = I->second;
1629 DIE *Die = TheCU->getCUDie();
1631 // Emit the compile units header.
1632 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
1635 // Emit size of content not including length itself
1636 unsigned ContentSize = Die->getSize() +
1637 sizeof(int16_t) + // DWARF version number
1638 sizeof(int32_t) + // Offset Into Abbrev. Section
1639 sizeof(int8_t); // Pointer Size (in bytes)
1641 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1642 Asm->EmitInt32(ContentSize);
1643 Asm->OutStreamer.AddComment("DWARF version number");
1644 Asm->EmitInt16(dwarf::DWARF_VERSION);
1645 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1646 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
1647 DwarfAbbrevSectionSym);
1648 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1649 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1652 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
1656 /// emitAbbreviations - Emit the abbreviation section.
1658 void DwarfDebug::emitAbbreviations() const {
1659 // Check to see if it is worth the effort.
1660 if (!Abbreviations.empty()) {
1661 // Start the debug abbrev section.
1662 Asm->OutStreamer.SwitchSection(
1663 Asm->getObjFileLowering().getDwarfAbbrevSection());
1665 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
1667 // For each abbrevation.
1668 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1669 // Get abbreviation data
1670 const DIEAbbrev *Abbrev = Abbreviations[i];
1672 // Emit the abbrevations code (base 1 index.)
1673 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1675 // Emit the abbreviations data.
1679 // Mark end of abbreviations.
1680 Asm->EmitULEB128(0, "EOM(3)");
1682 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
1686 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
1687 /// the line matrix.
1689 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1690 // Define last address of section.
1691 Asm->OutStreamer.AddComment("Extended Op");
1694 Asm->OutStreamer.AddComment("Op size");
1695 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
1696 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1697 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1699 Asm->OutStreamer.AddComment("Section end label");
1701 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1702 Asm->getTargetData().getPointerSize(),
1705 // Mark end of matrix.
1706 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1712 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1714 void DwarfDebug::emitDebugPubNames() {
1715 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1716 E = CUMap.end(); I != E; ++I) {
1717 CompileUnit *TheCU = I->second;
1718 // Start the dwarf pubnames section.
1719 Asm->OutStreamer.SwitchSection(
1720 Asm->getObjFileLowering().getDwarfPubNamesSection());
1722 Asm->OutStreamer.AddComment("Length of Public Names Info");
1723 Asm->EmitLabelDifference(
1724 Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
1725 Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
1727 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
1730 Asm->OutStreamer.AddComment("DWARF Version");
1731 Asm->EmitInt16(dwarf::DWARF_VERSION);
1733 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1734 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1735 DwarfInfoSectionSym);
1737 Asm->OutStreamer.AddComment("Compilation Unit Length");
1738 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1739 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1742 const StringMap<DIE*> &Globals = TheCU->getGlobals();
1743 for (StringMap<DIE*>::const_iterator
1744 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1745 const char *Name = GI->getKeyData();
1746 DIE *Entity = GI->second;
1748 Asm->OutStreamer.AddComment("DIE offset");
1749 Asm->EmitInt32(Entity->getOffset());
1751 if (Asm->isVerbose())
1752 Asm->OutStreamer.AddComment("External Name");
1753 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
1756 Asm->OutStreamer.AddComment("End Mark");
1758 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
1763 void DwarfDebug::emitDebugPubTypes() {
1764 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1765 E = CUMap.end(); I != E; ++I) {
1766 CompileUnit *TheCU = I->second;
1767 // Start the dwarf pubnames section.
1768 Asm->OutStreamer.SwitchSection(
1769 Asm->getObjFileLowering().getDwarfPubTypesSection());
1770 Asm->OutStreamer.AddComment("Length of Public Types Info");
1771 Asm->EmitLabelDifference(
1772 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
1773 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
1775 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
1778 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
1779 Asm->EmitInt16(dwarf::DWARF_VERSION);
1781 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1782 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1783 DwarfInfoSectionSym);
1785 Asm->OutStreamer.AddComment("Compilation Unit Length");
1786 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1787 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1790 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
1791 for (StringMap<DIE*>::const_iterator
1792 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1793 const char *Name = GI->getKeyData();
1794 DIE *Entity = GI->second;
1796 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
1797 Asm->EmitInt32(Entity->getOffset());
1799 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
1800 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
1803 Asm->OutStreamer.AddComment("End Mark");
1805 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
1810 /// emitDebugStr - Emit visible names into a debug str section.
1812 void DwarfDebug::emitDebugStr() {
1813 // Check to see if it is worth the effort.
1814 if (StringPool.empty()) return;
1816 // Start the dwarf str section.
1817 Asm->OutStreamer.SwitchSection(
1818 Asm->getObjFileLowering().getDwarfStrSection());
1820 // Get all of the string pool entries and put them in an array by their ID so
1821 // we can sort them.
1822 SmallVector<std::pair<unsigned,
1823 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
1825 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
1826 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
1827 Entries.push_back(std::make_pair(I->second.second, &*I));
1829 array_pod_sort(Entries.begin(), Entries.end());
1831 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
1832 // Emit a label for reference from debug information entries.
1833 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
1835 // Emit the string itself.
1836 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
1840 /// emitDebugLoc - Emit visible names into a debug loc section.
1842 void DwarfDebug::emitDebugLoc() {
1843 if (DotDebugLocEntries.empty())
1846 for (SmallVector<DotDebugLocEntry, 4>::iterator
1847 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1849 DotDebugLocEntry &Entry = *I;
1850 if (I + 1 != DotDebugLocEntries.end())
1854 // Start the dwarf loc section.
1855 Asm->OutStreamer.SwitchSection(
1856 Asm->getObjFileLowering().getDwarfLocSection());
1857 unsigned char Size = Asm->getTargetData().getPointerSize();
1858 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
1860 for (SmallVector<DotDebugLocEntry, 4>::iterator
1861 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1862 I != E; ++I, ++index) {
1863 DotDebugLocEntry &Entry = *I;
1864 if (Entry.isMerged()) continue;
1865 if (Entry.isEmpty()) {
1866 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1867 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1868 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
1870 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
1871 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
1872 DIVariable DV(Entry.Variable);
1873 Asm->OutStreamer.AddComment("Loc expr size");
1874 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1875 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1876 Asm->EmitLabelDifference(end, begin, 2);
1877 Asm->OutStreamer.EmitLabel(begin);
1878 if (Entry.isInt()) {
1879 DIBasicType BTy(DV.getType());
1881 (BTy.getEncoding() == dwarf::DW_ATE_signed
1882 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
1883 Asm->OutStreamer.AddComment("DW_OP_consts");
1884 Asm->EmitInt8(dwarf::DW_OP_consts);
1885 Asm->EmitSLEB128(Entry.getInt());
1887 Asm->OutStreamer.AddComment("DW_OP_constu");
1888 Asm->EmitInt8(dwarf::DW_OP_constu);
1889 Asm->EmitULEB128(Entry.getInt());
1891 } else if (Entry.isLocation()) {
1892 if (!DV.hasComplexAddress())
1894 Asm->EmitDwarfRegOp(Entry.Loc);
1896 // Complex address entry.
1897 unsigned N = DV.getNumAddrElements();
1899 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
1900 if (Entry.Loc.getOffset()) {
1902 Asm->EmitDwarfRegOp(Entry.Loc);
1903 Asm->OutStreamer.AddComment("DW_OP_deref");
1904 Asm->EmitInt8(dwarf::DW_OP_deref);
1905 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
1906 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
1907 Asm->EmitSLEB128(DV.getAddrElement(1));
1909 // If first address element is OpPlus then emit
1910 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
1911 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
1912 Asm->EmitDwarfRegOp(Loc);
1916 Asm->EmitDwarfRegOp(Entry.Loc);
1919 // Emit remaining complex address elements.
1920 for (; i < N; ++i) {
1921 uint64_t Element = DV.getAddrElement(i);
1922 if (Element == DIBuilder::OpPlus) {
1923 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
1924 Asm->EmitULEB128(DV.getAddrElement(++i));
1925 } else if (Element == DIBuilder::OpDeref)
1926 Asm->EmitInt8(dwarf::DW_OP_deref);
1927 else llvm_unreachable("unknown Opcode found in complex address");
1931 // else ... ignore constant fp. There is not any good way to
1932 // to represent them here in dwarf.
1933 Asm->OutStreamer.EmitLabel(end);
1938 /// EmitDebugARanges - Emit visible names into a debug aranges section.
1940 void DwarfDebug::EmitDebugARanges() {
1941 // Start the dwarf aranges section.
1942 Asm->OutStreamer.SwitchSection(
1943 Asm->getObjFileLowering().getDwarfARangesSection());
1946 /// emitDebugRanges - Emit visible names into a debug ranges section.
1948 void DwarfDebug::emitDebugRanges() {
1949 // Start the dwarf ranges section.
1950 Asm->OutStreamer.SwitchSection(
1951 Asm->getObjFileLowering().getDwarfRangesSection());
1952 unsigned char Size = Asm->getTargetData().getPointerSize();
1953 for (SmallVector<const MCSymbol *, 8>::iterator
1954 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
1957 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
1959 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1963 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
1965 void DwarfDebug::emitDebugMacInfo() {
1966 if (const MCSection *LineInfo =
1967 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
1968 // Start the dwarf macinfo section.
1969 Asm->OutStreamer.SwitchSection(LineInfo);
1973 /// emitDebugInlineInfo - Emit inline info using following format.
1975 /// 1. length of section
1976 /// 2. Dwarf version number
1977 /// 3. address size.
1979 /// Entries (one "entry" for each function that was inlined):
1981 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
1982 /// otherwise offset into __debug_str for regular function name.
1983 /// 2. offset into __debug_str section for regular function name.
1984 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
1985 /// instances for the function.
1987 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
1988 /// inlined instance; the die_offset points to the inlined_subroutine die in the
1989 /// __debug_info section, and the low_pc is the starting address for the
1990 /// inlining instance.
1991 void DwarfDebug::emitDebugInlineInfo() {
1992 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
1998 Asm->OutStreamer.SwitchSection(
1999 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2001 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2002 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2003 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2005 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2007 Asm->OutStreamer.AddComment("Dwarf Version");
2008 Asm->EmitInt16(dwarf::DWARF_VERSION);
2009 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2010 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2012 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2013 E = InlinedSPNodes.end(); I != E; ++I) {
2015 const MDNode *Node = *I;
2016 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2017 = InlineInfo.find(Node);
2018 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2019 DISubprogram SP(Node);
2020 StringRef LName = SP.getLinkageName();
2021 StringRef Name = SP.getName();
2023 Asm->OutStreamer.AddComment("MIPS linkage name");
2024 if (LName.empty()) {
2025 Asm->OutStreamer.EmitBytes(Name, 0);
2026 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
2028 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2029 DwarfStrSectionSym);
2031 Asm->OutStreamer.AddComment("Function name");
2032 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2033 Asm->EmitULEB128(Labels.size(), "Inline count");
2035 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2036 LE = Labels.end(); LI != LE; ++LI) {
2037 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2038 Asm->EmitInt32(LI->second->getOffset());
2040 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2041 Asm->OutStreamer.EmitSymbolValue(LI->first,
2042 Asm->getTargetData().getPointerSize(),0);
2046 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));