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 if (DIGlobalVariable(N).getVersion() <= LLVMDebugVersion9)
621 constructGlobalVariableDIE(getCompileUnit(N), N);
624 // Create DIEs for each subprogram.
625 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
626 E = DbgFinder.subprogram_end(); I != E; ++I) {
627 const MDNode *N = *I;
628 constructSubprogramDIE(getCompileUnit(N), N);
634 /// beginModule - Emit all Dwarf sections that should come prior to the
635 /// content. Create global DIEs and emit initial debug info sections.
636 /// This is invoked by the target AsmPrinter.
637 void DwarfDebug::beginModule(Module *M) {
638 if (DisableDebugInfoPrinting)
641 // If module has named metadata anchors then use them, otherwise scan the
642 // module using debug info finder to collect debug info.
643 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
646 NamedMDNode *GV_Nodes = M->getNamedMetadata("llvm.dbg.gv");
647 NamedMDNode *SP_Nodes = M->getNamedMetadata("llvm.dbg.sp");
648 if (!GV_Nodes && !SP_Nodes)
649 // If there are not any global variables or any functions then
650 // there is not any debug info in this module.
653 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i)
654 constructCompileUnit(CU_Nodes->getOperand(i));
657 for (unsigned i = 0, e = GV_Nodes->getNumOperands(); i != e; ++i) {
658 const MDNode *N = GV_Nodes->getOperand(i);
659 constructGlobalVariableDIE(getCompileUnit(N), N);
663 for (unsigned i = 0, e = SP_Nodes->getNumOperands(); i != e; ++i) {
664 const MDNode *N = SP_Nodes->getOperand(i);
665 constructSubprogramDIE(getCompileUnit(N), N);
668 } else if (!collectLegacyDebugInfo(M))
671 collectInfoFromNamedMDNodes(M);
673 // Tell MMI that we have debug info.
674 MMI->setDebugInfoAvailability(true);
676 // Emit initial sections.
679 // Prime section data.
680 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
683 /// endModule - Emit all Dwarf sections that should come after the content.
685 void DwarfDebug::endModule() {
686 if (!FirstCU) return;
687 const Module *M = MMI->getModule();
688 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
689 if (NamedMDNode *AllSPs = M->getNamedMetadata("llvm.dbg.sp")) {
690 for (unsigned SI = 0, SE = AllSPs->getNumOperands(); SI != SE; ++SI) {
691 if (ProcessedSPNodes.count(AllSPs->getOperand(SI)) != 0) continue;
692 DISubprogram SP(AllSPs->getOperand(SI));
693 if (!SP.Verify()) continue;
695 // Collect info for variables that were optimized out.
696 if (!SP.isDefinition()) continue;
697 StringRef FName = SP.getLinkageName();
699 FName = SP.getName();
700 NamedMDNode *NMD = getFnSpecificMDNode(*(MMI->getModule()), FName);
702 unsigned E = NMD->getNumOperands();
704 LexicalScope *Scope = new LexicalScope(NULL, DIDescriptor(SP), NULL,
706 DeadFnScopeMap[SP] = Scope;
707 SmallVector<DbgVariable, 8> Variables;
708 for (unsigned I = 0; I != E; ++I) {
709 DIVariable DV(NMD->getOperand(I));
710 if (!DV.Verify()) continue;
711 Variables.push_back(DbgVariable(DV, NULL));
714 // Construct subprogram DIE and add variables DIEs.
715 CompileUnit *SPCU = getCompileUnit(SP);
716 constructSubprogramDIE(SPCU, SP);
717 DIE *ScopeDIE = SPCU->getDIE(SP);
718 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
719 if (DIE *VariableDIE =
720 SPCU->constructVariableDIE(&Variables[i], Scope->isAbstractScope()))
721 ScopeDIE->addChild(VariableDIE);
726 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
727 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
728 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
730 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
733 // Emit DW_AT_containing_type attribute to connect types with their
734 // vtable holding type.
735 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
736 CUE = CUMap.end(); CUI != CUE; ++CUI) {
737 CompileUnit *TheCU = CUI->second;
738 TheCU->constructContainingTypeDIEs();
741 // Standard sections final addresses.
742 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
743 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
744 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
745 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
747 // End text sections.
748 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
749 Asm->OutStreamer.SwitchSection(SectionMap[i]);
750 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
753 // Compute DIE offsets and sizes.
754 computeSizeAndOffsets();
756 // Emit all the DIEs into a debug info section
759 // Corresponding abbreviations into a abbrev section.
762 // Emit info into a debug pubnames section.
765 // Emit info into a debug pubtypes section.
768 // Emit info into a debug loc section.
771 // Emit info into a debug aranges section.
774 // Emit info into a debug ranges section.
777 // Emit info into a debug macinfo section.
781 emitDebugInlineInfo();
783 // Emit info into a debug str section.
787 DeleteContainerSeconds(DeadFnScopeMap);
788 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
789 E = CUMap.end(); I != E; ++I)
791 FirstCU = NULL; // Reset for the next Module, if any.
794 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
795 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
797 LLVMContext &Ctx = DV->getContext();
798 // More then one inlined variable corresponds to one abstract variable.
799 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
800 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
802 return AbsDbgVariable;
804 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
808 AbsDbgVariable = new DbgVariable(Var, NULL);
809 addScopeVariable(Scope, AbsDbgVariable);
810 AbstractVariables[Var] = AbsDbgVariable;
811 return AbsDbgVariable;
814 /// addCurrentFnArgument - If Var is a current function argument then add
815 /// it to CurrentFnArguments list.
816 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
817 DbgVariable *Var, LexicalScope *Scope) {
818 if (!LScopes.isCurrentFunctionScope(Scope))
820 DIVariable DV = Var->getVariable();
821 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
823 unsigned ArgNo = DV.getArgNumber();
827 size_t Size = CurrentFnArguments.size();
829 CurrentFnArguments.resize(MF->getFunction()->arg_size());
830 // llvm::Function argument size is not good indicator of how many
831 // arguments does the function have at source level.
833 CurrentFnArguments.resize(ArgNo * 2);
834 CurrentFnArguments[ArgNo - 1] = Var;
838 /// collectVariableInfoFromMMITable - Collect variable information from
839 /// side table maintained by MMI.
841 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
842 SmallPtrSet<const MDNode *, 16> &Processed) {
843 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
844 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
845 VE = VMap.end(); VI != VE; ++VI) {
846 const MDNode *Var = VI->first;
848 Processed.insert(Var);
850 const std::pair<unsigned, DebugLoc> &VP = VI->second;
852 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
854 // If variable scope is not found then skip this variable.
858 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
859 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
860 RegVar->setFrameIndex(VP.first);
861 if (!addCurrentFnArgument(MF, RegVar, Scope))
862 addScopeVariable(Scope, RegVar);
864 AbsDbgVariable->setFrameIndex(VP.first);
868 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
869 /// DBG_VALUE instruction, is in a defined reg.
870 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
871 assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
872 return MI->getNumOperands() == 3 &&
873 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
874 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
877 /// getDebugLocEntry - Get .debug_loc entry for the instruction range starting
879 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
880 const MCSymbol *FLabel,
881 const MCSymbol *SLabel,
882 const MachineInstr *MI) {
883 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
885 if (MI->getNumOperands() != 3) {
886 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
887 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
889 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
890 MachineLocation MLoc;
891 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
892 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
894 if (MI->getOperand(0).isImm())
895 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
896 if (MI->getOperand(0).isFPImm())
897 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
898 if (MI->getOperand(0).isCImm())
899 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
901 assert (0 && "Unexpected 3 operand DBG_VALUE instruction!");
902 return DotDebugLocEntry();
905 /// collectVariableInfo - Find variables for each lexical scope.
907 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
908 SmallPtrSet<const MDNode *, 16> &Processed) {
910 /// collection info from MMI table.
911 collectVariableInfoFromMMITable(MF, Processed);
913 for (SmallVectorImpl<const MDNode*>::const_iterator
914 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
916 const MDNode *Var = *UVI;
917 if (Processed.count(Var))
920 // History contains relevant DBG_VALUE instructions for Var and instructions
922 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
925 const MachineInstr *MInsn = History.front();
928 LexicalScope *Scope = NULL;
929 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
930 DISubprogram(DV.getContext()).describes(MF->getFunction()))
931 Scope = LScopes.getCurrentFunctionScope();
933 if (DV.getVersion() <= LLVMDebugVersion9)
934 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
936 if (MDNode *IA = DV.getInlinedAt())
937 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
939 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
942 // If variable scope is not found then skip this variable.
946 Processed.insert(DV);
947 assert(MInsn->isDebugValue() && "History must begin with debug value");
948 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
949 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
950 if (!addCurrentFnArgument(MF, RegVar, Scope))
951 addScopeVariable(Scope, RegVar);
953 AbsVar->setMInsn(MInsn);
955 // Simple ranges that are fully coalesced.
956 if (History.size() <= 1 || (History.size() == 2 &&
957 MInsn->isIdenticalTo(History.back()))) {
958 RegVar->setMInsn(MInsn);
962 // handle multiple DBG_VALUE instructions describing one variable.
963 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
965 for (SmallVectorImpl<const MachineInstr*>::const_iterator
966 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
967 const MachineInstr *Begin = *HI;
968 assert(Begin->isDebugValue() && "Invalid History entry");
970 // Check if DBG_VALUE is truncating a range.
971 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
972 && !Begin->getOperand(0).getReg())
975 // Compute the range for a register location.
976 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
977 const MCSymbol *SLabel = 0;
980 // If Begin is the last instruction in History then its value is valid
981 // until the end of the function.
982 SLabel = FunctionEndSym;
984 const MachineInstr *End = HI[1];
985 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
986 << "\t" << *Begin << "\t" << *End << "\n");
987 if (End->isDebugValue())
988 SLabel = getLabelBeforeInsn(End);
990 // End is a normal instruction clobbering the range.
991 SLabel = getLabelAfterInsn(End);
992 assert(SLabel && "Forgot label after clobber instruction");
997 // The value is valid until the next DBG_VALUE or clobber.
998 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1000 DotDebugLocEntries.push_back(DotDebugLocEntry());
1003 // Collect info for variables that were optimized out.
1004 const Function *F = MF->getFunction();
1005 if (NamedMDNode *NMD = getFnSpecificMDNode(*(F->getParent()), F->getName())) {
1006 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1007 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
1008 if (!DV || !Processed.insert(DV))
1010 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1011 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1016 /// getLabelBeforeInsn - Return Label preceding the instruction.
1017 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1018 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1019 assert(Label && "Didn't insert label before instruction");
1023 /// getLabelAfterInsn - Return Label immediately following the instruction.
1024 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1025 return LabelsAfterInsn.lookup(MI);
1028 /// beginInstruction - Process beginning of an instruction.
1029 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1030 // Check if source location changes, but ignore DBG_VALUE locations.
1031 if (!MI->isDebugValue()) {
1032 DebugLoc DL = MI->getDebugLoc();
1033 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1034 unsigned Flags = DWARF2_FLAG_IS_STMT;
1036 if (DL == PrologEndLoc) {
1037 Flags |= DWARF2_FLAG_PROLOGUE_END;
1038 PrologEndLoc = DebugLoc();
1040 if (!DL.isUnknown()) {
1041 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1042 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1044 recordSourceLine(0, 0, 0, 0);
1048 // Insert labels where requested.
1049 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1050 LabelsBeforeInsn.find(MI);
1053 if (I == LabelsBeforeInsn.end())
1056 // Label already assigned.
1061 PrevLabel = MMI->getContext().CreateTempSymbol();
1062 Asm->OutStreamer.EmitLabel(PrevLabel);
1064 I->second = PrevLabel;
1067 /// endInstruction - Process end of an instruction.
1068 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1069 // Don't create a new label after DBG_VALUE instructions.
1070 // They don't generate code.
1071 if (!MI->isDebugValue())
1074 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1075 LabelsAfterInsn.find(MI);
1078 if (I == LabelsAfterInsn.end())
1081 // Label already assigned.
1085 // We need a label after this instruction.
1087 PrevLabel = MMI->getContext().CreateTempSymbol();
1088 Asm->OutStreamer.EmitLabel(PrevLabel);
1090 I->second = PrevLabel;
1093 /// identifyScopeMarkers() -
1094 /// Each LexicalScope has first instruction and last instruction to mark
1095 /// beginning and end of a scope respectively. Create an inverse map that list
1096 /// scopes starts (and ends) with an instruction. One instruction may start (or
1097 /// end) multiple scopes. Ignore scopes that are not reachable.
1098 void DwarfDebug::identifyScopeMarkers() {
1099 SmallVector<LexicalScope *, 4> WorkList;
1100 WorkList.push_back(LScopes.getCurrentFunctionScope());
1101 while (!WorkList.empty()) {
1102 LexicalScope *S = WorkList.pop_back_val();
1104 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1105 if (!Children.empty())
1106 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1107 SE = Children.end(); SI != SE; ++SI)
1108 WorkList.push_back(*SI);
1110 if (S->isAbstractScope())
1113 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1116 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1117 RE = Ranges.end(); RI != RE; ++RI) {
1118 assert(RI->first && "InsnRange does not have first instruction!");
1119 assert(RI->second && "InsnRange does not have second instruction!");
1120 requestLabelBeforeInsn(RI->first);
1121 requestLabelAfterInsn(RI->second);
1126 /// getScopeNode - Get MDNode for DebugLoc's scope.
1127 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1128 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1129 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1130 return DL.getScope(Ctx);
1133 /// getFnDebugLoc - Walk up the scope chain of given debug loc and find
1134 /// line number info for the function.
1135 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1136 const MDNode *Scope = getScopeNode(DL, Ctx);
1137 DISubprogram SP = getDISubprogram(Scope);
1139 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1143 /// beginFunction - Gather pre-function debug information. Assumes being
1144 /// emitted immediately after the function entry point.
1145 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1146 if (!MMI->hasDebugInfo()) return;
1147 LScopes.initialize(*MF);
1148 if (LScopes.empty()) return;
1149 identifyScopeMarkers();
1151 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1152 Asm->getFunctionNumber());
1153 // Assumes in correct section after the entry point.
1154 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1156 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1158 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1159 /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1160 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1162 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1164 bool AtBlockEntry = true;
1165 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1167 const MachineInstr *MI = II;
1169 if (MI->isDebugValue()) {
1170 assert (MI->getNumOperands() > 1 && "Invalid machine instruction!");
1172 // Keep track of user variables.
1174 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1176 // Variable is in a register, we need to check for clobbers.
1177 if (isDbgValueInDefinedReg(MI))
1178 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1180 // Check the history of this variable.
1181 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1182 if (History.empty()) {
1183 UserVariables.push_back(Var);
1184 // The first mention of a function argument gets the FunctionBeginSym
1185 // label, so arguments are visible when breaking at function entry.
1187 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1188 DISubprogram(getDISubprogram(DV.getContext()))
1189 .describes(MF->getFunction()))
1190 LabelsBeforeInsn[MI] = FunctionBeginSym;
1192 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1193 const MachineInstr *Prev = History.back();
1194 if (Prev->isDebugValue()) {
1195 // Coalesce identical entries at the end of History.
1196 if (History.size() >= 2 &&
1197 Prev->isIdenticalTo(History[History.size() - 2])) {
1198 DEBUG(dbgs() << "Coalesce identical DBG_VALUE entries:\n"
1200 << "\t" << *History[History.size() - 2] << "\n");
1204 // Terminate old register assignments that don't reach MI;
1205 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1206 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1207 isDbgValueInDefinedReg(Prev)) {
1208 // Previous register assignment needs to terminate at the end of
1210 MachineBasicBlock::const_iterator LastMI =
1211 PrevMBB->getLastNonDebugInstr();
1212 if (LastMI == PrevMBB->end()) {
1213 // Drop DBG_VALUE for empty range.
1214 DEBUG(dbgs() << "Drop DBG_VALUE for empty range:\n"
1215 << "\t" << *Prev << "\n");
1219 // Terminate after LastMI.
1220 History.push_back(LastMI);
1225 History.push_back(MI);
1227 // Not a DBG_VALUE instruction.
1229 AtBlockEntry = false;
1231 // First known non DBG_VALUE location marks beginning of function
1233 if (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown())
1234 PrologEndLoc = MI->getDebugLoc();
1236 // Check if the instruction clobbers any registers with debug vars.
1237 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1238 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1239 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1241 for (const unsigned *AI = TRI->getOverlaps(MOI->getReg());
1242 unsigned Reg = *AI; ++AI) {
1243 const MDNode *Var = LiveUserVar[Reg];
1246 // Reg is now clobbered.
1247 LiveUserVar[Reg] = 0;
1249 // Was MD last defined by a DBG_VALUE referring to Reg?
1250 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1251 if (HistI == DbgValues.end())
1253 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1254 if (History.empty())
1256 const MachineInstr *Prev = History.back();
1257 // Sanity-check: Register assignments are terminated at the end of
1259 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1261 // Is the variable still in Reg?
1262 if (!isDbgValueInDefinedReg(Prev) ||
1263 Prev->getOperand(0).getReg() != Reg)
1265 // Var is clobbered. Make sure the next instruction gets a label.
1266 History.push_back(MI);
1273 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1275 SmallVectorImpl<const MachineInstr*> &History = I->second;
1276 if (History.empty())
1279 // Make sure the final register assignments are terminated.
1280 const MachineInstr *Prev = History.back();
1281 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1282 const MachineBasicBlock *PrevMBB = Prev->getParent();
1283 MachineBasicBlock::const_iterator LastMI =
1284 PrevMBB->getLastNonDebugInstr();
1285 if (LastMI == PrevMBB->end())
1286 // Drop DBG_VALUE for empty range.
1289 // Terminate after LastMI.
1290 History.push_back(LastMI);
1293 // Request labels for the full history.
1294 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1295 const MachineInstr *MI = History[i];
1296 if (MI->isDebugValue())
1297 requestLabelBeforeInsn(MI);
1299 requestLabelAfterInsn(MI);
1303 PrevInstLoc = DebugLoc();
1304 PrevLabel = FunctionBeginSym;
1306 // Record beginning of function.
1307 if (!PrologEndLoc.isUnknown()) {
1308 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1309 MF->getFunction()->getContext());
1310 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1311 FnStartDL.getScope(MF->getFunction()->getContext()),
1312 DWARF2_FLAG_IS_STMT);
1316 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1317 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1318 ScopeVariables[LS].push_back(Var);
1319 // Vars.push_back(Var);
1322 /// endFunction - Gather and emit post-function debug information.
1324 void DwarfDebug::endFunction(const MachineFunction *MF) {
1325 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1327 // Define end label for subprogram.
1328 FunctionEndSym = Asm->GetTempSymbol("func_end",
1329 Asm->getFunctionNumber());
1330 // Assumes in correct section after the entry point.
1331 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1333 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1334 collectVariableInfo(MF, ProcessedVars);
1336 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1337 CompileUnit *TheCU = getCompileUnit(FnScope->getScopeNode());
1339 // Construct abstract scopes.
1340 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1341 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1342 LexicalScope *AScope = AList[i];
1343 DISubprogram SP(AScope->getScopeNode());
1345 // Collect info for variables that were optimized out.
1346 StringRef FName = SP.getLinkageName();
1348 FName = SP.getName();
1349 if (NamedMDNode *NMD =
1350 getFnSpecificMDNode(*(MF->getFunction()->getParent()), FName)) {
1351 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1352 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
1353 if (!DV || !ProcessedVars.insert(DV))
1355 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1356 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1360 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1361 constructScopeDIE(TheCU, AScope);
1364 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1366 if (!DisableFramePointerElim(*MF))
1367 TheCU->addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
1368 dwarf::DW_FORM_flag, 1);
1370 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1371 MMI->getFrameMoves()));
1374 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1375 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1376 DeleteContainerPointers(I->second);
1377 ScopeVariables.clear();
1378 DeleteContainerPointers(CurrentFnArguments);
1379 UserVariables.clear();
1381 AbstractVariables.clear();
1382 LabelsBeforeInsn.clear();
1383 LabelsAfterInsn.clear();
1387 /// recordSourceLine - Register a source line with debug info. Returns the
1388 /// unique label that was emitted and which provides correspondence to
1389 /// the source line list.
1390 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1396 DIDescriptor Scope(S);
1398 if (Scope.isCompileUnit()) {
1399 DICompileUnit CU(S);
1400 Fn = CU.getFilename();
1401 Dir = CU.getDirectory();
1402 } else if (Scope.isFile()) {
1404 Fn = F.getFilename();
1405 Dir = F.getDirectory();
1406 } else if (Scope.isSubprogram()) {
1408 Fn = SP.getFilename();
1409 Dir = SP.getDirectory();
1410 } else if (Scope.isLexicalBlock()) {
1411 DILexicalBlock DB(S);
1412 Fn = DB.getFilename();
1413 Dir = DB.getDirectory();
1415 assert(0 && "Unexpected scope info");
1417 Src = GetOrCreateSourceID(Fn, Dir);
1419 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1422 //===----------------------------------------------------------------------===//
1424 //===----------------------------------------------------------------------===//
1426 /// computeSizeAndOffset - Compute the size and offset of a DIE.
1429 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
1430 // Get the children.
1431 const std::vector<DIE *> &Children = Die->getChildren();
1433 // If not last sibling and has children then add sibling offset attribute.
1434 if (!Last && !Children.empty())
1435 Die->addSiblingOffset(DIEValueAllocator);
1437 // Record the abbreviation.
1438 assignAbbrevNumber(Die->getAbbrev());
1440 // Get the abbreviation for this DIE.
1441 unsigned AbbrevNumber = Die->getAbbrevNumber();
1442 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1445 Die->setOffset(Offset);
1447 // Start the size with the size of abbreviation code.
1448 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1450 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1451 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1453 // Size the DIE attribute values.
1454 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1455 // Size attribute value.
1456 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1458 // Size the DIE children if any.
1459 if (!Children.empty()) {
1460 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1461 "Children flag not set");
1463 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1464 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
1466 // End of children marker.
1467 Offset += sizeof(int8_t);
1470 Die->setSize(Offset - Die->getOffset());
1474 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
1476 void DwarfDebug::computeSizeAndOffsets() {
1477 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1478 E = CUMap.end(); I != E; ++I) {
1479 // Compute size of compile unit header.
1481 sizeof(int32_t) + // Length of Compilation Unit Info
1482 sizeof(int16_t) + // DWARF version number
1483 sizeof(int32_t) + // Offset Into Abbrev. Section
1484 sizeof(int8_t); // Pointer Size (in bytes)
1485 computeSizeAndOffset(I->second->getCUDie(), Offset, true);
1489 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
1490 /// temporary label to it if SymbolStem is specified.
1491 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
1492 const char *SymbolStem = 0) {
1493 Asm->OutStreamer.SwitchSection(Section);
1494 if (!SymbolStem) return 0;
1496 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
1497 Asm->OutStreamer.EmitLabel(TmpSym);
1501 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
1502 /// the start of each one.
1503 void DwarfDebug::EmitSectionLabels() {
1504 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1506 // Dwarf sections base addresses.
1507 DwarfInfoSectionSym =
1508 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1509 DwarfAbbrevSectionSym =
1510 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1511 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
1513 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1514 EmitSectionSym(Asm, MacroInfo);
1516 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1517 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
1518 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1519 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1520 DwarfStrSectionSym =
1521 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
1522 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1525 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
1526 "section_debug_loc");
1528 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1529 EmitSectionSym(Asm, TLOF.getDataSection());
1532 /// emitDIE - Recursively emits a debug information entry.
1534 void DwarfDebug::emitDIE(DIE *Die) {
1535 // Get the abbreviation for this DIE.
1536 unsigned AbbrevNumber = Die->getAbbrevNumber();
1537 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1539 // Emit the code (index) for the abbreviation.
1540 if (Asm->isVerbose())
1541 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1542 Twine::utohexstr(Die->getOffset()) + ":0x" +
1543 Twine::utohexstr(Die->getSize()) + " " +
1544 dwarf::TagString(Abbrev->getTag()));
1545 Asm->EmitULEB128(AbbrevNumber);
1547 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1548 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1550 // Emit the DIE attribute values.
1551 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1552 unsigned Attr = AbbrevData[i].getAttribute();
1553 unsigned Form = AbbrevData[i].getForm();
1554 assert(Form && "Too many attributes for DIE (check abbreviation)");
1556 if (Asm->isVerbose())
1557 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1560 case dwarf::DW_AT_sibling:
1561 Asm->EmitInt32(Die->getSiblingOffset());
1563 case dwarf::DW_AT_abstract_origin: {
1564 DIEEntry *E = cast<DIEEntry>(Values[i]);
1565 DIE *Origin = E->getEntry();
1566 unsigned Addr = Origin->getOffset();
1567 Asm->EmitInt32(Addr);
1570 case dwarf::DW_AT_ranges: {
1571 // DW_AT_range Value encodes offset in debug_range section.
1572 DIEInteger *V = cast<DIEInteger>(Values[i]);
1574 if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
1575 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1579 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1581 DwarfDebugRangeSectionSym,
1586 case dwarf::DW_AT_location: {
1587 if (DIELabel *L = dyn_cast<DIELabel>(Values[i]))
1588 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1590 Values[i]->EmitValue(Asm, Form);
1593 case dwarf::DW_AT_accessibility: {
1594 if (Asm->isVerbose()) {
1595 DIEInteger *V = cast<DIEInteger>(Values[i]);
1596 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1598 Values[i]->EmitValue(Asm, Form);
1602 // Emit an attribute using the defined form.
1603 Values[i]->EmitValue(Asm, Form);
1608 // Emit the DIE children if any.
1609 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1610 const std::vector<DIE *> &Children = Die->getChildren();
1612 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1613 emitDIE(Children[j]);
1615 if (Asm->isVerbose())
1616 Asm->OutStreamer.AddComment("End Of Children Mark");
1621 /// emitDebugInfo - Emit the debug info section.
1623 void DwarfDebug::emitDebugInfo() {
1624 // Start debug info section.
1625 Asm->OutStreamer.SwitchSection(
1626 Asm->getObjFileLowering().getDwarfInfoSection());
1627 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1628 E = CUMap.end(); I != E; ++I) {
1629 CompileUnit *TheCU = I->second;
1630 DIE *Die = TheCU->getCUDie();
1632 // Emit the compile units header.
1633 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
1636 // Emit size of content not including length itself
1637 unsigned ContentSize = Die->getSize() +
1638 sizeof(int16_t) + // DWARF version number
1639 sizeof(int32_t) + // Offset Into Abbrev. Section
1640 sizeof(int8_t); // Pointer Size (in bytes)
1642 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1643 Asm->EmitInt32(ContentSize);
1644 Asm->OutStreamer.AddComment("DWARF version number");
1645 Asm->EmitInt16(dwarf::DWARF_VERSION);
1646 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1647 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
1648 DwarfAbbrevSectionSym);
1649 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1650 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1653 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
1657 /// emitAbbreviations - Emit the abbreviation section.
1659 void DwarfDebug::emitAbbreviations() const {
1660 // Check to see if it is worth the effort.
1661 if (!Abbreviations.empty()) {
1662 // Start the debug abbrev section.
1663 Asm->OutStreamer.SwitchSection(
1664 Asm->getObjFileLowering().getDwarfAbbrevSection());
1666 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
1668 // For each abbrevation.
1669 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1670 // Get abbreviation data
1671 const DIEAbbrev *Abbrev = Abbreviations[i];
1673 // Emit the abbrevations code (base 1 index.)
1674 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1676 // Emit the abbreviations data.
1680 // Mark end of abbreviations.
1681 Asm->EmitULEB128(0, "EOM(3)");
1683 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
1687 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
1688 /// the line matrix.
1690 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1691 // Define last address of section.
1692 Asm->OutStreamer.AddComment("Extended Op");
1695 Asm->OutStreamer.AddComment("Op size");
1696 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
1697 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1698 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1700 Asm->OutStreamer.AddComment("Section end label");
1702 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1703 Asm->getTargetData().getPointerSize(),
1706 // Mark end of matrix.
1707 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1713 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1715 void DwarfDebug::emitDebugPubNames() {
1716 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1717 E = CUMap.end(); I != E; ++I) {
1718 CompileUnit *TheCU = I->second;
1719 // Start the dwarf pubnames section.
1720 Asm->OutStreamer.SwitchSection(
1721 Asm->getObjFileLowering().getDwarfPubNamesSection());
1723 Asm->OutStreamer.AddComment("Length of Public Names Info");
1724 Asm->EmitLabelDifference(
1725 Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
1726 Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
1728 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
1731 Asm->OutStreamer.AddComment("DWARF Version");
1732 Asm->EmitInt16(dwarf::DWARF_VERSION);
1734 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1735 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1736 DwarfInfoSectionSym);
1738 Asm->OutStreamer.AddComment("Compilation Unit Length");
1739 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1740 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1743 const StringMap<DIE*> &Globals = TheCU->getGlobals();
1744 for (StringMap<DIE*>::const_iterator
1745 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1746 const char *Name = GI->getKeyData();
1747 DIE *Entity = GI->second;
1749 Asm->OutStreamer.AddComment("DIE offset");
1750 Asm->EmitInt32(Entity->getOffset());
1752 if (Asm->isVerbose())
1753 Asm->OutStreamer.AddComment("External Name");
1754 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
1757 Asm->OutStreamer.AddComment("End Mark");
1759 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
1764 void DwarfDebug::emitDebugPubTypes() {
1765 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1766 E = CUMap.end(); I != E; ++I) {
1767 CompileUnit *TheCU = I->second;
1768 // Start the dwarf pubnames section.
1769 Asm->OutStreamer.SwitchSection(
1770 Asm->getObjFileLowering().getDwarfPubTypesSection());
1771 Asm->OutStreamer.AddComment("Length of Public Types Info");
1772 Asm->EmitLabelDifference(
1773 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
1774 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
1776 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
1779 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
1780 Asm->EmitInt16(dwarf::DWARF_VERSION);
1782 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1783 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1784 DwarfInfoSectionSym);
1786 Asm->OutStreamer.AddComment("Compilation Unit Length");
1787 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1788 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1791 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
1792 for (StringMap<DIE*>::const_iterator
1793 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1794 const char *Name = GI->getKeyData();
1795 DIE *Entity = GI->second;
1797 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
1798 Asm->EmitInt32(Entity->getOffset());
1800 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
1801 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
1804 Asm->OutStreamer.AddComment("End Mark");
1806 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
1811 /// emitDebugStr - Emit visible names into a debug str section.
1813 void DwarfDebug::emitDebugStr() {
1814 // Check to see if it is worth the effort.
1815 if (StringPool.empty()) return;
1817 // Start the dwarf str section.
1818 Asm->OutStreamer.SwitchSection(
1819 Asm->getObjFileLowering().getDwarfStrSection());
1821 // Get all of the string pool entries and put them in an array by their ID so
1822 // we can sort them.
1823 SmallVector<std::pair<unsigned,
1824 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
1826 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
1827 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
1828 Entries.push_back(std::make_pair(I->second.second, &*I));
1830 array_pod_sort(Entries.begin(), Entries.end());
1832 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
1833 // Emit a label for reference from debug information entries.
1834 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
1836 // Emit the string itself.
1837 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
1841 /// emitDebugLoc - Emit visible names into a debug loc section.
1843 void DwarfDebug::emitDebugLoc() {
1844 if (DotDebugLocEntries.empty())
1847 for (SmallVector<DotDebugLocEntry, 4>::iterator
1848 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1850 DotDebugLocEntry &Entry = *I;
1851 if (I + 1 != DotDebugLocEntries.end())
1855 // Start the dwarf loc section.
1856 Asm->OutStreamer.SwitchSection(
1857 Asm->getObjFileLowering().getDwarfLocSection());
1858 unsigned char Size = Asm->getTargetData().getPointerSize();
1859 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
1861 for (SmallVector<DotDebugLocEntry, 4>::iterator
1862 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1863 I != E; ++I, ++index) {
1864 DotDebugLocEntry &Entry = *I;
1865 if (Entry.isMerged()) continue;
1866 if (Entry.isEmpty()) {
1867 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1868 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1869 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
1871 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
1872 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
1873 DIVariable DV(Entry.Variable);
1874 Asm->OutStreamer.AddComment("Loc expr size");
1875 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1876 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1877 Asm->EmitLabelDifference(end, begin, 2);
1878 Asm->OutStreamer.EmitLabel(begin);
1879 if (Entry.isInt()) {
1880 DIBasicType BTy(DV.getType());
1882 (BTy.getEncoding() == dwarf::DW_ATE_signed
1883 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
1884 Asm->OutStreamer.AddComment("DW_OP_consts");
1885 Asm->EmitInt8(dwarf::DW_OP_consts);
1886 Asm->EmitSLEB128(Entry.getInt());
1888 Asm->OutStreamer.AddComment("DW_OP_constu");
1889 Asm->EmitInt8(dwarf::DW_OP_constu);
1890 Asm->EmitULEB128(Entry.getInt());
1892 } else if (Entry.isLocation()) {
1893 if (!DV.hasComplexAddress())
1895 Asm->EmitDwarfRegOp(Entry.Loc);
1897 // Complex address entry.
1898 unsigned N = DV.getNumAddrElements();
1900 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
1901 if (Entry.Loc.getOffset()) {
1903 Asm->EmitDwarfRegOp(Entry.Loc);
1904 Asm->OutStreamer.AddComment("DW_OP_deref");
1905 Asm->EmitInt8(dwarf::DW_OP_deref);
1906 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
1907 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
1908 Asm->EmitSLEB128(DV.getAddrElement(1));
1910 // If first address element is OpPlus then emit
1911 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
1912 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
1913 Asm->EmitDwarfRegOp(Loc);
1917 Asm->EmitDwarfRegOp(Entry.Loc);
1920 // Emit remaining complex address elements.
1921 for (; i < N; ++i) {
1922 uint64_t Element = DV.getAddrElement(i);
1923 if (Element == DIBuilder::OpPlus) {
1924 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
1925 Asm->EmitULEB128(DV.getAddrElement(++i));
1926 } else if (Element == DIBuilder::OpDeref)
1927 Asm->EmitInt8(dwarf::DW_OP_deref);
1928 else llvm_unreachable("unknown Opcode found in complex address");
1932 // else ... ignore constant fp. There is not any good way to
1933 // to represent them here in dwarf.
1934 Asm->OutStreamer.EmitLabel(end);
1939 /// EmitDebugARanges - Emit visible names into a debug aranges section.
1941 void DwarfDebug::EmitDebugARanges() {
1942 // Start the dwarf aranges section.
1943 Asm->OutStreamer.SwitchSection(
1944 Asm->getObjFileLowering().getDwarfARangesSection());
1947 /// emitDebugRanges - Emit visible names into a debug ranges section.
1949 void DwarfDebug::emitDebugRanges() {
1950 // Start the dwarf ranges section.
1951 Asm->OutStreamer.SwitchSection(
1952 Asm->getObjFileLowering().getDwarfRangesSection());
1953 unsigned char Size = Asm->getTargetData().getPointerSize();
1954 for (SmallVector<const MCSymbol *, 8>::iterator
1955 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
1958 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
1960 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1964 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
1966 void DwarfDebug::emitDebugMacInfo() {
1967 if (const MCSection *LineInfo =
1968 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
1969 // Start the dwarf macinfo section.
1970 Asm->OutStreamer.SwitchSection(LineInfo);
1974 /// emitDebugInlineInfo - Emit inline info using following format.
1976 /// 1. length of section
1977 /// 2. Dwarf version number
1978 /// 3. address size.
1980 /// Entries (one "entry" for each function that was inlined):
1982 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
1983 /// otherwise offset into __debug_str for regular function name.
1984 /// 2. offset into __debug_str section for regular function name.
1985 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
1986 /// instances for the function.
1988 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
1989 /// inlined instance; the die_offset points to the inlined_subroutine die in the
1990 /// __debug_info section, and the low_pc is the starting address for the
1991 /// inlining instance.
1992 void DwarfDebug::emitDebugInlineInfo() {
1993 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
1999 Asm->OutStreamer.SwitchSection(
2000 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2002 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2003 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2004 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2006 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2008 Asm->OutStreamer.AddComment("Dwarf Version");
2009 Asm->EmitInt16(dwarf::DWARF_VERSION);
2010 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2011 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2013 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2014 E = InlinedSPNodes.end(); I != E; ++I) {
2016 const MDNode *Node = *I;
2017 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2018 = InlineInfo.find(Node);
2019 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2020 DISubprogram SP(Node);
2021 StringRef LName = SP.getLinkageName();
2022 StringRef Name = SP.getName();
2024 Asm->OutStreamer.AddComment("MIPS linkage name");
2025 if (LName.empty()) {
2026 Asm->OutStreamer.EmitBytes(Name, 0);
2027 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
2029 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2030 DwarfStrSectionSym);
2032 Asm->OutStreamer.AddComment("Function name");
2033 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2034 Asm->EmitULEB128(Labels.size(), "Inline count");
2036 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2037 LE = Labels.end(); LI != LE; ++LI) {
2038 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2039 Asm->EmitInt32(LI->second->getOffset());
2041 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2042 Asm->OutStreamer.EmitSymbolValue(LI->first,
2043 Asm->getTargetData().getPointerSize(),0);
2047 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));