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/Mangler.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetFrameLowering.h"
30 #include "llvm/Target/TargetLoweringObjectFile.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Target/TargetOptions.h"
34 #include "llvm/Analysis/DebugInfo.h"
35 #include "llvm/Analysis/DIBuilder.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/ValueHandle.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/Timer.h"
45 #include "llvm/Support/Path.h"
48 static cl::opt<bool> PrintDbgScope("print-dbgscope", cl::Hidden,
49 cl::desc("Print DbgScope information for each machine instruction"));
51 static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print",
53 cl::desc("Disable debug info printing"));
55 static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
56 cl::desc("Make an absense of debug location information explicit."),
60 STATISTIC(BlocksWithoutLineNo, "Number of blocks without any line number");
64 const char *DWARFGroupName = "DWARF Emission";
65 const char *DbgTimerName = "DWARF Debug Writer";
66 } // end anonymous namespace
68 //===----------------------------------------------------------------------===//
70 /// Configuration values for initial hash set sizes (log2).
72 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
76 DIType DbgVariable::getType() const {
77 DIType Ty = Var.getType();
78 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
80 if (Var.isBlockByrefVariable()) {
81 /* Byref variables, in Blocks, are declared by the programmer as
82 "SomeType VarName;", but the compiler creates a
83 __Block_byref_x_VarName struct, and gives the variable VarName
84 either the struct, or a pointer to the struct, as its type. This
85 is necessary for various behind-the-scenes things the compiler
86 needs to do with by-reference variables in blocks.
88 However, as far as the original *programmer* is concerned, the
89 variable should still have type 'SomeType', as originally declared.
91 The following function dives into the __Block_byref_x_VarName
92 struct to find the original type of the variable. This will be
93 passed back to the code generating the type for the Debug
94 Information Entry for the variable 'VarName'. 'VarName' will then
95 have the original type 'SomeType' in its debug information.
97 The original type 'SomeType' will be the type of the field named
98 'VarName' inside the __Block_byref_x_VarName struct.
100 NOTE: In order for this to not completely fail on the debugger
101 side, the Debug Information Entry for the variable VarName needs to
102 have a DW_AT_location that tells the debugger how to unwind through
103 the pointers and __Block_byref_x_VarName struct to find the actual
104 value of the variable. The function addBlockByrefType does this. */
106 unsigned tag = Ty.getTag();
108 if (tag == dwarf::DW_TAG_pointer_type) {
109 DIDerivedType DTy = DIDerivedType(Ty);
110 subType = DTy.getTypeDerivedFrom();
113 DICompositeType blockStruct = DICompositeType(subType);
114 DIArray Elements = blockStruct.getTypeArray();
116 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
117 DIDescriptor Element = Elements.getElement(i);
118 DIDerivedType DT = DIDerivedType(Element);
119 if (getName() == DT.getName())
120 return (DT.getTypeDerivedFrom());
127 //===----------------------------------------------------------------------===//
128 /// DbgRange - This is used to track range of instructions with identical
129 /// debug info scope.
131 typedef std::pair<const MachineInstr *, const MachineInstr *> DbgRange;
133 //===----------------------------------------------------------------------===//
134 /// DbgScope - This class is used to track scope information.
137 DbgScope *Parent; // Parent to this scope.
138 DIDescriptor Desc; // Debug info descriptor for scope.
139 // Location at which this scope is inlined.
140 AssertingVH<const MDNode> InlinedAtLocation;
141 bool AbstractScope; // Abstract Scope
142 const MachineInstr *LastInsn; // Last instruction of this scope.
143 const MachineInstr *FirstInsn; // First instruction of this scope.
144 unsigned DFSIn, DFSOut;
145 // Scopes defined in scope. Contents not owned.
146 SmallVector<DbgScope *, 4> Scopes;
147 // Variables declared in scope. Contents owned.
148 SmallVector<DbgVariable *, 8> Variables;
149 SmallVector<DbgRange, 4> Ranges;
150 // Private state for dump()
151 mutable unsigned IndentLevel;
153 DbgScope(DbgScope *P, DIDescriptor D, const MDNode *I = 0)
154 : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(false),
155 LastInsn(0), FirstInsn(0),
156 DFSIn(0), DFSOut(0), IndentLevel(0) {}
160 DbgScope *getParent() const { return Parent; }
161 void setParent(DbgScope *P) { Parent = P; }
162 DIDescriptor getDesc() const { return Desc; }
163 const MDNode *getInlinedAt() const { return InlinedAtLocation; }
164 const MDNode *getScopeNode() const { return Desc; }
165 const SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
166 const SmallVector<DbgVariable *, 8> &getDbgVariables() { return Variables; }
167 const SmallVector<DbgRange, 4> &getRanges() { return Ranges; }
169 /// openInsnRange - This scope covers instruction range starting from MI.
170 void openInsnRange(const MachineInstr *MI) {
175 Parent->openInsnRange(MI);
178 /// extendInsnRange - Extend the current instruction range covered by
180 void extendInsnRange(const MachineInstr *MI) {
181 assert (FirstInsn && "MI Range is not open!");
184 Parent->extendInsnRange(MI);
187 /// closeInsnRange - Create a range based on FirstInsn and LastInsn collected
188 /// until now. This is used when a new scope is encountered while walking
189 /// machine instructions.
190 void closeInsnRange(DbgScope *NewScope = NULL) {
191 assert (LastInsn && "Last insn missing!");
192 Ranges.push_back(DbgRange(FirstInsn, LastInsn));
195 // If Parent dominates NewScope then do not close Parent's instruction
197 if (Parent && (!NewScope || !Parent->dominates(NewScope)))
198 Parent->closeInsnRange(NewScope);
201 void setAbstractScope() { AbstractScope = true; }
202 bool isAbstractScope() const { return AbstractScope; }
204 // Depth First Search support to walk and mainpluate DbgScope hierarchy.
205 unsigned getDFSOut() const { return DFSOut; }
206 void setDFSOut(unsigned O) { DFSOut = O; }
207 unsigned getDFSIn() const { return DFSIn; }
208 void setDFSIn(unsigned I) { DFSIn = I; }
209 bool dominates(const DbgScope *S) {
212 if (DFSIn < S->getDFSIn() && DFSOut > S->getDFSOut())
217 /// addScope - Add a scope to the scope.
219 void addScope(DbgScope *S) { Scopes.push_back(S); }
221 /// addVariable - Add a variable to the scope.
223 void addVariable(DbgVariable *V) { Variables.push_back(V); }
230 } // end llvm namespace
233 void DbgScope::dump() const {
234 raw_ostream &err = dbgs();
235 err.indent(IndentLevel);
236 const MDNode *N = Desc;
239 err << "Abstract Scope\n";
243 err << "Children ...\n";
244 for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
245 if (Scopes[i] != this)
252 DbgScope::~DbgScope() {
253 for (unsigned j = 0, M = Variables.size(); j < M; ++j)
257 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
258 : Asm(A), MMI(Asm->MMI), FirstCU(0),
259 AbbreviationsSet(InitAbbreviationsSetSize),
260 CurrentFnDbgScope(0), PrevLabel(NULL) {
261 NextStringPoolNumber = 0;
263 DwarfFrameSectionSym = DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
264 DwarfStrSectionSym = TextSectionSym = 0;
265 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
266 FunctionBeginSym = FunctionEndSym = 0;
268 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
272 DwarfDebug::~DwarfDebug() {
275 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
276 std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
277 if (Entry.first) return Entry.first;
279 Entry.second = NextStringPoolNumber++;
280 return Entry.first = Asm->GetTempSymbol("string", Entry.second);
284 /// assignAbbrevNumber - Define a unique number for the abbreviation.
286 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
287 // Profile the node so that we can make it unique.
291 // Check the set for priors.
292 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
294 // If it's newly added.
295 if (InSet == &Abbrev) {
296 // Add to abbreviation list.
297 Abbreviations.push_back(&Abbrev);
299 // Assign the vector position + 1 as its number.
300 Abbrev.setNumber(Abbreviations.size());
302 // Assign existing abbreviation number.
303 Abbrev.setNumber(InSet->getNumber());
307 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
308 /// printer to not emit usual symbol prefix before the symbol name is used then
309 /// return linkage name after skipping this special LLVM prefix.
310 static StringRef getRealLinkageName(StringRef LinkageName) {
312 if (LinkageName.startswith(StringRef(&One, 1)))
313 return LinkageName.substr(1);
317 /// createSubprogramDIE - Create new DIE using SP.
318 DIE *DwarfDebug::createSubprogramDIE(DISubprogram SP) {
319 CompileUnit *SPCU = getCompileUnit(SP);
320 DIE *SPDie = SPCU->getDIE(SP);
324 SPDie = new DIE(dwarf::DW_TAG_subprogram);
325 // Constructors and operators for anonymous aggregates do not have names.
326 if (!SP.getName().empty())
327 SPCU->addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
330 StringRef LinkageName = SP.getLinkageName();
331 if (!LinkageName.empty())
332 SPCU->addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
333 getRealLinkageName(LinkageName));
335 SPCU->addSourceLine(SPDie, SP);
337 if (SP.isPrototyped())
338 SPCU->addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
341 DICompositeType SPTy = SP.getType();
342 DIArray Args = SPTy.getTypeArray();
343 unsigned SPTag = SPTy.getTag();
345 if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
346 SPCU->addType(SPDie, SPTy);
348 SPCU->addType(SPDie, DIType(Args.getElement(0)));
350 unsigned VK = SP.getVirtuality();
352 SPCU->addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
353 DIEBlock *Block = SPCU->getDIEBlock();
354 SPCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
355 SPCU->addUInt(Block, 0, dwarf::DW_FORM_udata, SP.getVirtualIndex());
356 SPCU->addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
357 ContainingTypeMap.insert(std::make_pair(SPDie,
358 SP.getContainingType()));
361 if (!SP.isDefinition()) {
362 SPCU->addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
364 // Add arguments. Do not add arguments for subprogram definition. They will
365 // be handled while processing variables.
366 DICompositeType SPTy = SP.getType();
367 DIArray Args = SPTy.getTypeArray();
368 unsigned SPTag = SPTy.getTag();
370 if (SPTag == dwarf::DW_TAG_subroutine_type)
371 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
372 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
373 DIType ATy = DIType(DIType(Args.getElement(i)));
374 SPCU->addType(Arg, ATy);
375 if (ATy.isArtificial())
376 SPCU->addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
377 SPDie->addChild(Arg);
381 if (SP.isArtificial())
382 SPCU->addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
384 if (!SP.isLocalToUnit())
385 SPCU->addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
387 if (SP.isOptimized())
388 SPCU->addUInt(SPDie, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
390 if (unsigned isa = Asm->getISAEncoding()) {
391 SPCU->addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
394 // Add function template parameters.
395 SPCU->addTemplateParams(*SPDie, SP.getTemplateParams());
397 // DW_TAG_inlined_subroutine may refer to this DIE.
398 SPCU->insertDIE(SP, SPDie);
400 // Add to context owner.
401 SPCU->addToContextOwner(SPDie, SP.getContext());
406 DbgScope *DwarfDebug::getOrCreateAbstractScope(const MDNode *N) {
407 assert(N && "Invalid Scope encoding!");
409 DbgScope *AScope = AbstractScopes.lookup(N);
413 DbgScope *Parent = NULL;
415 DIDescriptor Scope(N);
416 if (Scope.isLexicalBlock()) {
417 DILexicalBlock DB(N);
418 DIDescriptor ParentDesc = DB.getContext();
419 Parent = getOrCreateAbstractScope(ParentDesc);
422 AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
425 Parent->addScope(AScope);
426 AScope->setAbstractScope();
427 AbstractScopes[N] = AScope;
428 if (DIDescriptor(N).isSubprogram())
429 AbstractScopesList.push_back(AScope);
433 /// isSubprogramContext - Return true if Context is either a subprogram
434 /// or another context nested inside a subprogram.
435 static bool isSubprogramContext(const MDNode *Context) {
438 DIDescriptor D(Context);
439 if (D.isSubprogram())
442 return isSubprogramContext(DIType(Context).getContext());
446 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
447 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
448 /// If there are global variables in this scope then create and insert
449 /// DIEs for these variables.
450 DIE *DwarfDebug::updateSubprogramScopeDIE(const MDNode *SPNode) {
451 CompileUnit *SPCU = getCompileUnit(SPNode);
452 DIE *SPDie = SPCU->getDIE(SPNode);
454 assert(SPDie && "Unable to find subprogram DIE!");
455 DISubprogram SP(SPNode);
457 // There is not any need to generate specification DIE for a function
458 // defined at compile unit level. If a function is defined inside another
459 // function then gdb prefers the definition at top level and but does not
460 // expect specification DIE in parent function. So avoid creating
461 // specification DIE for a function defined inside a function.
462 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
463 !SP.getContext().isFile() &&
464 !isSubprogramContext(SP.getContext())) {
465 SPCU-> addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
468 DICompositeType SPTy = SP.getType();
469 DIArray Args = SPTy.getTypeArray();
470 unsigned SPTag = SPTy.getTag();
471 if (SPTag == dwarf::DW_TAG_subroutine_type)
472 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
473 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
474 DIType ATy = DIType(DIType(Args.getElement(i)));
475 SPCU->addType(Arg, ATy);
476 if (ATy.isArtificial())
477 SPCU->addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
478 SPDie->addChild(Arg);
480 DIE *SPDeclDie = SPDie;
481 SPDie = new DIE(dwarf::DW_TAG_subprogram);
482 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
487 // Pick up abstract subprogram DIE.
488 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
489 SPDie = new DIE(dwarf::DW_TAG_subprogram);
490 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
491 dwarf::DW_FORM_ref4, AbsSPDIE);
495 SPCU->addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
496 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
497 SPCU->addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
498 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
499 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
500 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
501 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
506 /// constructLexicalScope - Construct new DW_TAG_lexical_block
507 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
508 DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
510 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
511 if (Scope->isAbstractScope())
514 const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
518 CompileUnit *TheCU = getCompileUnit(Scope->getScopeNode());
519 SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
520 if (Ranges.size() > 1) {
521 // .debug_range section has not been laid out yet. Emit offset in
522 // .debug_range as a uint, size 4, for now. emitDIE will handle
523 // DW_AT_ranges appropriately.
524 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
525 DebugRangeSymbols.size() * Asm->getTargetData().getPointerSize());
526 for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
527 RE = Ranges.end(); RI != RE; ++RI) {
528 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
529 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
531 DebugRangeSymbols.push_back(NULL);
532 DebugRangeSymbols.push_back(NULL);
536 const MCSymbol *Start = getLabelBeforeInsn(RI->first);
537 const MCSymbol *End = getLabelAfterInsn(RI->second);
539 if (End == 0) return 0;
541 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
542 assert(End->isDefined() && "Invalid end label for an inlined scope!");
544 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
545 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
550 /// constructInlinedScopeDIE - This scope represents inlined body of
551 /// a function. Construct DIE to represent this concrete inlined copy
553 DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
555 const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
556 assert (Ranges.empty() == false
557 && "DbgScope does not have instruction markers!");
559 // FIXME : .debug_inlined section specification does not clearly state how
560 // to emit inlined scope that is split into multiple instruction ranges.
561 // For now, use first instruction range and emit low_pc/high_pc pair and
562 // corresponding .debug_inlined section entry for this pair.
563 SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
564 const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
565 const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
567 if (StartLabel == 0 || EndLabel == 0) {
568 assert (0 && "Unexpected Start and End labels for a inlined scope!");
571 assert(StartLabel->isDefined() &&
572 "Invalid starting label for an inlined scope!");
573 assert(EndLabel->isDefined() &&
574 "Invalid end label for an inlined scope!");
576 if (!Scope->getScopeNode())
578 DIScope DS(Scope->getScopeNode());
579 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
581 DISubprogram InlinedSP = getDISubprogram(DS);
582 CompileUnit *TheCU = getCompileUnit(InlinedSP);
583 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
584 assert(OriginDIE && "Unable to find Origin DIE!");
585 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
586 dwarf::DW_FORM_ref4, OriginDIE);
588 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, StartLabel);
589 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, EndLabel);
591 InlinedSubprogramDIEs.insert(OriginDIE);
593 // Track the start label for this inlined function.
594 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
595 I = InlineInfo.find(InlinedSP);
597 if (I == InlineInfo.end()) {
598 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel,
600 InlinedSPNodes.push_back(InlinedSP);
602 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
604 DILocation DL(Scope->getInlinedAt());
605 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, TheCU->getID());
606 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
612 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
613 DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
614 StringRef Name = DV->getName();
618 // Translate tag to proper Dwarf tag. The result variable is dropped for
621 switch (DV->getTag()) {
622 case dwarf::DW_TAG_return_variable:
624 case dwarf::DW_TAG_arg_variable:
625 Tag = dwarf::DW_TAG_formal_parameter;
627 case dwarf::DW_TAG_auto_variable: // fall thru
629 Tag = dwarf::DW_TAG_variable;
633 // Define variable debug information entry.
634 DIE *VariableDie = new DIE(Tag);
635 CompileUnit *TheCU = getCompileUnit(DV->getVariable());
637 DenseMap<const DbgVariable *, const DbgVariable *>::iterator
638 V2AVI = VarToAbstractVarMap.find(DV);
639 if (V2AVI != VarToAbstractVarMap.end())
640 AbsDIE = V2AVI->second->getDIE();
643 TheCU->addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
644 dwarf::DW_FORM_ref4, AbsDIE);
646 TheCU->addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
647 TheCU->addSourceLine(VariableDie, DV->getVariable());
649 // Add variable type.
650 TheCU->addType(VariableDie, DV->getType());
653 if (Tag == dwarf::DW_TAG_formal_parameter && DV->getType().isArtificial())
654 TheCU->addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
655 else if (DIVariable(DV->getVariable()).isArtificial())
656 TheCU->addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
658 if (Scope->isAbstractScope()) {
659 DV->setDIE(VariableDie);
663 // Add variable address.
665 unsigned Offset = DV->getDotDebugLocOffset();
667 TheCU->addLabel(VariableDie, dwarf::DW_AT_location, dwarf::DW_FORM_data4,
668 Asm->GetTempSymbol("debug_loc", Offset));
669 DV->setDIE(VariableDie);
670 UseDotDebugLocEntry.insert(VariableDie);
674 // Check if variable is described by a DBG_VALUE instruction.
675 DenseMap<const DbgVariable *, const MachineInstr *>::iterator DVI =
676 DbgVariableToDbgInstMap.find(DV);
677 if (DVI != DbgVariableToDbgInstMap.end()) {
678 const MachineInstr *DVInsn = DVI->second;
679 bool updated = false;
680 // FIXME : Handle getNumOperands != 3
681 if (DVInsn->getNumOperands() == 3) {
682 if (DVInsn->getOperand(0).isReg()) {
683 const MachineOperand RegOp = DVInsn->getOperand(0);
684 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
685 if (DVInsn->getOperand(1).isImm() &&
686 TRI->getFrameRegister(*Asm->MF) == RegOp.getReg()) {
687 TheCU->addVariableAddress(DV, VariableDie, DVInsn->getOperand(1).getImm());
690 updated = TheCU->addRegisterAddress(VariableDie, RegOp);
692 else if (DVInsn->getOperand(0).isImm())
693 updated = TheCU->addConstantValue(VariableDie, DVInsn->getOperand(0));
694 else if (DVInsn->getOperand(0).isFPImm())
696 TheCU->addConstantFPValue(VariableDie, DVInsn->getOperand(0));
698 MachineLocation Location = Asm->getDebugValueLocation(DVInsn);
699 if (Location.getReg()) {
700 TheCU->addAddress(VariableDie, dwarf::DW_AT_location, Location);
705 // If variableDie is not updated then DBG_VALUE instruction does not
706 // have valid variable info.
710 DV->setDIE(VariableDie);
714 // .. else use frame index, if available.
716 if (findVariableFrameIndex(DV, &FI))
717 TheCU->addVariableAddress(DV, VariableDie, FI);
719 DV->setDIE(VariableDie);
724 void CompileUnit::addPubTypes(DISubprogram SP) {
725 DICompositeType SPTy = SP.getType();
726 unsigned SPTag = SPTy.getTag();
727 if (SPTag != dwarf::DW_TAG_subroutine_type)
730 DIArray Args = SPTy.getTypeArray();
731 for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
732 DIType ATy(Args.getElement(i));
735 DICompositeType CATy = getDICompositeType(ATy);
736 if (DIDescriptor(CATy).Verify() && !CATy.getName().empty()
737 && !CATy.isForwardDecl()) {
738 if (DIEEntry *Entry = getDIEEntry(CATy))
739 addGlobalType(CATy.getName(), Entry->getEntry());
744 /// constructScopeDIE - Construct a DIE for this scope.
745 DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
746 if (!Scope || !Scope->getScopeNode())
749 SmallVector <DIE *, 8> Children;
751 // Collect arguments for current function.
752 if (Scope == CurrentFnDbgScope)
753 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
754 if (DbgVariable *ArgDV = CurrentFnArguments[i])
755 if (DIE *Arg = constructVariableDIE(ArgDV, Scope))
756 Children.push_back(Arg);
758 // Collect lexical scope childrens first.
759 const SmallVector<DbgVariable *, 8> &Variables = Scope->getDbgVariables();
760 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
761 if (DIE *Variable = constructVariableDIE(Variables[i], Scope))
762 Children.push_back(Variable);
763 const SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
764 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
765 if (DIE *Nested = constructScopeDIE(Scopes[j]))
766 Children.push_back(Nested);
767 DIScope DS(Scope->getScopeNode());
768 DIE *ScopeDIE = NULL;
769 if (Scope->getInlinedAt())
770 ScopeDIE = constructInlinedScopeDIE(Scope);
771 else if (DS.isSubprogram()) {
772 ProcessedSPNodes.insert(DS);
773 if (Scope->isAbstractScope()) {
774 ScopeDIE = getCompileUnit(DS)->getDIE(DS);
775 // Note down abstract DIE.
777 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
780 ScopeDIE = updateSubprogramScopeDIE(DS);
783 // There is no need to emit empty lexical block DIE.
784 if (Children.empty())
786 ScopeDIE = constructLexicalScopeDIE(Scope);
789 if (!ScopeDIE) return NULL;
792 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
793 E = Children.end(); I != E; ++I)
794 ScopeDIE->addChild(*I);
796 if (DS.isSubprogram())
797 getCompileUnit(DS)->addPubTypes(DISubprogram(DS));
802 /// GetOrCreateSourceID - Look up the source id with the given directory and
803 /// source file names. If none currently exists, create a new id and insert it
804 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
807 unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName,
809 // If FE did not provide a file name, then assume stdin.
810 if (FileName.empty())
811 return GetOrCreateSourceID("<stdin>", StringRef());
813 // MCStream expects full path name as filename.
814 if (!DirName.empty() && !FileName.startswith("/")) {
815 std::string FullPathName(DirName.data());
816 if (!DirName.endswith("/"))
818 FullPathName += FileName.data();
819 // Here FullPathName will be copied into StringMap by GetOrCreateSourceID.
820 return GetOrCreateSourceID(StringRef(FullPathName), StringRef());
823 StringMapEntry<unsigned> &Entry = SourceIdMap.GetOrCreateValue(FileName);
824 if (Entry.getValue())
825 return Entry.getValue();
827 unsigned SrcId = SourceIdMap.size();
828 Entry.setValue(SrcId);
830 // Print out a .file directive to specify files for .loc directives.
831 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, Entry.getKey());
836 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
837 DIE *CompileUnit::getOrCreateNameSpace(DINameSpace NS) {
838 DIE *NDie = getDIE(NS);
841 NDie = new DIE(dwarf::DW_TAG_namespace);
843 if (!NS.getName().empty())
844 addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
845 addSourceLine(NDie, NS);
846 addToContextOwner(NDie, NS.getContext());
850 /// constructCompileUnit - Create new CompileUnit for the given
851 /// metadata node with tag DW_TAG_compile_unit.
852 void DwarfDebug::constructCompileUnit(const MDNode *N) {
853 DICompileUnit DIUnit(N);
854 StringRef FN = DIUnit.getFilename();
855 StringRef Dir = DIUnit.getDirectory();
856 unsigned ID = GetOrCreateSourceID(FN, Dir);
858 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
859 CompileUnit *NewCU = new CompileUnit(ID, Die, Asm, this);
860 NewCU->addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
861 DIUnit.getProducer());
862 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
863 DIUnit.getLanguage());
864 NewCU->addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
865 // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
866 // simplifies debug range entries.
867 NewCU->addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
868 // DW_AT_stmt_list is a offset of line number information for this
869 // compile unit in debug_line section.
870 if (Asm->MAI->doesDwarfUsesAbsoluteLabelForStmtList())
871 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_addr,
872 Asm->GetTempSymbol("section_line"));
874 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
877 NewCU->addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
878 if (DIUnit.isOptimized())
879 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
881 StringRef Flags = DIUnit.getFlags();
883 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
885 unsigned RVer = DIUnit.getRunTimeVersion();
887 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
888 dwarf::DW_FORM_data1, RVer);
892 CUMap.insert(std::make_pair(N, NewCU));
895 /// getCompielUnit - Get CompileUnit DIE.
896 CompileUnit *DwarfDebug::getCompileUnit(const MDNode *N) const {
897 assert (N && "Invalid DwarfDebug::getCompileUnit argument!");
899 const MDNode *CUNode = NULL;
900 if (D.isCompileUnit())
902 else if (D.isSubprogram())
903 CUNode = DISubprogram(N).getCompileUnit();
905 CUNode = DIType(N).getCompileUnit();
906 else if (D.isGlobalVariable())
907 CUNode = DIGlobalVariable(N).getCompileUnit();
908 else if (D.isVariable())
909 CUNode = DIVariable(N).getCompileUnit();
910 else if (D.isNameSpace())
911 CUNode = DINameSpace(N).getCompileUnit();
913 CUNode = DIFile(N).getCompileUnit();
917 DenseMap<const MDNode *, CompileUnit *>::const_iterator I
918 = CUMap.find(CUNode);
919 if (I == CUMap.end())
924 /// isUnsignedDIType - Return true if type encoding is unsigned.
925 static bool isUnsignedDIType(DIType Ty) {
926 DIDerivedType DTy(Ty);
928 return isUnsignedDIType(DTy.getTypeDerivedFrom());
932 unsigned Encoding = BTy.getEncoding();
933 if (Encoding == dwarf::DW_ATE_unsigned ||
934 Encoding == dwarf::DW_ATE_unsigned_char)
940 // Return const exprssion if value is a GEP to access merged global
942 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
943 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
944 const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
945 if (!CE || CE->getNumOperands() != 3 ||
946 CE->getOpcode() != Instruction::GetElementPtr)
949 // First operand points to a global value.
950 if (!isa<GlobalValue>(CE->getOperand(0)))
953 // Second operand is zero.
954 const ConstantInt *CI =
955 dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
956 if (!CI || !CI->isZero())
959 // Third operand is offset.
960 if (!isa<ConstantInt>(CE->getOperand(2)))
966 /// constructGlobalVariableDIE - Construct global variable DIE.
967 void DwarfDebug::constructGlobalVariableDIE(const MDNode *N) {
968 DIGlobalVariable GV(N);
970 // If debug information is malformed then ignore it.
971 if (GV.Verify() == false)
974 // Check for pre-existence.
975 CompileUnit *TheCU = getCompileUnit(N);
976 if (TheCU->getDIE(GV))
979 DIType GTy = GV.getType();
980 DIE *VariableDIE = new DIE(GV.getTag());
982 bool isGlobalVariable = GV.getGlobal() != NULL;
985 TheCU->addString(VariableDIE, dwarf::DW_AT_name, dwarf::DW_FORM_string,
986 GV.getDisplayName());
987 StringRef LinkageName = GV.getLinkageName();
988 if (!LinkageName.empty() && isGlobalVariable)
989 TheCU->addString(VariableDIE, dwarf::DW_AT_MIPS_linkage_name,
990 dwarf::DW_FORM_string,
991 getRealLinkageName(LinkageName));
993 TheCU->addType(VariableDIE, GTy);
994 if (GTy.isCompositeType() && !GTy.getName().empty()
995 && !GTy.isForwardDecl()) {
996 DIEEntry *Entry = TheCU->getDIEEntry(GTy);
997 assert(Entry && "Missing global type!");
998 TheCU->addGlobalType(GTy.getName(), Entry->getEntry());
1000 // Add scoping info.
1001 if (!GV.isLocalToUnit()) {
1002 TheCU->addUInt(VariableDIE, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1003 // Expose as global.
1004 TheCU->addGlobal(GV.getName(), VariableDIE);
1006 // Add line number info.
1007 TheCU->addSourceLine(VariableDIE, GV);
1009 TheCU->insertDIE(N, VariableDIE);
1010 // Add to context owner.
1011 DIDescriptor GVContext = GV.getContext();
1012 TheCU->addToContextOwner(VariableDIE, GVContext);
1014 if (isGlobalVariable) {
1015 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1016 TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1017 TheCU->addLabel(Block, 0, dwarf::DW_FORM_udata,
1018 Asm->Mang->getSymbol(GV.getGlobal()));
1019 // Do not create specification DIE if context is either compile unit
1021 if (GV.isDefinition() && !GVContext.isCompileUnit() &&
1022 !GVContext.isFile() && !isSubprogramContext(GVContext)) {
1023 // Create specification DIE.
1024 DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1025 TheCU->addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1026 dwarf::DW_FORM_ref4, VariableDIE);
1027 TheCU->addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1028 TheCU->addUInt(VariableDIE, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1029 TheCU->addDie(VariableSpecDIE);
1031 TheCU->addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1033 } else if (ConstantInt *CI =
1034 dyn_cast_or_null<ConstantInt>(GV.getConstant()))
1035 TheCU->addConstantValue(VariableDIE, CI, isUnsignedDIType(GTy));
1036 else if (const ConstantExpr *CE = getMergedGlobalExpr(N->getOperand(11))) {
1037 // GV is a merged global.
1038 DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1039 TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1040 TheCU->addLabel(Block, 0, dwarf::DW_FORM_udata,
1041 Asm->Mang->getSymbol(cast<GlobalValue>(CE->getOperand(0))));
1042 ConstantInt *CII = cast<ConstantInt>(CE->getOperand(2));
1043 TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1044 TheCU->addUInt(Block, 0, dwarf::DW_FORM_udata, CII->getZExtValue());
1045 TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1046 TheCU->addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1052 /// construct SubprogramDIE - Construct subprogram DIE.
1053 void DwarfDebug::constructSubprogramDIE(const MDNode *N) {
1056 // Check for pre-existence.
1057 CompileUnit *TheCU = getCompileUnit(N);
1058 if (TheCU->getDIE(N))
1061 if (!SP.isDefinition())
1062 // This is a method declaration which will be handled while constructing
1066 DIE *SubprogramDie = createSubprogramDIE(SP);
1069 TheCU->insertDIE(N, SubprogramDie);
1071 // Add to context owner.
1072 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
1074 // Expose as global.
1075 TheCU->addGlobal(SP.getName(), SubprogramDie);
1080 /// beginModule - Emit all Dwarf sections that should come prior to the
1081 /// content. Create global DIEs and emit initial debug info sections.
1082 /// This is inovked by the target AsmPrinter.
1083 void DwarfDebug::beginModule(Module *M) {
1084 if (DisableDebugInfoPrinting)
1087 DebugInfoFinder DbgFinder;
1088 DbgFinder.processModule(*M);
1090 bool HasDebugInfo = false;
1092 // Scan all the compile-units to see if there are any marked as the main unit.
1093 // if not, we do not generate debug info.
1094 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1095 E = DbgFinder.compile_unit_end(); I != E; ++I) {
1096 if (DICompileUnit(*I).isMain()) {
1097 HasDebugInfo = true;
1102 if (!HasDebugInfo) return;
1104 // Tell MMI that we have debug info.
1105 MMI->setDebugInfoAvailability(true);
1107 // Emit initial sections.
1108 EmitSectionLabels();
1110 // Create all the compile unit DIEs.
1111 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1112 E = DbgFinder.compile_unit_end(); I != E; ++I)
1113 constructCompileUnit(*I);
1115 // Create DIEs for each subprogram.
1116 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1117 E = DbgFinder.subprogram_end(); I != E; ++I)
1118 constructSubprogramDIE(*I);
1120 // Create DIEs for each global variable.
1121 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1122 E = DbgFinder.global_variable_end(); I != E; ++I)
1123 constructGlobalVariableDIE(*I);
1125 //getOrCreateTypeDIE
1126 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
1127 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1128 DIType Ty(NMD->getOperand(i));
1129 getCompileUnit(Ty)->getOrCreateTypeDIE(Ty);
1132 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
1133 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1134 DIType Ty(NMD->getOperand(i));
1135 getCompileUnit(Ty)->getOrCreateTypeDIE(Ty);
1138 // Prime section data.
1139 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1142 /// endModule - Emit all Dwarf sections that should come after the content.
1144 void DwarfDebug::endModule() {
1145 if (!FirstCU) return;
1146 const Module *M = MMI->getModule();
1147 DenseMap<const MDNode *, DbgScope *> DeadFnScopeMap;
1148 if (NamedMDNode *AllSPs = M->getNamedMetadata("llvm.dbg.sp")) {
1149 for (unsigned SI = 0, SE = AllSPs->getNumOperands(); SI != SE; ++SI) {
1150 if (ProcessedSPNodes.count(AllSPs->getOperand(SI)) != 0) continue;
1151 DISubprogram SP(AllSPs->getOperand(SI));
1152 if (!SP.Verify()) continue;
1154 // Collect info for variables that were optimized out.
1155 if (!SP.isDefinition()) continue;
1156 StringRef FName = SP.getLinkageName();
1158 FName = SP.getName();
1159 NamedMDNode *NMD = getFnSpecificMDNode(*(MMI->getModule()), FName);
1161 unsigned E = NMD->getNumOperands();
1163 DbgScope *Scope = new DbgScope(NULL, DIDescriptor(SP), NULL);
1164 DeadFnScopeMap[SP] = Scope;
1165 for (unsigned I = 0; I != E; ++I) {
1166 DIVariable DV(NMD->getOperand(I));
1167 if (!DV.Verify()) continue;
1168 Scope->addVariable(new DbgVariable(DV));
1171 // Construct subprogram DIE and add variables DIEs.
1172 constructSubprogramDIE(SP);
1173 DIE *ScopeDIE = getCompileUnit(SP)->getDIE(SP);
1174 const SmallVector<DbgVariable *, 8> &Variables = Scope->getDbgVariables();
1175 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1176 DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
1178 ScopeDIE->addChild(VariableDIE);
1183 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1184 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
1185 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
1187 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
1190 for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1191 CE = ContainingTypeMap.end(); CI != CE; ++CI) {
1192 DIE *SPDie = CI->first;
1193 const MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
1195 DIE *NDie = getCompileUnit(N)->getDIE(N);
1196 if (!NDie) continue;
1197 getCompileUnit(N)->addDIEEntry(SPDie, dwarf::DW_AT_containing_type,
1198 dwarf::DW_FORM_ref4, NDie);
1201 // Standard sections final addresses.
1202 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1203 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
1204 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1205 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
1207 // End text sections.
1208 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1209 Asm->OutStreamer.SwitchSection(SectionMap[i]);
1210 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
1213 // Emit common frame information.
1214 emitCommonDebugFrame();
1216 // Emit function debug frame information
1217 for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
1218 E = DebugFrames.end(); I != E; ++I)
1219 emitFunctionDebugFrame(*I);
1221 // Compute DIE offsets and sizes.
1222 computeSizeAndOffsets();
1224 // Emit all the DIEs into a debug info section
1227 // Corresponding abbreviations into a abbrev section.
1228 emitAbbreviations();
1230 // Emit info into a debug pubnames section.
1231 emitDebugPubNames();
1233 // Emit info into a debug pubtypes section.
1234 emitDebugPubTypes();
1236 // Emit info into a debug loc section.
1239 // Emit info into a debug aranges section.
1242 // Emit info into a debug ranges section.
1245 // Emit info into a debug macinfo section.
1248 // Emit inline info.
1249 emitDebugInlineInfo();
1251 // Emit info into a debug str section.
1255 DeleteContainerSeconds(DeadFnScopeMap);
1256 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1257 E = CUMap.end(); I != E; ++I)
1259 FirstCU = NULL; // Reset for the next Module, if any.
1262 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
1263 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
1264 DebugLoc ScopeLoc) {
1266 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1268 return AbsDbgVariable;
1270 LLVMContext &Ctx = Var->getContext();
1271 DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
1275 AbsDbgVariable = new DbgVariable(Var);
1276 Scope->addVariable(AbsDbgVariable);
1277 AbstractVariables[Var] = AbsDbgVariable;
1278 return AbsDbgVariable;
1281 /// addCurrentFnArgument - If Var is an current function argument that add
1282 /// it in CurrentFnArguments list.
1283 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1284 DbgVariable *Var, DbgScope *Scope) {
1285 if (Scope != CurrentFnDbgScope)
1287 DIVariable DV = Var->getVariable();
1288 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1290 unsigned ArgNo = DV.getArgNumber();
1294 size_t Size = CurrentFnArguments.size();
1296 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1297 // llvm::Function argument size is not good indicator of how many
1298 // arguments does the function have at source level.
1300 CurrentFnArguments.resize(ArgNo * 2);
1301 CurrentFnArguments[ArgNo - 1] = Var;
1305 /// collectVariableInfoFromMMITable - Collect variable information from
1306 /// side table maintained by MMI.
1308 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction * MF,
1309 SmallPtrSet<const MDNode *, 16> &Processed) {
1310 const LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
1311 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1312 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1313 VE = VMap.end(); VI != VE; ++VI) {
1314 const MDNode *Var = VI->first;
1316 Processed.insert(Var);
1318 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1320 DbgScope *Scope = 0;
1321 if (const MDNode *IA = VP.second.getInlinedAt(Ctx))
1322 Scope = ConcreteScopes.lookup(IA);
1324 Scope = DbgScopeMap.lookup(VP.second.getScope(Ctx));
1326 // If variable scope is not found then skip this variable.
1330 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1331 DbgVariable *RegVar = new DbgVariable(DV);
1332 recordVariableFrameIndex(RegVar, VP.first);
1333 if (!addCurrentFnArgument(MF, RegVar, Scope))
1334 Scope->addVariable(RegVar);
1335 if (AbsDbgVariable) {
1336 recordVariableFrameIndex(AbsDbgVariable, VP.first);
1337 VarToAbstractVarMap[RegVar] = AbsDbgVariable;
1342 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
1343 /// DBG_VALUE instruction, is in a defined reg.
1344 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1345 assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1346 return MI->getNumOperands() == 3 &&
1347 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1348 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
1351 /// collectVariableInfo - Populate DbgScope entries with variables' info.
1353 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1354 SmallPtrSet<const MDNode *, 16> &Processed) {
1356 /// collection info from MMI table.
1357 collectVariableInfoFromMMITable(MF, Processed);
1359 for (SmallVectorImpl<const MDNode*>::const_iterator
1360 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1362 const MDNode *Var = *UVI;
1363 if (Processed.count(Var))
1366 // History contains relevant DBG_VALUE instructions for Var and instructions
1368 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1369 if (History.empty())
1371 const MachineInstr *MInsn = History.front();
1374 DbgScope *Scope = NULL;
1375 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1376 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1377 Scope = CurrentFnDbgScope;
1379 Scope = findDbgScope(MInsn);
1380 // If variable scope is not found then skip this variable.
1384 Processed.insert(DV);
1385 assert(MInsn->isDebugValue() && "History must begin with debug value");
1386 DbgVariable *RegVar = new DbgVariable(DV);
1387 if (!addCurrentFnArgument(MF, RegVar, Scope))
1388 Scope->addVariable(RegVar);
1389 if (DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc())) {
1390 DbgVariableToDbgInstMap[AbsVar] = MInsn;
1391 VarToAbstractVarMap[RegVar] = AbsVar;
1394 // Simple ranges that are fully coalesced.
1395 if (History.size() <= 1 || (History.size() == 2 &&
1396 MInsn->isIdenticalTo(History.back()))) {
1397 DbgVariableToDbgInstMap[RegVar] = MInsn;
1401 // handle multiple DBG_VALUE instructions describing one variable.
1402 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1404 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1405 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1406 const MachineInstr *Begin = *HI;
1407 assert(Begin->isDebugValue() && "Invalid History entry");
1408 MachineLocation MLoc;
1409 if (Begin->getNumOperands() == 3) {
1410 if (Begin->getOperand(0).isReg() && Begin->getOperand(1).isImm())
1411 MLoc.set(Begin->getOperand(0).getReg(), Begin->getOperand(1).getImm());
1413 MLoc = Asm->getDebugValueLocation(Begin);
1415 // FIXME: emitDebugLoc only understands registers.
1419 // Compute the range for a register location.
1420 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1421 const MCSymbol *SLabel = 0;
1424 // If Begin is the last instruction in History then its value is valid
1425 // until the end of the funtion.
1426 SLabel = FunctionEndSym;
1428 const MachineInstr *End = HI[1];
1429 if (End->isDebugValue())
1430 SLabel = getLabelBeforeInsn(End);
1432 // End is a normal instruction clobbering the range.
1433 SLabel = getLabelAfterInsn(End);
1434 assert(SLabel && "Forgot label after clobber instruction");
1439 // The value is valid until the next DBG_VALUE or clobber.
1440 DotDebugLocEntries.push_back(DotDebugLocEntry(FLabel, SLabel, MLoc));
1442 DotDebugLocEntries.push_back(DotDebugLocEntry());
1445 // Collect info for variables that were optimized out.
1446 const Function *F = MF->getFunction();
1447 if (NamedMDNode *NMD = getFnSpecificMDNode(*(F->getParent()), F->getName())) {
1448 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1449 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
1450 if (!DV || !Processed.insert(DV))
1452 DbgScope *Scope = DbgScopeMap.lookup(DV.getContext());
1454 Scope->addVariable(new DbgVariable(DV));
1459 /// getLabelBeforeInsn - Return Label preceding the instruction.
1460 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1461 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1462 assert(Label && "Didn't insert label before instruction");
1466 /// getLabelAfterInsn - Return Label immediately following the instruction.
1467 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1468 return LabelsAfterInsn.lookup(MI);
1471 /// beginInstruction - Process beginning of an instruction.
1472 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1473 // Check if source location changes, but ignore DBG_VALUE locations.
1474 if (!MI->isDebugValue()) {
1475 DebugLoc DL = MI->getDebugLoc();
1476 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1478 if (!DL.isUnknown()) {
1479 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1480 recordSourceLine(DL.getLine(), DL.getCol(), Scope);
1482 recordSourceLine(0, 0, 0);
1486 // Insert labels where requested.
1487 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1488 LabelsBeforeInsn.find(MI);
1491 if (I == LabelsBeforeInsn.end())
1494 // Label already assigned.
1499 PrevLabel = MMI->getContext().CreateTempSymbol();
1500 Asm->OutStreamer.EmitLabel(PrevLabel);
1502 I->second = PrevLabel;
1505 /// endInstruction - Process end of an instruction.
1506 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1507 // Don't create a new label after DBG_VALUE instructions.
1508 // They don't generate code.
1509 if (!MI->isDebugValue())
1512 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1513 LabelsAfterInsn.find(MI);
1516 if (I == LabelsAfterInsn.end())
1519 // Label already assigned.
1523 // We need a label after this instruction.
1525 PrevLabel = MMI->getContext().CreateTempSymbol();
1526 Asm->OutStreamer.EmitLabel(PrevLabel);
1528 I->second = PrevLabel;
1531 /// getOrCreateDbgScope - Create DbgScope for the scope.
1532 DbgScope *DwarfDebug::getOrCreateDbgScope(const MDNode *Scope,
1533 const MDNode *InlinedAt) {
1535 DbgScope *WScope = DbgScopeMap.lookup(Scope);
1538 WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
1539 DbgScopeMap.insert(std::make_pair(Scope, WScope));
1540 if (DIDescriptor(Scope).isLexicalBlock()) {
1542 getOrCreateDbgScope(DILexicalBlock(Scope).getContext(), NULL);
1543 WScope->setParent(Parent);
1544 Parent->addScope(WScope);
1547 if (!WScope->getParent()) {
1548 StringRef SPName = DISubprogram(Scope).getLinkageName();
1549 // We used to check only for a linkage name, but that fails
1550 // since we began omitting the linkage name for private
1551 // functions. The new way is to check for the name in metadata,
1552 // but that's not supported in old .ll test cases. Ergo, we
1554 if (SPName == Asm->MF->getFunction()->getName() ||
1555 DISubprogram(Scope).getFunction() == Asm->MF->getFunction())
1556 CurrentFnDbgScope = WScope;
1562 getOrCreateAbstractScope(Scope);
1563 DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
1567 WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
1568 DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
1569 DILocation DL(InlinedAt);
1571 getOrCreateDbgScope(DL.getScope(), DL.getOrigLocation());
1572 WScope->setParent(Parent);
1573 Parent->addScope(WScope);
1575 ConcreteScopes[InlinedAt] = WScope;
1580 /// hasValidLocation - Return true if debug location entry attached with
1581 /// machine instruction encodes valid location info.
1582 static bool hasValidLocation(LLVMContext &Ctx,
1583 const MachineInstr *MInsn,
1584 const MDNode *&Scope, const MDNode *&InlinedAt) {
1585 DebugLoc DL = MInsn->getDebugLoc();
1586 if (DL.isUnknown()) return false;
1588 const MDNode *S = DL.getScope(Ctx);
1590 // There is no need to create another DIE for compile unit. For all
1591 // other scopes, create one DbgScope now. This will be translated
1592 // into a scope DIE at the end.
1593 if (DIScope(S).isCompileUnit()) return false;
1596 InlinedAt = DL.getInlinedAt(Ctx);
1600 /// calculateDominanceGraph - Calculate dominance graph for DbgScope
1602 static void calculateDominanceGraph(DbgScope *Scope) {
1603 assert (Scope && "Unable to calculate scop edominance graph!");
1604 SmallVector<DbgScope *, 4> WorkStack;
1605 WorkStack.push_back(Scope);
1606 unsigned Counter = 0;
1607 while (!WorkStack.empty()) {
1608 DbgScope *WS = WorkStack.back();
1609 const SmallVector<DbgScope *, 4> &Children = WS->getScopes();
1610 bool visitedChildren = false;
1611 for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
1612 SE = Children.end(); SI != SE; ++SI) {
1613 DbgScope *ChildScope = *SI;
1614 if (!ChildScope->getDFSOut()) {
1615 WorkStack.push_back(ChildScope);
1616 visitedChildren = true;
1617 ChildScope->setDFSIn(++Counter);
1621 if (!visitedChildren) {
1622 WorkStack.pop_back();
1623 WS->setDFSOut(++Counter);
1628 /// printDbgScopeInfo - Print DbgScope info for each machine instruction.
1630 void printDbgScopeInfo(LLVMContext &Ctx, const MachineFunction *MF,
1631 DenseMap<const MachineInstr *, DbgScope *> &MI2ScopeMap)
1634 unsigned PrevDFSIn = 0;
1635 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1637 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1639 const MachineInstr *MInsn = II;
1640 const MDNode *Scope = NULL;
1641 const MDNode *InlinedAt = NULL;
1643 // Check if instruction has valid location information.
1644 if (hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
1648 DenseMap<const MachineInstr *, DbgScope *>::iterator DI =
1649 MI2ScopeMap.find(MInsn);
1650 if (DI != MI2ScopeMap.end()) {
1651 DbgScope *S = DI->second;
1652 dbgs() << S->getDFSIn();
1653 PrevDFSIn = S->getDFSIn();
1655 dbgs() << PrevDFSIn;
1657 dbgs() << " [ x" << PrevDFSIn;
1665 /// extractScopeInformation - Scan machine instructions in this function
1666 /// and collect DbgScopes. Return true, if at least one scope was found.
1667 bool DwarfDebug::extractScopeInformation() {
1668 // If scope information was extracted using .dbg intrinsics then there is not
1669 // any need to extract these information by scanning each instruction.
1670 if (!DbgScopeMap.empty())
1673 // Scan each instruction and create scopes. First build working set of scopes.
1674 LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
1675 SmallVector<DbgRange, 4> MIRanges;
1676 DenseMap<const MachineInstr *, DbgScope *> MI2ScopeMap;
1677 const MDNode *PrevScope = NULL;
1678 const MDNode *PrevInlinedAt = NULL;
1679 const MachineInstr *RangeBeginMI = NULL;
1680 const MachineInstr *PrevMI = NULL;
1681 for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
1683 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1685 const MachineInstr *MInsn = II;
1686 const MDNode *Scope = NULL;
1687 const MDNode *InlinedAt = NULL;
1689 // Check if instruction has valid location information.
1690 if (!hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
1695 // If scope has not changed then skip this instruction.
1696 if (Scope == PrevScope && PrevInlinedAt == InlinedAt) {
1701 // Ignore DBG_VALUE. It does not contribute any instruction in output.
1702 if (MInsn->isDebugValue())
1706 // If we have alread seen a beginning of a instruction range and
1707 // current instruction scope does not match scope of first instruction
1708 // in this range then create a new instruction range.
1709 DbgRange R(RangeBeginMI, PrevMI);
1710 MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope,
1712 MIRanges.push_back(R);
1715 // This is a beginning of a new instruction range.
1716 RangeBeginMI = MInsn;
1718 // Reset previous markers.
1721 PrevInlinedAt = InlinedAt;
1725 // Create last instruction range.
1726 if (RangeBeginMI && PrevMI && PrevScope) {
1727 DbgRange R(RangeBeginMI, PrevMI);
1728 MIRanges.push_back(R);
1729 MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
1732 if (!CurrentFnDbgScope)
1735 calculateDominanceGraph(CurrentFnDbgScope);
1737 printDbgScopeInfo(Ctx, Asm->MF, MI2ScopeMap);
1739 // Find ranges of instructions covered by each DbgScope;
1740 DbgScope *PrevDbgScope = NULL;
1741 for (SmallVector<DbgRange, 4>::const_iterator RI = MIRanges.begin(),
1742 RE = MIRanges.end(); RI != RE; ++RI) {
1743 const DbgRange &R = *RI;
1744 DbgScope *S = MI2ScopeMap.lookup(R.first);
1745 assert (S && "Lost DbgScope for a machine instruction!");
1746 if (PrevDbgScope && !PrevDbgScope->dominates(S))
1747 PrevDbgScope->closeInsnRange(S);
1748 S->openInsnRange(R.first);
1749 S->extendInsnRange(R.second);
1754 PrevDbgScope->closeInsnRange();
1756 identifyScopeMarkers();
1758 return !DbgScopeMap.empty();
1761 /// identifyScopeMarkers() -
1762 /// Each DbgScope has first instruction and last instruction to mark beginning
1763 /// and end of a scope respectively. Create an inverse map that list scopes
1764 /// starts (and ends) with an instruction. One instruction may start (or end)
1765 /// multiple scopes. Ignore scopes that are not reachable.
1766 void DwarfDebug::identifyScopeMarkers() {
1767 SmallVector<DbgScope *, 4> WorkList;
1768 WorkList.push_back(CurrentFnDbgScope);
1769 while (!WorkList.empty()) {
1770 DbgScope *S = WorkList.pop_back_val();
1772 const SmallVector<DbgScope *, 4> &Children = S->getScopes();
1773 if (!Children.empty())
1774 for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
1775 SE = Children.end(); SI != SE; ++SI)
1776 WorkList.push_back(*SI);
1778 if (S->isAbstractScope())
1781 const SmallVector<DbgRange, 4> &Ranges = S->getRanges();
1784 for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
1785 RE = Ranges.end(); RI != RE; ++RI) {
1786 assert(RI->first && "DbgRange does not have first instruction!");
1787 assert(RI->second && "DbgRange does not have second instruction!");
1788 requestLabelBeforeInsn(RI->first);
1789 requestLabelAfterInsn(RI->second);
1794 /// FindFirstDebugLoc - Find the first debug location in the function. This
1795 /// is intended to be an approximation for the source position of the
1796 /// beginning of the function.
1797 static DebugLoc FindFirstDebugLoc(const MachineFunction *MF) {
1798 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1800 for (MachineBasicBlock::const_iterator MBBI = I->begin(), MBBE = I->end();
1801 MBBI != MBBE; ++MBBI) {
1802 DebugLoc DL = MBBI->getDebugLoc();
1803 if (!DL.isUnknown())
1810 /// CheckLineNumbers - Count basicblocks whose instructions do not have any
1811 /// line number information.
1812 static void CheckLineNumbers(const MachineFunction *MF) {
1813 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1815 bool FoundLineNo = false;
1816 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1818 const MachineInstr *MI = II;
1819 if (!MI->getDebugLoc().isUnknown()) {
1824 if (!FoundLineNo && I->size())
1825 ++BlocksWithoutLineNo;
1830 /// beginFunction - Gather pre-function debug information. Assumes being
1831 /// emitted immediately after the function entry point.
1832 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1833 if (!MMI->hasDebugInfo()) return;
1834 if (!extractScopeInformation()) return;
1837 CheckLineNumbers(MF);
1840 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1841 Asm->getFunctionNumber());
1842 // Assumes in correct section after the entry point.
1843 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1845 // Emit label for the implicitly defined dbg.stoppoint at the start of the
1847 DebugLoc FDL = FindFirstDebugLoc(MF);
1848 if (FDL.isUnknown()) return;
1850 const MDNode *Scope = FDL.getScope(MF->getFunction()->getContext());
1851 const MDNode *TheScope = 0;
1853 DISubprogram SP = getDISubprogram(Scope);
1856 Line = SP.getLineNumber();
1860 Line = FDL.getLine();
1865 recordSourceLine(Line, Col, TheScope);
1867 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1869 /// ProcessedArgs - Collection of arguments already processed.
1870 SmallPtrSet<const MDNode *, 8> ProcessedArgs;
1872 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1874 /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1875 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1877 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1879 bool AtBlockEntry = true;
1880 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1882 const MachineInstr *MI = II;
1884 if (MI->isDebugValue()) {
1885 assert (MI->getNumOperands() > 1 && "Invalid machine instruction!");
1887 // Keep track of user variables.
1889 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1891 // Variable is in a register, we need to check for clobbers.
1892 if (isDbgValueInDefinedReg(MI))
1893 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1895 // Check the history of this variable.
1896 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1897 if (History.empty()) {
1898 UserVariables.push_back(Var);
1899 // The first mention of a function argument gets the FunctionBeginSym
1900 // label, so arguments are visible when breaking at function entry.
1902 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1903 DISubprogram(getDISubprogram(DV.getContext()))
1904 .describes(MF->getFunction()))
1905 LabelsBeforeInsn[MI] = FunctionBeginSym;
1907 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1908 const MachineInstr *Prev = History.back();
1909 if (Prev->isDebugValue()) {
1910 // Coalesce identical entries at the end of History.
1911 if (History.size() >= 2 &&
1912 Prev->isIdenticalTo(History[History.size() - 2]))
1915 // Terminate old register assignments that don't reach MI;
1916 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1917 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1918 isDbgValueInDefinedReg(Prev)) {
1919 // Previous register assignment needs to terminate at the end of
1921 MachineBasicBlock::const_iterator LastMI =
1922 PrevMBB->getLastNonDebugInstr();
1923 if (LastMI == PrevMBB->end())
1924 // Drop DBG_VALUE for empty range.
1927 // Terminate after LastMI.
1928 History.push_back(LastMI);
1933 History.push_back(MI);
1935 // Not a DBG_VALUE instruction.
1937 AtBlockEntry = false;
1939 // Check if the instruction clobbers any registers with debug vars.
1940 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1941 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1942 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1944 for (const unsigned *AI = TRI->getOverlaps(MOI->getReg());
1945 unsigned Reg = *AI; ++AI) {
1946 const MDNode *Var = LiveUserVar[Reg];
1949 // Reg is now clobbered.
1950 LiveUserVar[Reg] = 0;
1952 // Was MD last defined by a DBG_VALUE referring to Reg?
1953 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1954 if (HistI == DbgValues.end())
1956 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1957 if (History.empty())
1959 const MachineInstr *Prev = History.back();
1960 // Sanity-check: Register assignments are terminated at the end of
1962 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1964 // Is the variable still in Reg?
1965 if (!isDbgValueInDefinedReg(Prev) ||
1966 Prev->getOperand(0).getReg() != Reg)
1968 // Var is clobbered. Make sure the next instruction gets a label.
1969 History.push_back(MI);
1976 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1978 SmallVectorImpl<const MachineInstr*> &History = I->second;
1979 if (History.empty())
1982 // Make sure the final register assignments are terminated.
1983 const MachineInstr *Prev = History.back();
1984 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1985 const MachineBasicBlock *PrevMBB = Prev->getParent();
1986 MachineBasicBlock::const_iterator LastMI = PrevMBB->getLastNonDebugInstr();
1987 if (LastMI == PrevMBB->end())
1988 // Drop DBG_VALUE for empty range.
1991 // Terminate after LastMI.
1992 History.push_back(LastMI);
1995 // Request labels for the full history.
1996 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1997 const MachineInstr *MI = History[i];
1998 if (MI->isDebugValue())
1999 requestLabelBeforeInsn(MI);
2001 requestLabelAfterInsn(MI);
2005 PrevInstLoc = DebugLoc();
2006 PrevLabel = FunctionBeginSym;
2009 /// endFunction - Gather and emit post-function debug information.
2011 void DwarfDebug::endFunction(const MachineFunction *MF) {
2012 if (!MMI->hasDebugInfo() || DbgScopeMap.empty()) return;
2014 if (CurrentFnDbgScope) {
2016 // Define end label for subprogram.
2017 FunctionEndSym = Asm->GetTempSymbol("func_end",
2018 Asm->getFunctionNumber());
2019 // Assumes in correct section after the entry point.
2020 Asm->OutStreamer.EmitLabel(FunctionEndSym);
2022 SmallPtrSet<const MDNode *, 16> ProcessedVars;
2023 collectVariableInfo(MF, ProcessedVars);
2025 // Construct abstract scopes.
2026 for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2027 AE = AbstractScopesList.end(); AI != AE; ++AI) {
2028 DISubprogram SP((*AI)->getScopeNode());
2030 // Collect info for variables that were optimized out.
2031 StringRef FName = SP.getLinkageName();
2033 FName = SP.getName();
2034 if (NamedMDNode *NMD =
2035 getFnSpecificMDNode(*(MF->getFunction()->getParent()), FName)) {
2036 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2037 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
2038 if (!DV || !ProcessedVars.insert(DV))
2040 DbgScope *Scope = AbstractScopes.lookup(DV.getContext());
2042 Scope->addVariable(new DbgVariable(DV));
2046 if (ProcessedSPNodes.count((*AI)->getScopeNode()) == 0)
2047 constructScopeDIE(*AI);
2050 DIE *CurFnDIE = constructScopeDIE(CurrentFnDbgScope);
2052 if (!DisableFramePointerElim(*MF))
2053 getCompileUnit(CurrentFnDbgScope->getScopeNode())->addUInt(CurFnDIE,
2054 dwarf::DW_AT_APPLE_omit_frame_ptr,
2055 dwarf::DW_FORM_flag, 1);
2058 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
2059 MMI->getFrameMoves()));
2063 CurrentFnDbgScope = NULL;
2064 CurrentFnArguments.clear();
2065 DbgVariableToFrameIndexMap.clear();
2066 VarToAbstractVarMap.clear();
2067 DbgVariableToDbgInstMap.clear();
2068 DeleteContainerSeconds(DbgScopeMap);
2069 UserVariables.clear();
2071 ConcreteScopes.clear();
2072 DeleteContainerSeconds(AbstractScopes);
2073 AbstractScopesList.clear();
2074 AbstractVariables.clear();
2075 LabelsBeforeInsn.clear();
2076 LabelsAfterInsn.clear();
2080 /// recordVariableFrameIndex - Record a variable's index.
2081 void DwarfDebug::recordVariableFrameIndex(const DbgVariable *V, int Index) {
2082 assert (V && "Invalid DbgVariable!");
2083 DbgVariableToFrameIndexMap[V] = Index;
2086 /// findVariableFrameIndex - Return true if frame index for the variable
2087 /// is found. Update FI to hold value of the index.
2088 bool DwarfDebug::findVariableFrameIndex(const DbgVariable *V, int *FI) {
2089 assert (V && "Invalid DbgVariable!");
2090 DenseMap<const DbgVariable *, int>::iterator I =
2091 DbgVariableToFrameIndexMap.find(V);
2092 if (I == DbgVariableToFrameIndexMap.end())
2098 /// findDbgScope - Find DbgScope for the debug loc attached with an
2100 DbgScope *DwarfDebug::findDbgScope(const MachineInstr *MInsn) {
2101 DbgScope *Scope = NULL;
2103 MInsn->getParent()->getParent()->getFunction()->getContext();
2104 DebugLoc DL = MInsn->getDebugLoc();
2109 if (const MDNode *IA = DL.getInlinedAt(Ctx))
2110 Scope = ConcreteScopes.lookup(IA);
2112 Scope = DbgScopeMap.lookup(DL.getScope(Ctx));
2118 /// recordSourceLine - Register a source line with debug info. Returns the
2119 /// unique label that was emitted and which provides correspondence to
2120 /// the source line list.
2121 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S){
2126 DIDescriptor Scope(S);
2128 if (Scope.isCompileUnit()) {
2129 DICompileUnit CU(S);
2130 Fn = CU.getFilename();
2131 Dir = CU.getDirectory();
2132 } else if (Scope.isFile()) {
2134 Fn = F.getFilename();
2135 Dir = F.getDirectory();
2136 } else if (Scope.isSubprogram()) {
2138 Fn = SP.getFilename();
2139 Dir = SP.getDirectory();
2140 } else if (Scope.isLexicalBlock()) {
2141 DILexicalBlock DB(S);
2142 Fn = DB.getFilename();
2143 Dir = DB.getDirectory();
2145 assert(0 && "Unexpected scope info");
2147 Src = GetOrCreateSourceID(Fn, Dir);
2150 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, DWARF2_FLAG_IS_STMT,
2154 //===----------------------------------------------------------------------===//
2156 //===----------------------------------------------------------------------===//
2158 /// computeSizeAndOffset - Compute the size and offset of a DIE.
2161 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
2162 // Get the children.
2163 const std::vector<DIE *> &Children = Die->getChildren();
2165 // If not last sibling and has children then add sibling offset attribute.
2166 if (!Last && !Children.empty())
2167 Die->addSiblingOffset(DIEValueAllocator);
2169 // Record the abbreviation.
2170 assignAbbrevNumber(Die->getAbbrev());
2172 // Get the abbreviation for this DIE.
2173 unsigned AbbrevNumber = Die->getAbbrevNumber();
2174 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2177 Die->setOffset(Offset);
2179 // Start the size with the size of abbreviation code.
2180 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2182 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2183 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2185 // Size the DIE attribute values.
2186 for (unsigned i = 0, N = Values.size(); i < N; ++i)
2187 // Size attribute value.
2188 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
2190 // Size the DIE children if any.
2191 if (!Children.empty()) {
2192 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2193 "Children flag not set");
2195 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2196 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
2198 // End of children marker.
2199 Offset += sizeof(int8_t);
2202 Die->setSize(Offset - Die->getOffset());
2206 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
2208 void DwarfDebug::computeSizeAndOffsets() {
2209 unsigned PrevOffset = 0;
2210 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2211 E = CUMap.end(); I != E; ++I) {
2212 // Compute size of compile unit header.
2213 static unsigned Offset = PrevOffset +
2214 sizeof(int32_t) + // Length of Compilation Unit Info
2215 sizeof(int16_t) + // DWARF version number
2216 sizeof(int32_t) + // Offset Into Abbrev. Section
2217 sizeof(int8_t); // Pointer Size (in bytes)
2218 computeSizeAndOffset(I->second->getCUDie(), Offset, true);
2219 PrevOffset = Offset;
2223 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
2224 /// temporary label to it if SymbolStem is specified.
2225 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
2226 const char *SymbolStem = 0) {
2227 Asm->OutStreamer.SwitchSection(Section);
2228 if (!SymbolStem) return 0;
2230 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
2231 Asm->OutStreamer.EmitLabel(TmpSym);
2235 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
2236 /// the start of each one.
2237 void DwarfDebug::EmitSectionLabels() {
2238 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2240 // Dwarf sections base addresses.
2241 if (Asm->MAI->doesDwarfRequireFrameSection()) {
2242 DwarfFrameSectionSym =
2243 EmitSectionSym(Asm, TLOF.getDwarfFrameSection(), "section_debug_frame");
2246 DwarfInfoSectionSym =
2247 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
2248 DwarfAbbrevSectionSym =
2249 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
2250 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
2252 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
2253 EmitSectionSym(Asm, MacroInfo);
2255 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
2256 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
2257 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
2258 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2259 DwarfStrSectionSym =
2260 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
2261 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
2264 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
2265 "section_debug_loc");
2267 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
2268 EmitSectionSym(Asm, TLOF.getDataSection());
2271 /// emitDIE - Recusively Emits a debug information entry.
2273 void DwarfDebug::emitDIE(DIE *Die) {
2274 // Get the abbreviation for this DIE.
2275 unsigned AbbrevNumber = Die->getAbbrevNumber();
2276 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2278 // Emit the code (index) for the abbreviation.
2279 if (Asm->isVerbose())
2280 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
2281 Twine::utohexstr(Die->getOffset()) + ":0x" +
2282 Twine::utohexstr(Die->getSize()) + " " +
2283 dwarf::TagString(Abbrev->getTag()));
2284 Asm->EmitULEB128(AbbrevNumber);
2286 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2287 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2289 // Emit the DIE attribute values.
2290 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2291 unsigned Attr = AbbrevData[i].getAttribute();
2292 unsigned Form = AbbrevData[i].getForm();
2293 assert(Form && "Too many attributes for DIE (check abbreviation)");
2295 if (Asm->isVerbose())
2296 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2299 case dwarf::DW_AT_sibling:
2300 Asm->EmitInt32(Die->getSiblingOffset());
2302 case dwarf::DW_AT_abstract_origin: {
2303 DIEEntry *E = cast<DIEEntry>(Values[i]);
2304 DIE *Origin = E->getEntry();
2305 unsigned Addr = Origin->getOffset();
2306 Asm->EmitInt32(Addr);
2309 case dwarf::DW_AT_ranges: {
2310 // DW_AT_range Value encodes offset in debug_range section.
2311 DIEInteger *V = cast<DIEInteger>(Values[i]);
2313 if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
2314 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
2318 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
2320 DwarfDebugRangeSectionSym,
2325 case dwarf::DW_AT_location: {
2326 if (UseDotDebugLocEntry.count(Die) != 0) {
2327 DIELabel *L = cast<DIELabel>(Values[i]);
2328 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2330 Values[i]->EmitValue(Asm, Form);
2333 case dwarf::DW_AT_accessibility: {
2334 if (Asm->isVerbose()) {
2335 DIEInteger *V = cast<DIEInteger>(Values[i]);
2336 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2338 Values[i]->EmitValue(Asm, Form);
2342 // Emit an attribute using the defined form.
2343 Values[i]->EmitValue(Asm, Form);
2348 // Emit the DIE children if any.
2349 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2350 const std::vector<DIE *> &Children = Die->getChildren();
2352 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2353 emitDIE(Children[j]);
2355 if (Asm->isVerbose())
2356 Asm->OutStreamer.AddComment("End Of Children Mark");
2361 /// emitDebugInfo - Emit the debug info section.
2363 void DwarfDebug::emitDebugInfo() {
2364 // Start debug info section.
2365 Asm->OutStreamer.SwitchSection(
2366 Asm->getObjFileLowering().getDwarfInfoSection());
2367 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2368 E = CUMap.end(); I != E; ++I) {
2369 CompileUnit *TheCU = I->second;
2370 DIE *Die = TheCU->getCUDie();
2372 // Emit the compile units header.
2373 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
2376 // Emit size of content not including length itself
2377 unsigned ContentSize = Die->getSize() +
2378 sizeof(int16_t) + // DWARF version number
2379 sizeof(int32_t) + // Offset Into Abbrev. Section
2380 sizeof(int8_t) + // Pointer Size (in bytes)
2381 sizeof(int32_t); // FIXME - extra pad for gdb bug.
2383 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2384 Asm->EmitInt32(ContentSize);
2385 Asm->OutStreamer.AddComment("DWARF version number");
2386 Asm->EmitInt16(dwarf::DWARF_VERSION);
2387 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2388 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
2389 DwarfAbbrevSectionSym);
2390 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2391 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2394 // FIXME - extra padding for gdb bug.
2395 Asm->OutStreamer.AddComment("4 extra padding bytes for GDB");
2400 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
2404 /// emitAbbreviations - Emit the abbreviation section.
2406 void DwarfDebug::emitAbbreviations() const {
2407 // Check to see if it is worth the effort.
2408 if (!Abbreviations.empty()) {
2409 // Start the debug abbrev section.
2410 Asm->OutStreamer.SwitchSection(
2411 Asm->getObjFileLowering().getDwarfAbbrevSection());
2413 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
2415 // For each abbrevation.
2416 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2417 // Get abbreviation data
2418 const DIEAbbrev *Abbrev = Abbreviations[i];
2420 // Emit the abbrevations code (base 1 index.)
2421 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2423 // Emit the abbreviations data.
2427 // Mark end of abbreviations.
2428 Asm->EmitULEB128(0, "EOM(3)");
2430 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
2434 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
2435 /// the line matrix.
2437 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2438 // Define last address of section.
2439 Asm->OutStreamer.AddComment("Extended Op");
2442 Asm->OutStreamer.AddComment("Op size");
2443 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
2444 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2445 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2447 Asm->OutStreamer.AddComment("Section end label");
2449 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2450 Asm->getTargetData().getPointerSize(),
2453 // Mark end of matrix.
2454 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2460 /// emitCommonDebugFrame - Emit common frame info into a debug frame section.
2462 void DwarfDebug::emitCommonDebugFrame() {
2463 if (!Asm->MAI->doesDwarfRequireFrameSection())
2466 int stackGrowth = Asm->getTargetData().getPointerSize();
2467 if (Asm->TM.getFrameLowering()->getStackGrowthDirection() ==
2468 TargetFrameLowering::StackGrowsDown)
2471 // Start the dwarf frame section.
2472 Asm->OutStreamer.SwitchSection(
2473 Asm->getObjFileLowering().getDwarfFrameSection());
2475 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common"));
2476 Asm->OutStreamer.AddComment("Length of Common Information Entry");
2477 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_frame_common_end"),
2478 Asm->GetTempSymbol("debug_frame_common_begin"), 4);
2480 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_begin"));
2481 Asm->OutStreamer.AddComment("CIE Identifier Tag");
2482 Asm->EmitInt32((int)dwarf::DW_CIE_ID);
2483 Asm->OutStreamer.AddComment("CIE Version");
2484 Asm->EmitInt8(dwarf::DW_CIE_VERSION);
2485 Asm->OutStreamer.AddComment("CIE Augmentation");
2486 Asm->OutStreamer.EmitIntValue(0, 1, /*addrspace*/0); // nul terminator.
2487 Asm->EmitULEB128(1, "CIE Code Alignment Factor");
2488 Asm->EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
2489 Asm->OutStreamer.AddComment("CIE RA Column");
2490 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
2491 const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
2492 Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2494 std::vector<MachineMove> Moves;
2495 TFI->getInitialFrameState(Moves);
2497 Asm->EmitFrameMoves(Moves, 0, false);
2499 Asm->EmitAlignment(2);
2500 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_end"));
2503 /// emitFunctionDebugFrame - Emit per function frame info into a debug frame
2506 emitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2507 if (!Asm->MAI->doesDwarfRequireFrameSection())
2510 // Start the dwarf frame section.
2511 Asm->OutStreamer.SwitchSection(
2512 Asm->getObjFileLowering().getDwarfFrameSection());
2514 Asm->OutStreamer.AddComment("Length of Frame Information Entry");
2515 MCSymbol *DebugFrameBegin =
2516 Asm->GetTempSymbol("debug_frame_begin", DebugFrameInfo.Number);
2517 MCSymbol *DebugFrameEnd =
2518 Asm->GetTempSymbol("debug_frame_end", DebugFrameInfo.Number);
2519 Asm->EmitLabelDifference(DebugFrameEnd, DebugFrameBegin, 4);
2521 Asm->OutStreamer.EmitLabel(DebugFrameBegin);
2523 Asm->OutStreamer.AddComment("FDE CIE offset");
2524 Asm->EmitSectionOffset(Asm->GetTempSymbol("debug_frame_common"),
2525 DwarfFrameSectionSym);
2527 Asm->OutStreamer.AddComment("FDE initial location");
2528 MCSymbol *FuncBeginSym =
2529 Asm->GetTempSymbol("func_begin", DebugFrameInfo.Number);
2530 Asm->OutStreamer.EmitSymbolValue(FuncBeginSym,
2531 Asm->getTargetData().getPointerSize(),
2535 Asm->OutStreamer.AddComment("FDE address range");
2536 Asm->EmitLabelDifference(Asm->GetTempSymbol("func_end",DebugFrameInfo.Number),
2537 FuncBeginSym, Asm->getTargetData().getPointerSize());
2539 Asm->EmitFrameMoves(DebugFrameInfo.Moves, FuncBeginSym, false);
2541 Asm->EmitAlignment(2);
2542 Asm->OutStreamer.EmitLabel(DebugFrameEnd);
2545 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2547 void DwarfDebug::emitDebugPubNames() {
2548 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2549 E = CUMap.end(); I != E; ++I) {
2550 CompileUnit *TheCU = I->second;
2551 // Start the dwarf pubnames section.
2552 Asm->OutStreamer.SwitchSection(
2553 Asm->getObjFileLowering().getDwarfPubNamesSection());
2555 Asm->OutStreamer.AddComment("Length of Public Names Info");
2556 Asm->EmitLabelDifference(
2557 Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
2558 Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
2560 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
2563 Asm->OutStreamer.AddComment("DWARF Version");
2564 Asm->EmitInt16(dwarf::DWARF_VERSION);
2566 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2567 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
2568 DwarfInfoSectionSym);
2570 Asm->OutStreamer.AddComment("Compilation Unit Length");
2571 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
2572 Asm->GetTempSymbol("info_begin", TheCU->getID()),
2575 const StringMap<DIE*> &Globals = TheCU->getGlobals();
2576 for (StringMap<DIE*>::const_iterator
2577 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2578 const char *Name = GI->getKeyData();
2579 DIE *Entity = GI->second;
2581 Asm->OutStreamer.AddComment("DIE offset");
2582 Asm->EmitInt32(Entity->getOffset());
2584 if (Asm->isVerbose())
2585 Asm->OutStreamer.AddComment("External Name");
2586 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
2589 Asm->OutStreamer.AddComment("End Mark");
2591 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
2596 void DwarfDebug::emitDebugPubTypes() {
2597 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2598 E = CUMap.end(); I != E; ++I) {
2599 CompileUnit *TheCU = I->second;
2600 // Start the dwarf pubnames section.
2601 Asm->OutStreamer.SwitchSection(
2602 Asm->getObjFileLowering().getDwarfPubTypesSection());
2603 Asm->OutStreamer.AddComment("Length of Public Types Info");
2604 Asm->EmitLabelDifference(
2605 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
2606 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
2608 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2611 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2612 Asm->EmitInt16(dwarf::DWARF_VERSION);
2614 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2615 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
2616 DwarfInfoSectionSym);
2618 Asm->OutStreamer.AddComment("Compilation Unit Length");
2619 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
2620 Asm->GetTempSymbol("info_begin", TheCU->getID()),
2623 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2624 for (StringMap<DIE*>::const_iterator
2625 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2626 const char *Name = GI->getKeyData();
2627 DIE * Entity = GI->second;
2629 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2630 Asm->EmitInt32(Entity->getOffset());
2632 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2633 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
2636 Asm->OutStreamer.AddComment("End Mark");
2638 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2643 /// emitDebugStr - Emit visible names into a debug str section.
2645 void DwarfDebug::emitDebugStr() {
2646 // Check to see if it is worth the effort.
2647 if (StringPool.empty()) return;
2649 // Start the dwarf str section.
2650 Asm->OutStreamer.SwitchSection(
2651 Asm->getObjFileLowering().getDwarfStrSection());
2653 // Get all of the string pool entries and put them in an array by their ID so
2654 // we can sort them.
2655 SmallVector<std::pair<unsigned,
2656 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2658 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2659 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
2660 Entries.push_back(std::make_pair(I->second.second, &*I));
2662 array_pod_sort(Entries.begin(), Entries.end());
2664 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2665 // Emit a label for reference from debug information entries.
2666 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2668 // Emit the string itself.
2669 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
2673 /// emitDebugLoc - Emit visible names into a debug loc section.
2675 void DwarfDebug::emitDebugLoc() {
2676 if (DotDebugLocEntries.empty())
2679 for (SmallVector<DotDebugLocEntry, 4>::iterator
2680 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2682 DotDebugLocEntry &Entry = *I;
2683 if (I + 1 != DotDebugLocEntries.end())
2687 // Start the dwarf loc section.
2688 Asm->OutStreamer.SwitchSection(
2689 Asm->getObjFileLowering().getDwarfLocSection());
2690 unsigned char Size = Asm->getTargetData().getPointerSize();
2691 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2693 for (SmallVector<DotDebugLocEntry, 4>::iterator
2694 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2695 I != E; ++I, ++index) {
2696 DotDebugLocEntry &Entry = *I;
2697 if (Entry.isMerged()) continue;
2698 if (Entry.isEmpty()) {
2699 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2700 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2701 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2703 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
2704 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
2705 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
2706 unsigned Reg = RI->getDwarfRegNum(Entry.Loc.getReg(), false);
2707 if (int Offset = Entry.Loc.getOffset()) {
2708 // If the value is at a certain offset from frame register then
2710 unsigned OffsetSize = Offset ? MCAsmInfo::getSLEB128Size(Offset) : 1;
2711 Asm->OutStreamer.AddComment("Loc expr size");
2712 Asm->EmitInt16(1 + OffsetSize);
2713 Asm->OutStreamer.AddComment(
2714 dwarf::OperationEncodingString(dwarf::DW_OP_fbreg));
2715 Asm->EmitInt8(dwarf::DW_OP_fbreg);
2716 Asm->OutStreamer.AddComment("Offset");
2717 Asm->EmitSLEB128(Offset);
2720 Asm->OutStreamer.AddComment("Loc expr size");
2722 Asm->OutStreamer.AddComment(
2723 dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
2724 Asm->EmitInt8(dwarf::DW_OP_reg0 + Reg);
2726 Asm->OutStreamer.AddComment("Loc expr size");
2727 Asm->EmitInt16(1 + MCAsmInfo::getULEB128Size(Reg));
2728 Asm->EmitInt8(dwarf::DW_OP_regx);
2729 Asm->EmitULEB128(Reg);
2736 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2738 void DwarfDebug::EmitDebugARanges() {
2739 // Start the dwarf aranges section.
2740 Asm->OutStreamer.SwitchSection(
2741 Asm->getObjFileLowering().getDwarfARangesSection());
2744 /// emitDebugRanges - Emit visible names into a debug ranges section.
2746 void DwarfDebug::emitDebugRanges() {
2747 // Start the dwarf ranges section.
2748 Asm->OutStreamer.SwitchSection(
2749 Asm->getObjFileLowering().getDwarfRangesSection());
2750 unsigned char Size = Asm->getTargetData().getPointerSize();
2751 for (SmallVector<const MCSymbol *, 8>::iterator
2752 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2755 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
2757 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2761 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2763 void DwarfDebug::emitDebugMacInfo() {
2764 if (const MCSection *LineInfo =
2765 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2766 // Start the dwarf macinfo section.
2767 Asm->OutStreamer.SwitchSection(LineInfo);
2771 /// emitDebugInlineInfo - Emit inline info using following format.
2773 /// 1. length of section
2774 /// 2. Dwarf version number
2775 /// 3. address size.
2777 /// Entries (one "entry" for each function that was inlined):
2779 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2780 /// otherwise offset into __debug_str for regular function name.
2781 /// 2. offset into __debug_str section for regular function name.
2782 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2783 /// instances for the function.
2785 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2786 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2787 /// __debug_info section, and the low_pc is the starting address for the
2788 /// inlining instance.
2789 void DwarfDebug::emitDebugInlineInfo() {
2790 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
2796 Asm->OutStreamer.SwitchSection(
2797 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2799 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2800 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2801 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2803 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2805 Asm->OutStreamer.AddComment("Dwarf Version");
2806 Asm->EmitInt16(dwarf::DWARF_VERSION);
2807 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2808 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2810 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2811 E = InlinedSPNodes.end(); I != E; ++I) {
2813 const MDNode *Node = *I;
2814 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2815 = InlineInfo.find(Node);
2816 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2817 DISubprogram SP(Node);
2818 StringRef LName = SP.getLinkageName();
2819 StringRef Name = SP.getName();
2821 Asm->OutStreamer.AddComment("MIPS linkage name");
2822 if (LName.empty()) {
2823 Asm->OutStreamer.EmitBytes(Name, 0);
2824 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
2826 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2827 DwarfStrSectionSym);
2829 Asm->OutStreamer.AddComment("Function name");
2830 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2831 Asm->EmitULEB128(Labels.size(), "Inline count");
2833 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2834 LE = Labels.end(); LI != LE; ++LI) {
2835 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2836 Asm->EmitInt32(LI->second->getOffset());
2838 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2839 Asm->OutStreamer.EmitSymbolValue(LI->first,
2840 Asm->getTargetData().getPointerSize(),0);
2844 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));