Simplify by creating parent first.
[oota-llvm.git] / lib / CodeGen / AsmPrinter / DwarfDebug.cpp
1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing dwarf debug info into asm files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "dwarfdebug"
15 #include "DwarfDebug.h"
16 #include "DIE.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"
46 using namespace llvm;
47
48 static cl::opt<bool> PrintDbgScope("print-dbgscope", cl::Hidden,
49      cl::desc("Print DbgScope information for each machine instruction"));
50
51 static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print",
52                                               cl::Hidden,
53      cl::desc("Disable debug info printing"));
54
55 static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
56      cl::desc("Make an absence of debug location information explicit."),
57      cl::init(false));
58
59 namespace {
60   const char *DWARFGroupName = "DWARF Emission";
61   const char *DbgTimerName = "DWARF Debug Writer";
62 } // end anonymous namespace
63
64 //===----------------------------------------------------------------------===//
65
66 /// Configuration values for initial hash set sizes (log2).
67 ///
68 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
69
70 namespace llvm {
71
72 DIType DbgVariable::getType() const {
73   DIType Ty = Var.getType();
74   // FIXME: isBlockByrefVariable should be reformulated in terms of complex
75   // addresses instead.
76   if (Var.isBlockByrefVariable()) {
77     /* Byref variables, in Blocks, are declared by the programmer as
78        "SomeType VarName;", but the compiler creates a
79        __Block_byref_x_VarName struct, and gives the variable VarName
80        either the struct, or a pointer to the struct, as its type.  This
81        is necessary for various behind-the-scenes things the compiler
82        needs to do with by-reference variables in blocks.
83        
84        However, as far as the original *programmer* is concerned, the
85        variable should still have type 'SomeType', as originally declared.
86        
87        The following function dives into the __Block_byref_x_VarName
88        struct to find the original type of the variable.  This will be
89        passed back to the code generating the type for the Debug
90        Information Entry for the variable 'VarName'.  'VarName' will then
91        have the original type 'SomeType' in its debug information.
92        
93        The original type 'SomeType' will be the type of the field named
94        'VarName' inside the __Block_byref_x_VarName struct.
95        
96        NOTE: In order for this to not completely fail on the debugger
97        side, the Debug Information Entry for the variable VarName needs to
98        have a DW_AT_location that tells the debugger how to unwind through
99        the pointers and __Block_byref_x_VarName struct to find the actual
100        value of the variable.  The function addBlockByrefType does this.  */
101     DIType subType = Ty;
102     unsigned tag = Ty.getTag();
103     
104     if (tag == dwarf::DW_TAG_pointer_type) {
105       DIDerivedType DTy = DIDerivedType(Ty);
106       subType = DTy.getTypeDerivedFrom();
107     }
108     
109     DICompositeType blockStruct = DICompositeType(subType);
110     DIArray Elements = blockStruct.getTypeArray();
111     
112     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
113       DIDescriptor Element = Elements.getElement(i);
114       DIDerivedType DT = DIDerivedType(Element);
115       if (getName() == DT.getName())
116         return (DT.getTypeDerivedFrom());
117     }
118     return Ty;
119   }
120   return Ty;
121 }
122
123 //===----------------------------------------------------------------------===//
124 /// DbgRange - This is used to track range of instructions with identical
125 /// debug info scope.
126 ///
127 typedef std::pair<const MachineInstr *, const MachineInstr *> DbgRange;
128
129 //===----------------------------------------------------------------------===//
130 /// DbgScope - This class is used to track scope information.
131 ///
132 class DbgScope {
133   DbgScope *Parent;                   // Parent to this scope.
134   DIDescriptor Desc;                  // Debug info descriptor for scope.
135   // Location at which this scope is inlined.
136   AssertingVH<const MDNode> InlinedAtLocation;
137   bool AbstractScope;                 // Abstract Scope
138   const MachineInstr *LastInsn;       // Last instruction of this scope.
139   const MachineInstr *FirstInsn;      // First instruction of this scope.
140   unsigned DFSIn, DFSOut;
141   // Scopes defined in scope.  Contents not owned.
142   SmallVector<DbgScope *, 4> Scopes;
143   // Variables declared in scope.  Contents owned.
144   SmallVector<DbgVariable *, 8> Variables;
145   SmallVector<DbgRange, 4> Ranges;
146   // Private state for dump()
147   mutable unsigned IndentLevel;
148 public:
149   DbgScope(DbgScope *P, DIDescriptor D, const MDNode *I = 0)
150     : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(false),
151       LastInsn(0), FirstInsn(0),
152       DFSIn(0), DFSOut(0), IndentLevel(0) {
153     if (Parent)
154       Parent->addScope(this);
155   }
156   virtual ~DbgScope();
157
158   // Accessors.
159   DbgScope *getParent()          const { return Parent; }
160   DIDescriptor getDesc()         const { return Desc; }
161   const MDNode *getInlinedAt()         const { return InlinedAtLocation; }
162   const MDNode *getScopeNode()         const { return Desc; }
163   const SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
164   const SmallVector<DbgVariable *, 8> &getDbgVariables() { return Variables; }
165   const SmallVector<DbgRange, 4> &getRanges() { return Ranges; }
166
167   /// openInsnRange - This scope covers instruction range starting from MI.
168   void openInsnRange(const MachineInstr *MI) {
169     if (!FirstInsn)
170       FirstInsn = MI;
171
172     if (Parent)
173       Parent->openInsnRange(MI);
174   }
175
176   /// extendInsnRange - Extend the current instruction range covered by
177   /// this scope.
178   void extendInsnRange(const MachineInstr *MI) {
179     assert (FirstInsn && "MI Range is not open!");
180     LastInsn = MI;
181     if (Parent)
182       Parent->extendInsnRange(MI);
183   }
184
185   /// closeInsnRange - Create a range based on FirstInsn and LastInsn collected
186   /// until now. This is used when a new scope is encountered while walking
187   /// machine instructions.
188   void closeInsnRange(DbgScope *NewScope = NULL) {
189     assert (LastInsn && "Last insn missing!");
190     Ranges.push_back(DbgRange(FirstInsn, LastInsn));
191     FirstInsn = NULL;
192     LastInsn = NULL;
193     // If Parent dominates NewScope then do not close Parent's instruction
194     // range.
195     if (Parent && (!NewScope || !Parent->dominates(NewScope)))
196       Parent->closeInsnRange(NewScope);
197   }
198
199   void setAbstractScope() { AbstractScope = true; }
200   bool isAbstractScope() const { return AbstractScope; }
201
202   // Depth First Search support to walk and manipulate DbgScope hierarchy.
203   unsigned getDFSOut() const { return DFSOut; }
204   void setDFSOut(unsigned O) { DFSOut = O; }
205   unsigned getDFSIn() const  { return DFSIn; }
206   void setDFSIn(unsigned I)  { DFSIn = I; }
207   bool dominates(const DbgScope *S) {
208     if (S == this)
209       return true;
210     if (DFSIn < S->getDFSIn() && DFSOut > S->getDFSOut())
211       return true;
212     return false;
213   }
214
215   /// addScope - Add a scope to the scope.
216   ///
217   void addScope(DbgScope *S) { Scopes.push_back(S); }
218
219   /// addVariable - Add a variable to the scope.
220   ///
221   void addVariable(DbgVariable *V) { Variables.push_back(V); }
222
223 #ifndef NDEBUG
224   void dump() const;
225 #endif
226 };
227
228 } // end llvm namespace
229
230 #ifndef NDEBUG
231 void DbgScope::dump() const {
232   raw_ostream &err = dbgs();
233   err.indent(IndentLevel);
234   err << "DFSIn: " << DFSIn << " DFSOut: " << DFSOut << "\n";
235   const MDNode *N = Desc;
236   N->dump();
237   if (AbstractScope)
238     err << "Abstract Scope\n";
239
240   IndentLevel += 2;
241   if (!Scopes.empty())
242     err << "Children ...\n";
243   for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
244     if (Scopes[i] != this)
245       Scopes[i]->dump();
246
247   IndentLevel -= 2;
248 }
249 #endif
250
251 DbgScope::~DbgScope() {
252   for (unsigned j = 0, M = Variables.size(); j < M; ++j)
253     delete Variables[j];
254 }
255
256 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
257   : Asm(A), MMI(Asm->MMI), FirstCU(0),
258     AbbreviationsSet(InitAbbreviationsSetSize),
259     CurrentFnDbgScope(0), PrevLabel(NULL) {
260   NextStringPoolNumber = 0;
261
262   DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
263   DwarfStrSectionSym = TextSectionSym = 0;
264   DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
265   FunctionBeginSym = FunctionEndSym = 0;
266   {
267     NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
268     beginModule(M);
269   }
270 }
271 DwarfDebug::~DwarfDebug() {
272 }
273
274 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
275   std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
276   if (Entry.first) return Entry.first;
277
278   Entry.second = NextStringPoolNumber++;
279   return Entry.first = Asm->GetTempSymbol("string", Entry.second);
280 }
281
282
283 /// assignAbbrevNumber - Define a unique number for the abbreviation.
284 ///
285 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
286   // Profile the node so that we can make it unique.
287   FoldingSetNodeID ID;
288   Abbrev.Profile(ID);
289
290   // Check the set for priors.
291   DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
292
293   // If it's newly added.
294   if (InSet == &Abbrev) {
295     // Add to abbreviation list.
296     Abbreviations.push_back(&Abbrev);
297
298     // Assign the vector position + 1 as its number.
299     Abbrev.setNumber(Abbreviations.size());
300   } else {
301     // Assign existing abbreviation number.
302     Abbrev.setNumber(InSet->getNumber());
303   }
304 }
305
306 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
307 /// printer to not emit usual symbol prefix before the symbol name is used then
308 /// return linkage name after skipping this special LLVM prefix.
309 static StringRef getRealLinkageName(StringRef LinkageName) {
310   char One = '\1';
311   if (LinkageName.startswith(StringRef(&One, 1)))
312     return LinkageName.substr(1);
313   return LinkageName;
314 }
315
316 /// createSubprogramDIE - Create new DIE using SP.
317 DIE *DwarfDebug::createSubprogramDIE(DISubprogram SP) {
318   CompileUnit *SPCU = getCompileUnit(SP);
319   DIE *SPDie = SPCU->getDIE(SP);
320   if (SPDie)
321     return SPDie;
322
323   SPDie = new DIE(dwarf::DW_TAG_subprogram);
324   
325   // DW_TAG_inlined_subroutine may refer to this DIE.
326   SPCU->insertDIE(SP, SPDie);
327   
328   // Add to context owner.
329   SPCU->addToContextOwner(SPDie, SP.getContext());
330
331   // Add function template parameters.
332   SPCU->addTemplateParams(*SPDie, SP.getTemplateParams());
333
334   StringRef LinkageName = SP.getLinkageName();
335   if (!LinkageName.empty())
336     SPCU->addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
337                     getRealLinkageName(LinkageName));
338
339   // If this DIE is going to refer declaration info using AT_specification
340   // then there is no need to add other attributes.
341   if (SP.getFunctionDeclaration().isSubprogram())
342     return SPDie;
343
344   // Constructors and operators for anonymous aggregates do not have names.
345   if (!SP.getName().empty())
346     SPCU->addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, 
347                     SP.getName());
348
349   SPCU->addSourceLine(SPDie, SP);
350
351   if (SP.isPrototyped()) 
352     SPCU->addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
353
354   // Add Return Type.
355   DICompositeType SPTy = SP.getType();
356   DIArray Args = SPTy.getTypeArray();
357   unsigned SPTag = SPTy.getTag();
358
359   if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
360     SPCU->addType(SPDie, SPTy);
361   else
362     SPCU->addType(SPDie, DIType(Args.getElement(0)));
363
364   unsigned VK = SP.getVirtuality();
365   if (VK) {
366     SPCU->addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
367     DIEBlock *Block = SPCU->getDIEBlock();
368     SPCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
369     SPCU->addUInt(Block, 0, dwarf::DW_FORM_udata, SP.getVirtualIndex());
370     SPCU->addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
371     ContainingTypeMap.insert(std::make_pair(SPDie,
372                                             SP.getContainingType()));
373   }
374
375   if (!SP.isDefinition()) {
376     SPCU->addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
377     
378     // Add arguments. Do not add arguments for subprogram definition. They will
379     // be handled while processing variables.
380     DICompositeType SPTy = SP.getType();
381     DIArray Args = SPTy.getTypeArray();
382     unsigned SPTag = SPTy.getTag();
383
384     if (SPTag == dwarf::DW_TAG_subroutine_type)
385       for (unsigned i = 1, N =  Args.getNumElements(); i < N; ++i) {
386         DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
387         DIType ATy = DIType(DIType(Args.getElement(i)));
388         SPCU->addType(Arg, ATy);
389         if (ATy.isArtificial())
390           SPCU->addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
391         SPDie->addChild(Arg);
392       }
393   }
394
395   if (SP.isArtificial())
396     SPCU->addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
397
398   if (!SP.isLocalToUnit())
399     SPCU->addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
400
401   if (SP.isOptimized())
402     SPCU->addUInt(SPDie, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
403
404   if (unsigned isa = Asm->getISAEncoding()) {
405     SPCU->addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa);
406   }
407
408   return SPDie;
409 }
410
411 DbgScope *DwarfDebug::getOrCreateAbstractScope(const MDNode *N) {
412   assert(N && "Invalid Scope encoding!");
413
414   DbgScope *AScope = AbstractScopes.lookup(N);
415   if (AScope)
416     return AScope;
417
418   DbgScope *Parent = NULL;
419
420   DIDescriptor Scope(N);
421   if (Scope.isLexicalBlock()) {
422     DILexicalBlock DB(N);
423     DIDescriptor ParentDesc = DB.getContext();
424     Parent = getOrCreateAbstractScope(ParentDesc);
425   }
426   AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
427   AScope->setAbstractScope();
428   AbstractScopes[N] = AScope;
429   if (DIDescriptor(N).isSubprogram())
430     AbstractScopesList.push_back(AScope);
431   return AScope;
432 }
433
434 /// isSubprogramContext - Return true if Context is either a subprogram
435 /// or another context nested inside a subprogram.
436 static bool isSubprogramContext(const MDNode *Context) {
437   if (!Context)
438     return false;
439   DIDescriptor D(Context);
440   if (D.isSubprogram())
441     return true;
442   if (D.isType())
443     return isSubprogramContext(DIType(Context).getContext());
444   return false;
445 }
446
447 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
448 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
449 /// If there are global variables in this scope then create and insert
450 /// DIEs for these variables.
451 DIE *DwarfDebug::updateSubprogramScopeDIE(const MDNode *SPNode) {
452   CompileUnit *SPCU = getCompileUnit(SPNode);
453   DIE *SPDie = SPCU->getDIE(SPNode);
454
455   assert(SPDie && "Unable to find subprogram DIE!");
456   DISubprogram SP(SPNode);
457
458   DISubprogram SPDecl = SP.getFunctionDeclaration();
459   if (SPDecl.isSubprogram())
460     // Refer function declaration directly.
461     SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
462                       createSubprogramDIE(SPDecl));
463   else {
464     // There is not any need to generate specification DIE for a function
465     // defined at compile unit level. If a function is defined inside another
466     // function then gdb prefers the definition at top level and but does not
467     // expect specification DIE in parent function. So avoid creating
468     // specification DIE for a function defined inside a function.
469     if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
470         !SP.getContext().isFile() &&
471         !isSubprogramContext(SP.getContext())) {
472       SPCU-> addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
473       
474       // Add arguments.
475       DICompositeType SPTy = SP.getType();
476       DIArray Args = SPTy.getTypeArray();
477       unsigned SPTag = SPTy.getTag();
478       if (SPTag == dwarf::DW_TAG_subroutine_type)
479         for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
480           DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
481           DIType ATy = DIType(DIType(Args.getElement(i)));
482           SPCU->addType(Arg, ATy);
483           if (ATy.isArtificial())
484             SPCU->addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
485           SPDie->addChild(Arg);
486         }
487       DIE *SPDeclDie = SPDie;
488       SPDie = new DIE(dwarf::DW_TAG_subprogram);
489       SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
490                         SPDeclDie);
491       SPCU->addDie(SPDie);
492     }
493   }
494   // Pick up abstract subprogram DIE.
495   if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
496     SPDie = new DIE(dwarf::DW_TAG_subprogram);
497     SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
498                       dwarf::DW_FORM_ref4, AbsSPDIE);
499     SPCU->addDie(SPDie);
500   }
501
502   SPCU->addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
503                  Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
504   SPCU->addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
505                  Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
506   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
507   MachineLocation Location(RI->getFrameRegister(*Asm->MF));
508   SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
509
510   return SPDie;
511 }
512
513 /// constructLexicalScope - Construct new DW_TAG_lexical_block
514 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
515 DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
516
517   DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
518   if (Scope->isAbstractScope())
519     return ScopeDIE;
520
521   const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
522   if (Ranges.empty())
523     return 0;
524
525   CompileUnit *TheCU = getCompileUnit(Scope->getScopeNode());
526   SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
527   if (Ranges.size() > 1) {
528     // .debug_range section has not been laid out yet. Emit offset in
529     // .debug_range as a uint, size 4, for now. emitDIE will handle
530     // DW_AT_ranges appropriately.
531     TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
532                    DebugRangeSymbols.size() * Asm->getTargetData().getPointerSize());
533     for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
534          RE = Ranges.end(); RI != RE; ++RI) {
535       DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
536       DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
537     }
538     DebugRangeSymbols.push_back(NULL);
539     DebugRangeSymbols.push_back(NULL);
540     return ScopeDIE;
541   }
542
543   const MCSymbol *Start = getLabelBeforeInsn(RI->first);
544   const MCSymbol *End = getLabelAfterInsn(RI->second);
545
546   if (End == 0) return 0;
547
548   assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
549   assert(End->isDefined() && "Invalid end label for an inlined scope!");
550
551   TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
552   TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
553
554   return ScopeDIE;
555 }
556
557 /// constructInlinedScopeDIE - This scope represents inlined body of
558 /// a function. Construct DIE to represent this concrete inlined copy
559 /// of the function.
560 DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
561
562   const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
563   assert (Ranges.empty() == false
564           && "DbgScope does not have instruction markers!");
565
566   if (!Scope->getScopeNode())
567     return NULL;
568   DIScope DS(Scope->getScopeNode());
569   DISubprogram InlinedSP = getDISubprogram(DS);
570   CompileUnit *TheCU = getCompileUnit(InlinedSP);
571   DIE *OriginDIE = TheCU->getDIE(InlinedSP);
572   if (!OriginDIE) {
573     DEBUG(dbgs() << "Unable to find original DIE for inlined subprogram.");
574     return NULL;
575   }
576
577   SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
578   const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
579   const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
580
581   if (StartLabel == 0 || EndLabel == 0) {
582     assert (0 && "Unexpected Start and End labels for a inlined scope!");
583     return 0;
584   }
585   assert(StartLabel->isDefined() &&
586          "Invalid starting label for an inlined scope!");
587   assert(EndLabel->isDefined() &&
588          "Invalid end label for an inlined scope!");
589
590   DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
591   TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
592                      dwarf::DW_FORM_ref4, OriginDIE);
593
594   if (Ranges.size() > 1) {
595     // .debug_range section has not been laid out yet. Emit offset in
596     // .debug_range as a uint, size 4, for now. emitDIE will handle
597     // DW_AT_ranges appropriately.
598     TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
599                    DebugRangeSymbols.size() * Asm->getTargetData().getPointerSize());
600     for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
601          RE = Ranges.end(); RI != RE; ++RI) {
602       DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
603       DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
604     }
605     DebugRangeSymbols.push_back(NULL);
606     DebugRangeSymbols.push_back(NULL);
607   } else {
608     TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, StartLabel);
609     TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, EndLabel);
610   }
611
612   InlinedSubprogramDIEs.insert(OriginDIE);
613
614   // Track the start label for this inlined function.
615   //.debug_inlined section specification does not clearly state how
616   // to emit inlined scope that is split into multiple instruction ranges.
617   // For now, use first instruction range and emit low_pc/high_pc pair and
618   // corresponding .debug_inlined section entry for this pair.
619   DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
620     I = InlineInfo.find(InlinedSP);
621
622   if (I == InlineInfo.end()) {
623     InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel,
624                                                              ScopeDIE));
625     InlinedSPNodes.push_back(InlinedSP);
626   } else
627     I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
628
629   DILocation DL(Scope->getInlinedAt());
630   TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, TheCU->getID());
631   TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
632
633   return ScopeDIE;
634 }
635
636 /// isUnsignedDIType - Return true if type encoding is unsigned.
637 static bool isUnsignedDIType(DIType Ty) {
638   DIDerivedType DTy(Ty);
639   if (DTy.Verify())
640     return isUnsignedDIType(DTy.getTypeDerivedFrom());
641
642   DIBasicType BTy(Ty);
643   if (BTy.Verify()) {
644     unsigned Encoding = BTy.getEncoding();
645     if (Encoding == dwarf::DW_ATE_unsigned ||
646         Encoding == dwarf::DW_ATE_unsigned_char)
647       return true;
648   }
649   return false;
650 }
651
652 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
653 DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
654   StringRef Name = DV->getName();
655   if (Name.empty())
656     return NULL;
657
658   // Translate tag to proper Dwarf tag.  The result variable is dropped for
659   // now.
660   unsigned Tag;
661   switch (DV->getTag()) {
662   case dwarf::DW_TAG_return_variable:
663     return NULL;
664   case dwarf::DW_TAG_arg_variable:
665     Tag = dwarf::DW_TAG_formal_parameter;
666     break;
667   case dwarf::DW_TAG_auto_variable:    // fall thru
668   default:
669     Tag = dwarf::DW_TAG_variable;
670     break;
671   }
672
673   // Define variable debug information entry.
674   DIE *VariableDie = new DIE(Tag);
675   CompileUnit *VariableCU = getCompileUnit(DV->getVariable());
676   DIE *AbsDIE = NULL;
677   DenseMap<const DbgVariable *, const DbgVariable *>::iterator
678     V2AVI = VarToAbstractVarMap.find(DV);
679   if (V2AVI != VarToAbstractVarMap.end())
680     AbsDIE = V2AVI->second->getDIE();
681
682   if (AbsDIE)
683     VariableCU->addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
684                        dwarf::DW_FORM_ref4, AbsDIE);
685   else {
686     VariableCU->addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
687                           Name);
688     VariableCU->addSourceLine(VariableDie, DV->getVariable());
689
690     // Add variable type.
691     VariableCU->addType(VariableDie, DV->getType());
692   }
693
694   if (Tag == dwarf::DW_TAG_formal_parameter && DV->getType().isArtificial())
695     VariableCU->addUInt(VariableDie, dwarf::DW_AT_artificial, 
696                         dwarf::DW_FORM_flag, 1);
697   else if (DIVariable(DV->getVariable()).isArtificial())
698     VariableCU->addUInt(VariableDie, dwarf::DW_AT_artificial, 
699                         dwarf::DW_FORM_flag, 1);
700
701   if (Scope->isAbstractScope()) {
702     DV->setDIE(VariableDie);
703     return VariableDie;
704   }
705
706   // Add variable address.
707
708   unsigned Offset = DV->getDotDebugLocOffset();
709   if (Offset != ~0U) {
710     VariableCU->addLabel(VariableDie, dwarf::DW_AT_location, dwarf::DW_FORM_data4,
711              Asm->GetTempSymbol("debug_loc", Offset));
712     DV->setDIE(VariableDie);
713     UseDotDebugLocEntry.insert(VariableDie);
714     return VariableDie;
715   }
716
717   // Check if variable is described by a  DBG_VALUE instruction.
718   DenseMap<const DbgVariable *, const MachineInstr *>::iterator DVI =
719     DbgVariableToDbgInstMap.find(DV);
720   if (DVI != DbgVariableToDbgInstMap.end()) {
721     const MachineInstr *DVInsn = DVI->second;
722     bool updated = false;
723     if (DVInsn->getNumOperands() == 3) {
724       if (DVInsn->getOperand(0).isReg()) {
725         const MachineOperand RegOp = DVInsn->getOperand(0);
726         const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
727         if (DVInsn->getOperand(1).isImm() &&
728             TRI->getFrameRegister(*Asm->MF) == RegOp.getReg()) {
729           unsigned FrameReg = 0;
730           const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
731           int Offset = 
732             TFI->getFrameIndexReference(*Asm->MF, 
733                                         DVInsn->getOperand(1).getImm(), 
734                                         FrameReg);
735           MachineLocation Location(FrameReg, Offset);
736           VariableCU->addVariableAddress(DV, VariableDie, Location);
737           
738         } else if (RegOp.getReg())
739           VariableCU->addVariableAddress(DV, VariableDie, 
740                                          MachineLocation(RegOp.getReg()));
741         updated = true;
742       }
743       else if (DVInsn->getOperand(0).isImm())
744         updated = 
745           VariableCU->addConstantValue(VariableDie, DVInsn->getOperand(0),
746                                        DV->getType());
747       else if (DVInsn->getOperand(0).isFPImm())
748         updated =
749           VariableCU->addConstantFPValue(VariableDie, DVInsn->getOperand(0));
750       else if (DVInsn->getOperand(0).isCImm())
751         updated =
752           VariableCU->addConstantValue(VariableDie, 
753                                        DVInsn->getOperand(0).getCImm(),
754                                        isUnsignedDIType(DV->getType()));
755     } else {
756       VariableCU->addVariableAddress(DV, VariableDie, 
757                                      Asm->getDebugValueLocation(DVInsn));
758       updated = true;
759     }
760     if (!updated) {
761       // If variableDie is not updated then DBG_VALUE instruction does not
762       // have valid variable info.
763       delete VariableDie;
764       return NULL;
765     }
766     DV->setDIE(VariableDie);
767     return VariableDie;
768   }
769
770   // .. else use frame index, if available.
771   int FI = 0;
772   if (findVariableFrameIndex(DV, &FI)) {
773     unsigned FrameReg = 0;
774     const TargetFrameLowering *TFI = Asm->TM.getFrameLowering();
775     int Offset = 
776       TFI->getFrameIndexReference(*Asm->MF, FI, FrameReg);
777     MachineLocation Location(FrameReg, Offset);
778     VariableCU->addVariableAddress(DV, VariableDie, Location);
779   }
780
781   DV->setDIE(VariableDie);
782   return VariableDie;
783
784 }
785
786 /// constructScopeDIE - Construct a DIE for this scope.
787 DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
788   if (!Scope || !Scope->getScopeNode())
789     return NULL;
790
791   SmallVector <DIE *, 8> Children;
792
793   // Collect arguments for current function.
794   if (Scope == CurrentFnDbgScope)
795     for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
796       if (DbgVariable *ArgDV = CurrentFnArguments[i])
797         if (DIE *Arg = constructVariableDIE(ArgDV, Scope))
798           Children.push_back(Arg);
799
800   // Collect lexical scope childrens first.
801   const SmallVector<DbgVariable *, 8> &Variables = Scope->getDbgVariables();
802   for (unsigned i = 0, N = Variables.size(); i < N; ++i)
803     if (DIE *Variable = constructVariableDIE(Variables[i], Scope))
804       Children.push_back(Variable);
805   const SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
806   for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
807     if (DIE *Nested = constructScopeDIE(Scopes[j]))
808       Children.push_back(Nested);
809   DIScope DS(Scope->getScopeNode());
810   DIE *ScopeDIE = NULL;
811   if (Scope->getInlinedAt())
812     ScopeDIE = constructInlinedScopeDIE(Scope);
813   else if (DS.isSubprogram()) {
814     ProcessedSPNodes.insert(DS);
815     if (Scope->isAbstractScope()) {
816       ScopeDIE = getCompileUnit(DS)->getDIE(DS);
817       // Note down abstract DIE.
818       if (ScopeDIE)
819         AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
820     }
821     else
822       ScopeDIE = updateSubprogramScopeDIE(DS);
823   }
824   else {
825     // There is no need to emit empty lexical block DIE.
826     if (Children.empty())
827       return NULL;
828     ScopeDIE = constructLexicalScopeDIE(Scope);
829   }
830   
831   if (!ScopeDIE) return NULL;
832
833   // Add children
834   for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
835          E = Children.end(); I != E; ++I)
836     ScopeDIE->addChild(*I);
837
838   if (DS.isSubprogram())
839     getCompileUnit(DS)->addPubTypes(DISubprogram(DS));
840
841  return ScopeDIE;
842 }
843
844 /// GetOrCreateSourceID - Look up the source id with the given directory and
845 /// source file names. If none currently exists, create a new id and insert it
846 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
847 /// maps as well.
848
849 unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName, 
850                                          StringRef DirName) {
851   // If FE did not provide a file name, then assume stdin.
852   if (FileName.empty())
853     return GetOrCreateSourceID("<stdin>", StringRef());
854
855   // MCStream expects full path name as filename.
856   if (!DirName.empty() && !sys::path::is_absolute(FileName)) {
857     SmallString<128> FullPathName = DirName;
858     sys::path::append(FullPathName, FileName);
859     // Here FullPathName will be copied into StringMap by GetOrCreateSourceID.
860     return GetOrCreateSourceID(StringRef(FullPathName), StringRef());
861   }
862
863   StringMapEntry<unsigned> &Entry = SourceIdMap.GetOrCreateValue(FileName);
864   if (Entry.getValue())
865     return Entry.getValue();
866
867   unsigned SrcId = SourceIdMap.size();
868   Entry.setValue(SrcId);
869
870   // Print out a .file directive to specify files for .loc directives.
871   Asm->OutStreamer.EmitDwarfFileDirective(SrcId, Entry.getKey());
872
873   return SrcId;
874 }
875
876 /// constructCompileUnit - Create new CompileUnit for the given
877 /// metadata node with tag DW_TAG_compile_unit.
878 void DwarfDebug::constructCompileUnit(const MDNode *N) {
879   DICompileUnit DIUnit(N);
880   StringRef FN = DIUnit.getFilename();
881   StringRef Dir = DIUnit.getDirectory();
882   unsigned ID = GetOrCreateSourceID(FN, Dir);
883
884   DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
885   CompileUnit *NewCU = new CompileUnit(ID, Die, Asm, this);
886   NewCU->addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
887                    DIUnit.getProducer());
888   NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
889                  DIUnit.getLanguage());
890   NewCU->addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
891   // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
892   // simplifies debug range entries.
893   NewCU->addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
894   // DW_AT_stmt_list is a offset of line number information for this
895   // compile unit in debug_line section.
896   if(Asm->MAI->doesDwarfRequireRelocationForSectionOffset())
897     NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
898                     Asm->GetTempSymbol("section_line"));
899   else
900     NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
901
902   if (!Dir.empty())
903     NewCU->addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
904   if (DIUnit.isOptimized())
905     NewCU->addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
906
907   StringRef Flags = DIUnit.getFlags();
908   if (!Flags.empty())
909     NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
910   
911   unsigned RVer = DIUnit.getRunTimeVersion();
912   if (RVer)
913     NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
914             dwarf::DW_FORM_data1, RVer);
915
916   if (!FirstCU)
917     FirstCU = NewCU;
918   CUMap.insert(std::make_pair(N, NewCU));
919 }
920
921 /// getCompileUnit - Get CompileUnit DIE.
922 CompileUnit *DwarfDebug::getCompileUnit(const MDNode *N) const {
923   assert (N && "Invalid DwarfDebug::getCompileUnit argument!");
924   DIDescriptor D(N);
925   const MDNode *CUNode = NULL;
926   if (D.isCompileUnit())
927     CUNode = N;
928   else if (D.isSubprogram())
929     CUNode = DISubprogram(N).getCompileUnit();
930   else if (D.isType())
931     CUNode = DIType(N).getCompileUnit();
932   else if (D.isGlobalVariable())
933     CUNode = DIGlobalVariable(N).getCompileUnit();
934   else if (D.isVariable())
935     CUNode = DIVariable(N).getCompileUnit();
936   else if (D.isNameSpace())
937     CUNode = DINameSpace(N).getCompileUnit();
938   else if (D.isFile())
939     CUNode = DIFile(N).getCompileUnit();
940   else
941     return FirstCU;
942
943   DenseMap<const MDNode *, CompileUnit *>::const_iterator I
944     = CUMap.find(CUNode);
945   if (I == CUMap.end())
946     return FirstCU;
947   return I->second;
948 }
949
950 // Return const expression if value is a GEP to access merged global
951 // constant. e.g.
952 // i8* getelementptr ({ i8, i8, i8, i8 }* @_MergedGlobals, i32 0, i32 0)
953 static const ConstantExpr *getMergedGlobalExpr(const Value *V) {
954   const ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(V);
955   if (!CE || CE->getNumOperands() != 3 ||
956       CE->getOpcode() != Instruction::GetElementPtr)
957     return NULL;
958
959   // First operand points to a global struct.
960   Value *Ptr = CE->getOperand(0);
961   if (!isa<GlobalValue>(Ptr) ||
962       !isa<StructType>(cast<PointerType>(Ptr->getType())->getElementType()))
963     return NULL;
964
965   // Second operand is zero.
966   const ConstantInt *CI = dyn_cast_or_null<ConstantInt>(CE->getOperand(1));
967   if (!CI || !CI->isZero())
968     return NULL;
969
970   // Third operand is offset.
971   if (!isa<ConstantInt>(CE->getOperand(2)))
972     return NULL;
973
974   return CE;
975 }
976
977 /// constructGlobalVariableDIE - Construct global variable DIE.
978 void DwarfDebug::constructGlobalVariableDIE(const MDNode *N) {
979   DIGlobalVariable GV(N);
980
981   // If debug information is malformed then ignore it.
982   if (GV.Verify() == false)
983     return;
984
985   // Check for pre-existence.
986   CompileUnit *TheCU = getCompileUnit(N);
987   if (TheCU->getDIE(GV))
988     return;
989
990   DIType GTy = GV.getType();
991   DIE *VariableDIE = new DIE(GV.getTag());
992
993   bool isGlobalVariable = GV.getGlobal() != NULL;
994
995   // Add name.
996   TheCU->addString(VariableDIE, dwarf::DW_AT_name, dwarf::DW_FORM_string,
997                    GV.getDisplayName());
998   StringRef LinkageName = GV.getLinkageName();
999   if (!LinkageName.empty() && isGlobalVariable)
1000     TheCU->addString(VariableDIE, dwarf::DW_AT_MIPS_linkage_name, 
1001                      dwarf::DW_FORM_string,
1002                      getRealLinkageName(LinkageName));
1003   // Add type.
1004   TheCU->addType(VariableDIE, GTy);
1005
1006   // Add scoping info.
1007   if (!GV.isLocalToUnit()) {
1008     TheCU->addUInt(VariableDIE, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1009     // Expose as global. 
1010     TheCU->addGlobal(GV.getName(), VariableDIE);
1011   }
1012   // Add line number info.
1013   TheCU->addSourceLine(VariableDIE, GV);
1014   // Add to map.
1015   TheCU->insertDIE(N, VariableDIE);
1016   // Add to context owner.
1017   DIDescriptor GVContext = GV.getContext();
1018   TheCU->addToContextOwner(VariableDIE, GVContext);
1019   // Add location.
1020   if (isGlobalVariable) {
1021     DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1022     TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1023     TheCU->addLabel(Block, 0, dwarf::DW_FORM_udata,
1024              Asm->Mang->getSymbol(GV.getGlobal()));
1025     // Do not create specification DIE if context is either compile unit
1026     // or a subprogram.
1027     if (GV.isDefinition() && !GVContext.isCompileUnit() &&
1028         !GVContext.isFile() && !isSubprogramContext(GVContext)) {
1029       // Create specification DIE.
1030       DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1031       TheCU->addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1032                   dwarf::DW_FORM_ref4, VariableDIE);
1033       TheCU->addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1034       TheCU->addUInt(VariableDIE, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1035       TheCU->addDie(VariableSpecDIE);
1036     } else {
1037       TheCU->addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1038     } 
1039   } else if (const ConstantInt *CI = 
1040              dyn_cast_or_null<ConstantInt>(GV.getConstant()))
1041     TheCU->addConstantValue(VariableDIE, CI, isUnsignedDIType(GTy));
1042   else if (const ConstantExpr *CE = getMergedGlobalExpr(N->getOperand(11))) {
1043     // GV is a merged global.
1044     DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1045     Value *Ptr = CE->getOperand(0);
1046     TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1047     TheCU->addLabel(Block, 0, dwarf::DW_FORM_udata,
1048                     Asm->Mang->getSymbol(cast<GlobalValue>(Ptr)));
1049     TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1050     SmallVector<Value*, 3> Idx(CE->op_begin()+1, CE->op_end());
1051     TheCU->addUInt(Block, 0, dwarf::DW_FORM_udata, 
1052                    Asm->getTargetData().getIndexedOffset(Ptr->getType(), Idx));
1053     TheCU->addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1054     TheCU->addBlock(VariableDIE, dwarf::DW_AT_location, 0, Block);
1055   }
1056
1057   return;
1058 }
1059
1060 /// construct SubprogramDIE - Construct subprogram DIE.
1061 void DwarfDebug::constructSubprogramDIE(const MDNode *N) {
1062   DISubprogram SP(N);
1063
1064   // Check for pre-existence.
1065   CompileUnit *TheCU = getCompileUnit(N);
1066   if (TheCU->getDIE(N))
1067     return;
1068
1069   if (!SP.isDefinition())
1070     // This is a method declaration which will be handled while constructing
1071     // class type.
1072     return;
1073
1074   DIE *SubprogramDie = createSubprogramDIE(SP);
1075
1076   // Add to map.
1077   TheCU->insertDIE(N, SubprogramDie);
1078
1079   // Add to context owner.
1080   TheCU->addToContextOwner(SubprogramDie, SP.getContext());
1081
1082   // Expose as global.
1083   TheCU->addGlobal(SP.getName(), SubprogramDie);
1084
1085   return;
1086 }
1087
1088 /// beginModule - Emit all Dwarf sections that should come prior to the
1089 /// content. Create global DIEs and emit initial debug info sections.
1090 /// This is invoked by the target AsmPrinter.
1091 void DwarfDebug::beginModule(Module *M) {
1092   if (DisableDebugInfoPrinting)
1093     return;
1094
1095   // If module has named metadata anchors then use them, otherwise scan the
1096   // module using debug info finder to collect debug info.
1097   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
1098   if (CU_Nodes) {
1099
1100     NamedMDNode *GV_Nodes = M->getNamedMetadata("llvm.dbg.gv");
1101     NamedMDNode *SP_Nodes = M->getNamedMetadata("llvm.dbg.sp");
1102     if (!GV_Nodes && !SP_Nodes)
1103       // If there are not any global variables or any functions then
1104       // there is not any debug info in this module.
1105       return;
1106
1107     for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i)
1108       constructCompileUnit(CU_Nodes->getOperand(i));
1109
1110     if (GV_Nodes)
1111       for (unsigned i = 0, e = GV_Nodes->getNumOperands(); i != e; ++i)
1112         constructGlobalVariableDIE(GV_Nodes->getOperand(i));
1113
1114     if (SP_Nodes)
1115       for (unsigned i = 0, e = SP_Nodes->getNumOperands(); i != e; ++i)
1116         constructSubprogramDIE(SP_Nodes->getOperand(i));
1117     
1118   } else {
1119
1120     DebugInfoFinder DbgFinder;
1121     DbgFinder.processModule(*M);
1122     
1123     bool HasDebugInfo = false;
1124     // Scan all the compile-units to see if there are any marked as the main
1125     // unit. If not, we do not generate debug info.
1126     for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1127            E = DbgFinder.compile_unit_end(); I != E; ++I) {
1128       if (DICompileUnit(*I).isMain()) {
1129         HasDebugInfo = true;
1130         break;
1131       }
1132     }
1133     if (!HasDebugInfo) return;
1134     
1135     // Create all the compile unit DIEs.
1136     for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1137            E = DbgFinder.compile_unit_end(); I != E; ++I)
1138       constructCompileUnit(*I);
1139     
1140     // Create DIEs for each global variable.
1141     for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1142            E = DbgFinder.global_variable_end(); I != E; ++I)
1143       constructGlobalVariableDIE(*I);
1144     
1145     // Create DIEs for each subprogram.
1146     for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1147            E = DbgFinder.subprogram_end(); I != E; ++I)
1148       constructSubprogramDIE(*I);
1149   }
1150   
1151   // Tell MMI that we have debug info.
1152   MMI->setDebugInfoAvailability(true);
1153   
1154   // Emit initial sections.
1155   EmitSectionLabels();
1156
1157   //getOrCreateTypeDIE
1158   if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
1159     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1160       DIType Ty(NMD->getOperand(i));
1161       getCompileUnit(Ty)->getOrCreateTypeDIE(Ty);
1162     }
1163
1164   if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
1165     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1166       DIType Ty(NMD->getOperand(i));
1167       getCompileUnit(Ty)->getOrCreateTypeDIE(Ty);
1168     }
1169
1170   // Prime section data.
1171   SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1172 }
1173
1174 /// endModule - Emit all Dwarf sections that should come after the content.
1175 ///
1176 void DwarfDebug::endModule() {
1177   if (!FirstCU) return;
1178   const Module *M = MMI->getModule();
1179   DenseMap<const MDNode *, DbgScope *> DeadFnScopeMap;
1180   if (NamedMDNode *AllSPs = M->getNamedMetadata("llvm.dbg.sp")) {
1181     for (unsigned SI = 0, SE = AllSPs->getNumOperands(); SI != SE; ++SI) {
1182       if (ProcessedSPNodes.count(AllSPs->getOperand(SI)) != 0) continue;
1183       DISubprogram SP(AllSPs->getOperand(SI));
1184       if (!SP.Verify()) continue;
1185
1186       // Collect info for variables that were optimized out.
1187       if (!SP.isDefinition()) continue;
1188       StringRef FName = SP.getLinkageName();
1189       if (FName.empty())
1190         FName = SP.getName();
1191       NamedMDNode *NMD = getFnSpecificMDNode(*(MMI->getModule()), FName);
1192       if (!NMD) continue;
1193       unsigned E = NMD->getNumOperands();
1194       if (!E) continue;
1195       DbgScope *Scope = new DbgScope(NULL, DIDescriptor(SP), NULL);
1196       DeadFnScopeMap[SP] = Scope;
1197       for (unsigned I = 0; I != E; ++I) {
1198         DIVariable DV(NMD->getOperand(I));
1199         if (!DV.Verify()) continue;
1200         Scope->addVariable(new DbgVariable(DV));
1201       }
1202
1203       // Construct subprogram DIE and add variables DIEs.
1204       constructSubprogramDIE(SP);
1205       DIE *ScopeDIE = getCompileUnit(SP)->getDIE(SP);
1206       const SmallVector<DbgVariable *, 8> &Variables = Scope->getDbgVariables();
1207       for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1208         DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
1209         if (VariableDIE)
1210           ScopeDIE->addChild(VariableDIE);
1211       }
1212     }
1213   }
1214
1215   // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1216   for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
1217          AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
1218     DIE *ISP = *AI;
1219     FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
1220   }
1221
1222   for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
1223          CE = ContainingTypeMap.end(); CI != CE; ++CI) {
1224     DIE *SPDie = CI->first;
1225     const MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
1226     if (!N) continue;
1227     DIE *NDie = getCompileUnit(N)->getDIE(N);
1228     if (!NDie) continue;
1229     getCompileUnit(N)->addDIEEntry(SPDie, dwarf::DW_AT_containing_type, 
1230                                    dwarf::DW_FORM_ref4, NDie);
1231   }
1232
1233   // Standard sections final addresses.
1234   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1235   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
1236   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1237   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
1238
1239   // End text sections.
1240   for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
1241     Asm->OutStreamer.SwitchSection(SectionMap[i]);
1242     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
1243   }
1244
1245   // Compute DIE offsets and sizes.
1246   computeSizeAndOffsets();
1247
1248   // Emit all the DIEs into a debug info section
1249   emitDebugInfo();
1250
1251   // Corresponding abbreviations into a abbrev section.
1252   emitAbbreviations();
1253
1254   // Emit info into a debug pubnames section.
1255   emitDebugPubNames();
1256
1257   // Emit info into a debug pubtypes section.
1258   emitDebugPubTypes();
1259
1260   // Emit info into a debug loc section.
1261   emitDebugLoc();
1262
1263   // Emit info into a debug aranges section.
1264   EmitDebugARanges();
1265
1266   // Emit info into a debug ranges section.
1267   emitDebugRanges();
1268
1269   // Emit info into a debug macinfo section.
1270   emitDebugMacInfo();
1271
1272   // Emit inline info.
1273   emitDebugInlineInfo();
1274
1275   // Emit info into a debug str section.
1276   emitDebugStr();
1277
1278   // clean up.
1279   DeleteContainerSeconds(DeadFnScopeMap);
1280   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1281          E = CUMap.end(); I != E; ++I)
1282     delete I->second;
1283   FirstCU = NULL;  // Reset for the next Module, if any.
1284 }
1285
1286 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
1287 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
1288                                               DebugLoc ScopeLoc) {
1289
1290   DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1291   if (AbsDbgVariable)
1292     return AbsDbgVariable;
1293
1294   LLVMContext &Ctx = Var->getContext();
1295   DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
1296   if (!Scope)
1297     return NULL;
1298
1299   AbsDbgVariable = new DbgVariable(Var);
1300   Scope->addVariable(AbsDbgVariable);
1301   AbstractVariables[Var] = AbsDbgVariable;
1302   return AbsDbgVariable;
1303 }
1304
1305 /// addCurrentFnArgument - If Var is a current function argument then add
1306 /// it to CurrentFnArguments list.
1307 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1308                                       DbgVariable *Var, DbgScope *Scope) {
1309   if (Scope != CurrentFnDbgScope) 
1310     return false;
1311   DIVariable DV = Var->getVariable();
1312   if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1313     return false;
1314   unsigned ArgNo = DV.getArgNumber();
1315   if (ArgNo == 0) 
1316     return false;
1317
1318   size_t Size = CurrentFnArguments.size();
1319   if (Size == 0)
1320     CurrentFnArguments.resize(MF->getFunction()->arg_size());
1321   // llvm::Function argument size is not good indicator of how many
1322   // arguments does the function have at source level.
1323   if (ArgNo > Size)
1324     CurrentFnArguments.resize(ArgNo * 2);
1325   CurrentFnArguments[ArgNo - 1] = Var;
1326   return true;
1327 }
1328
1329 /// collectVariableInfoFromMMITable - Collect variable information from
1330 /// side table maintained by MMI.
1331 void
1332 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1333                                    SmallPtrSet<const MDNode *, 16> &Processed) {
1334   MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1335   for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1336          VE = VMap.end(); VI != VE; ++VI) {
1337     const MDNode *Var = VI->first;
1338     if (!Var) continue;
1339     Processed.insert(Var);
1340     DIVariable DV(Var);
1341     const std::pair<unsigned, DebugLoc> &VP = VI->second;
1342
1343     DbgScope *Scope = findDbgScope(VP.second);
1344
1345     // If variable scope is not found then skip this variable.
1346     if (Scope == 0)
1347       continue;
1348
1349     DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1350     DbgVariable *RegVar = new DbgVariable(DV);
1351     recordVariableFrameIndex(RegVar, VP.first);
1352     if (!addCurrentFnArgument(MF, RegVar, Scope))
1353       Scope->addVariable(RegVar);
1354     if (AbsDbgVariable) {
1355       recordVariableFrameIndex(AbsDbgVariable, VP.first);
1356       VarToAbstractVarMap[RegVar] = AbsDbgVariable;
1357     }
1358   }
1359 }
1360
1361 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
1362 /// DBG_VALUE instruction, is in a defined reg.
1363 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1364   assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1365   return MI->getNumOperands() == 3 &&
1366          MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1367          MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
1368 }
1369
1370 /// getDebugLocEntry - Get .debug_loc entry for the instruction range starting
1371 /// at MI.
1372 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm, 
1373                                          const MCSymbol *FLabel, 
1374                                          const MCSymbol *SLabel,
1375                                          const MachineInstr *MI) {
1376   const MDNode *Var =  MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1377
1378   if (MI->getNumOperands() != 3) {
1379     MachineLocation MLoc = Asm->getDebugValueLocation(MI);
1380     return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1381   }
1382   if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
1383     MachineLocation MLoc;
1384     MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1385     return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1386   }
1387   if (MI->getOperand(0).isImm())
1388     return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1389   if (MI->getOperand(0).isFPImm())
1390     return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1391   if (MI->getOperand(0).isCImm())
1392     return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1393
1394   assert (0 && "Unexpected 3 operand DBG_VALUE instruction!");
1395   return DotDebugLocEntry();
1396 }
1397
1398 /// collectVariableInfo - Populate DbgScope entries with variables' info.
1399 void
1400 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1401                                 SmallPtrSet<const MDNode *, 16> &Processed) {
1402
1403   /// collection info from MMI table.
1404   collectVariableInfoFromMMITable(MF, Processed);
1405
1406   for (SmallVectorImpl<const MDNode*>::const_iterator
1407          UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1408          ++UVI) {
1409     const MDNode *Var = *UVI;
1410     if (Processed.count(Var))
1411       continue;
1412
1413     // History contains relevant DBG_VALUE instructions for Var and instructions
1414     // clobbering it.
1415     SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1416     if (History.empty())
1417       continue;
1418     const MachineInstr *MInsn = History.front();
1419
1420     DIVariable DV(Var);
1421     DbgScope *Scope = NULL;
1422     if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1423         DISubprogram(DV.getContext()).describes(MF->getFunction()))
1424       Scope = CurrentFnDbgScope;
1425     else {
1426       if (DV.getVersion() <= LLVMDebugVersion9)
1427         Scope = findDbgScope(MInsn->getDebugLoc());
1428       else {
1429         if (MDNode *IA = DV.getInlinedAt())
1430           Scope = InlinedDbgScopeMap.lookup(DebugLoc::getFromDILocation(IA));
1431         else
1432           Scope = DbgScopeMap.lookup(cast<MDNode>(DV->getOperand(1)));
1433       }
1434     }
1435     // If variable scope is not found then skip this variable.
1436     if (!Scope)
1437       continue;
1438
1439     Processed.insert(DV);
1440     assert(MInsn->isDebugValue() && "History must begin with debug value");
1441     DbgVariable *RegVar = new DbgVariable(DV);
1442     if (!addCurrentFnArgument(MF, RegVar, Scope))
1443       Scope->addVariable(RegVar);
1444     if (DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc())) {
1445       DbgVariableToDbgInstMap[AbsVar] = MInsn;
1446       VarToAbstractVarMap[RegVar] = AbsVar;
1447     }
1448
1449     // Simple ranges that are fully coalesced.
1450     if (History.size() <= 1 || (History.size() == 2 &&
1451                                 MInsn->isIdenticalTo(History.back()))) {
1452       DbgVariableToDbgInstMap[RegVar] = MInsn;
1453       continue;
1454     }
1455
1456     // handle multiple DBG_VALUE instructions describing one variable.
1457     RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1458
1459     for (SmallVectorImpl<const MachineInstr*>::const_iterator
1460            HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1461       const MachineInstr *Begin = *HI;
1462       assert(Begin->isDebugValue() && "Invalid History entry");
1463
1464       // Check if DBG_VALUE is truncating a range.
1465       if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1466           && !Begin->getOperand(0).getReg())
1467         continue;
1468
1469       // Compute the range for a register location.
1470       const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1471       const MCSymbol *SLabel = 0;
1472
1473       if (HI + 1 == HE)
1474         // If Begin is the last instruction in History then its value is valid
1475         // until the end of the function.
1476         SLabel = FunctionEndSym;
1477       else {
1478         const MachineInstr *End = HI[1];
1479         DEBUG(dbgs() << "DotDebugLoc Pair:\n" 
1480               << "\t" << *Begin << "\t" << *End << "\n");
1481         if (End->isDebugValue())
1482           SLabel = getLabelBeforeInsn(End);
1483         else {
1484           // End is a normal instruction clobbering the range.
1485           SLabel = getLabelAfterInsn(End);
1486           assert(SLabel && "Forgot label after clobber instruction");
1487           ++HI;
1488         }
1489       }
1490
1491       // The value is valid until the next DBG_VALUE or clobber.
1492       DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1493     }
1494     DotDebugLocEntries.push_back(DotDebugLocEntry());
1495   }
1496
1497   // Collect info for variables that were optimized out.
1498   const Function *F = MF->getFunction();
1499   if (NamedMDNode *NMD = getFnSpecificMDNode(*(F->getParent()), F->getName())) {
1500     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1501       DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
1502       if (!DV || !Processed.insert(DV))
1503         continue;
1504       DbgScope *Scope = DbgScopeMap.lookup(DV.getContext());
1505       if (Scope)
1506         Scope->addVariable(new DbgVariable(DV));
1507     }
1508   }
1509 }
1510
1511 /// getLabelBeforeInsn - Return Label preceding the instruction.
1512 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1513   MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1514   assert(Label && "Didn't insert label before instruction");
1515   return Label;
1516 }
1517
1518 /// getLabelAfterInsn - Return Label immediately following the instruction.
1519 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1520   return LabelsAfterInsn.lookup(MI);
1521 }
1522
1523 /// beginInstruction - Process beginning of an instruction.
1524 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1525   // Check if source location changes, but ignore DBG_VALUE locations.
1526   if (!MI->isDebugValue()) {
1527     DebugLoc DL = MI->getDebugLoc();
1528     if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1529       unsigned Flags = DWARF2_FLAG_IS_STMT;
1530       PrevInstLoc = DL;
1531       if (DL == PrologEndLoc) {
1532         Flags |= DWARF2_FLAG_PROLOGUE_END;
1533         PrologEndLoc = DebugLoc();
1534       }
1535       if (!DL.isUnknown()) {
1536         const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1537         recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1538       } else
1539         recordSourceLine(0, 0, 0, 0);
1540     }
1541   }
1542
1543   // Insert labels where requested.
1544   DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1545     LabelsBeforeInsn.find(MI);
1546
1547   // No label needed.
1548   if (I == LabelsBeforeInsn.end())
1549     return;
1550
1551   // Label already assigned.
1552   if (I->second)
1553     return;
1554
1555   if (!PrevLabel) {
1556     PrevLabel = MMI->getContext().CreateTempSymbol();
1557     Asm->OutStreamer.EmitLabel(PrevLabel);
1558   }
1559   I->second = PrevLabel;
1560 }
1561
1562 /// endInstruction - Process end of an instruction.
1563 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1564   // Don't create a new label after DBG_VALUE instructions.
1565   // They don't generate code.
1566   if (!MI->isDebugValue())
1567     PrevLabel = 0;
1568
1569   DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1570     LabelsAfterInsn.find(MI);
1571
1572   // No label needed.
1573   if (I == LabelsAfterInsn.end())
1574     return;
1575
1576   // Label already assigned.
1577   if (I->second)
1578     return;
1579
1580   // We need a label after this instruction.
1581   if (!PrevLabel) {
1582     PrevLabel = MMI->getContext().CreateTempSymbol();
1583     Asm->OutStreamer.EmitLabel(PrevLabel);
1584   }
1585   I->second = PrevLabel;
1586 }
1587
1588 /// getOrCreateRegularScope - Create regular DbgScope.
1589 DbgScope *DwarfDebug::getOrCreateRegularScope(MDNode *Scope) {
1590   DbgScope *WScope = DbgScopeMap.lookup(Scope);
1591   if (WScope) 
1592     return WScope;
1593
1594   DbgScope *Parent = NULL;
1595   if (DIDescriptor(Scope).isLexicalBlock())
1596     Parent = getOrCreateDbgScope(DebugLoc::getFromDILexicalBlock(Scope));
1597   WScope = new DbgScope(Parent, DIDescriptor(Scope), NULL);
1598   DbgScopeMap.insert(std::make_pair(Scope, WScope));
1599   if (!Parent && DIDescriptor(Scope).isSubprogram()
1600       && DISubprogram(Scope).describes(Asm->MF->getFunction()))
1601     CurrentFnDbgScope = WScope;
1602   
1603   return WScope;
1604 }
1605
1606 /// getOrCreateInlinedScope - Create inlined scope. 
1607 DbgScope *DwarfDebug::getOrCreateInlinedScope(MDNode *Scope, MDNode *InlinedAt){
1608   DbgScope *InlinedScope = DbgScopeMap.lookup(InlinedAt);
1609   if (InlinedScope)
1610     return InlinedScope;
1611
1612   DebugLoc InlinedLoc = DebugLoc::getFromDILocation(InlinedAt);
1613   InlinedScope = new DbgScope(getOrCreateDbgScope(InlinedLoc),
1614                               DIDescriptor(Scope), InlinedAt);
1615   InlinedDbgScopeMap[InlinedLoc] = InlinedScope;
1616   DbgScopeMap[InlinedAt] = InlinedScope;
1617   return InlinedScope;
1618 }
1619
1620 /// getOrCreateDbgScope - Create DbgScope for the scope.
1621 DbgScope *DwarfDebug::getOrCreateDbgScope(DebugLoc DL) {
1622   LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
1623   MDNode *Scope = NULL;
1624   MDNode *InlinedAt = NULL;
1625   DL.getScopeAndInlinedAt(Scope, InlinedAt, Ctx);
1626   if (!InlinedAt) 
1627     return getOrCreateRegularScope(Scope);
1628
1629   // Create an abstract scope for inlined function.
1630   getOrCreateAbstractScope(Scope);
1631   // Create an inlined scope for inlined function.
1632   return getOrCreateInlinedScope(Scope, InlinedAt);
1633 }
1634
1635 /// calculateDominanceGraph - Calculate dominance graph for DbgScope
1636 /// hierarchy.
1637 static void calculateDominanceGraph(DbgScope *Scope) {
1638   assert (Scope && "Unable to calculate scop edominance graph!");
1639   SmallVector<DbgScope *, 4> WorkStack;
1640   WorkStack.push_back(Scope);
1641   unsigned Counter = 0;
1642   while (!WorkStack.empty()) {
1643     DbgScope *WS = WorkStack.back();
1644     const SmallVector<DbgScope *, 4> &Children = WS->getScopes();
1645     bool visitedChildren = false;
1646     for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
1647            SE = Children.end(); SI != SE; ++SI) {
1648       DbgScope *ChildScope = *SI;
1649       if (!ChildScope->getDFSOut()) {
1650         WorkStack.push_back(ChildScope);
1651         visitedChildren = true;
1652         ChildScope->setDFSIn(++Counter);
1653 #ifndef NDEBUG
1654         if (PrintDbgScope)
1655           dbgs() << "calculate dbgscope dom: In " << Counter << "\n";
1656 #endif
1657         break;
1658       }
1659     }
1660     if (!visitedChildren) {
1661       WorkStack.pop_back();
1662       WS->setDFSOut(++Counter);
1663 #ifndef NDEBUG
1664       if (PrintDbgScope)
1665         dbgs() << "calculate dbgscope dom: In " << WS->getDFSIn() 
1666                << " Out " << Counter << "\n";
1667 #endif
1668     }
1669   }
1670 }
1671
1672 /// printDbgScopeInfo - Print DbgScope info for each machine instruction.
1673 static
1674 void printDbgScopeInfo(const MachineFunction *MF,
1675                        DenseMap<const MachineInstr *, DbgScope *> &MI2ScopeMap)
1676 {
1677 #ifndef NDEBUG
1678   LLVMContext &Ctx = MF->getFunction()->getContext();
1679   unsigned PrevDFSIn = 0;
1680   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1681        I != E; ++I) {
1682     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1683          II != IE; ++II) {
1684       const MachineInstr *MInsn = II;
1685       MDNode *Scope = NULL;
1686       MDNode *InlinedAt = NULL;
1687
1688       // Check if instruction has valid location information.
1689       DebugLoc MIDL = MInsn->getDebugLoc();
1690       if (!MIDL.isUnknown()) {
1691         MIDL.getScopeAndInlinedAt(Scope, InlinedAt, Ctx);
1692         dbgs() << " [ ";
1693         if (InlinedAt)
1694           dbgs() << "*";
1695         DenseMap<const MachineInstr *, DbgScope *>::iterator DI =
1696           MI2ScopeMap.find(MInsn);
1697         if (DI != MI2ScopeMap.end()) {
1698           DbgScope *S = DI->second;
1699           dbgs() << S->getDFSIn();
1700           PrevDFSIn = S->getDFSIn();
1701         } else
1702           dbgs() << PrevDFSIn;
1703       } else
1704         dbgs() << " [ x" << PrevDFSIn;
1705       dbgs() << " ]";
1706       MInsn->dump();
1707     }
1708     dbgs() << "\n";
1709   }
1710 #endif
1711 }
1712 /// extractScopeInformation - Scan machine instructions in this function
1713 /// and collect DbgScopes. Return true, if at least one scope was found.
1714 bool DwarfDebug::extractScopeInformation() {
1715   // If scope information was extracted using .dbg intrinsics then there is not
1716   // any need to extract these information by scanning each instruction.
1717   if (!DbgScopeMap.empty())
1718     return false;
1719
1720   // Scan each instruction and create scopes. First build working set of scopes.
1721   SmallVector<DbgRange, 4> MIRanges;
1722   DenseMap<const MachineInstr *, DbgScope *> MI2ScopeMap;
1723   for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
1724        I != E; ++I) {
1725     const MachineInstr *RangeBeginMI = NULL;
1726     const MachineInstr *PrevMI = NULL;
1727     DebugLoc PrevDL;
1728     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1729          II != IE; ++II) {
1730       const MachineInstr *MInsn = II;
1731
1732       // Check if instruction has valid location information.
1733       const DebugLoc MIDL = MInsn->getDebugLoc();
1734       if (MIDL.isUnknown()) {
1735         PrevMI = MInsn;
1736         continue;
1737       }
1738
1739       // If scope has not changed then skip this instruction.
1740       if (MIDL == PrevDL) {
1741         PrevMI = MInsn;
1742         continue;
1743       }
1744
1745       // Ignore DBG_VALUE. It does not contribute to any instruction in output.
1746       if (MInsn->isDebugValue())
1747         continue;
1748
1749       if (RangeBeginMI) {
1750         // If we have already seen a beginning of an instruction range and
1751         // current instruction scope does not match scope of first instruction
1752         // in this range then create a new instruction range.
1753         DEBUG(dbgs() << "Creating new instruction range :\n");
1754         DEBUG(dbgs() << "Begin Range at " << *RangeBeginMI);
1755         DEBUG(dbgs() << "End Range at " << *PrevMI);
1756         DEBUG(dbgs() << "Next Range starting at " << *MInsn);
1757         DEBUG(dbgs() << "------------------------\n");
1758         DbgRange R(RangeBeginMI, PrevMI);
1759         MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevDL);
1760         MIRanges.push_back(R);
1761       }
1762
1763       // This is a beginning of a new instruction range.
1764       RangeBeginMI = MInsn;
1765
1766       // Reset previous markers.
1767       PrevMI = MInsn;
1768       PrevDL = MIDL;
1769     }
1770
1771     // Create last instruction range.
1772     if (RangeBeginMI && PrevMI && !PrevDL.isUnknown()) {
1773       DbgRange R(RangeBeginMI, PrevMI);
1774       MIRanges.push_back(R);
1775       MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevDL);
1776     }
1777   }
1778
1779   if (!CurrentFnDbgScope)
1780     return false;
1781
1782   calculateDominanceGraph(CurrentFnDbgScope);
1783   if (PrintDbgScope)
1784     printDbgScopeInfo(Asm->MF, MI2ScopeMap);
1785
1786   // Find ranges of instructions covered by each DbgScope;
1787   DbgScope *PrevDbgScope = NULL;
1788   for (SmallVector<DbgRange, 4>::const_iterator RI = MIRanges.begin(),
1789          RE = MIRanges.end(); RI != RE; ++RI) {
1790     const DbgRange &R = *RI;
1791     DbgScope *S = MI2ScopeMap.lookup(R.first);
1792     assert (S && "Lost DbgScope for a machine instruction!");
1793     if (PrevDbgScope && !PrevDbgScope->dominates(S))
1794       PrevDbgScope->closeInsnRange(S);
1795     S->openInsnRange(R.first);
1796     S->extendInsnRange(R.second);
1797     PrevDbgScope = S;
1798   }
1799
1800   if (PrevDbgScope)
1801     PrevDbgScope->closeInsnRange();
1802
1803   identifyScopeMarkers();
1804
1805   return !DbgScopeMap.empty();
1806 }
1807
1808 /// identifyScopeMarkers() -
1809 /// Each DbgScope has first instruction and last instruction to mark beginning
1810 /// and end of a scope respectively. Create an inverse map that list scopes
1811 /// starts (and ends) with an instruction. One instruction may start (or end)
1812 /// multiple scopes. Ignore scopes that are not reachable.
1813 void DwarfDebug::identifyScopeMarkers() {
1814   SmallVector<DbgScope *, 4> WorkList;
1815   WorkList.push_back(CurrentFnDbgScope);
1816   while (!WorkList.empty()) {
1817     DbgScope *S = WorkList.pop_back_val();
1818
1819     const SmallVector<DbgScope *, 4> &Children = S->getScopes();
1820     if (!Children.empty())
1821       for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
1822              SE = Children.end(); SI != SE; ++SI)
1823         WorkList.push_back(*SI);
1824
1825     if (S->isAbstractScope())
1826       continue;
1827
1828     const SmallVector<DbgRange, 4> &Ranges = S->getRanges();
1829     if (Ranges.empty())
1830       continue;
1831     for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
1832            RE = Ranges.end(); RI != RE; ++RI) {
1833       assert(RI->first && "DbgRange does not have first instruction!");
1834       assert(RI->second && "DbgRange does not have second instruction!");
1835       requestLabelBeforeInsn(RI->first);
1836       requestLabelAfterInsn(RI->second);
1837     }
1838   }
1839 }
1840
1841 /// getScopeNode - Get MDNode for DebugLoc's scope.
1842 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1843   if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1844     return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1845   return DL.getScope(Ctx);
1846 }
1847
1848 /// getFnDebugLoc - Walk up the scope chain of given debug loc and find
1849 /// line number  info for the function.
1850 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1851   const MDNode *Scope = getScopeNode(DL, Ctx);
1852   DISubprogram SP = getDISubprogram(Scope);
1853   if (SP.Verify()) 
1854     return DebugLoc::get(SP.getLineNumber(), 0, SP);
1855   return DebugLoc();
1856 }
1857
1858 /// beginFunction - Gather pre-function debug information.  Assumes being
1859 /// emitted immediately after the function entry point.
1860 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1861   if (!MMI->hasDebugInfo()) return;
1862   if (!extractScopeInformation()) return;
1863
1864   FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1865                                         Asm->getFunctionNumber());
1866   // Assumes in correct section after the entry point.
1867   Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1868
1869   assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1870
1871   const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1872   /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1873   std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1874
1875   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1876        I != E; ++I) {
1877     bool AtBlockEntry = true;
1878     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1879          II != IE; ++II) {
1880       const MachineInstr *MI = II;
1881
1882       if (MI->isDebugValue()) {
1883         assert (MI->getNumOperands() > 1 && "Invalid machine instruction!");
1884
1885         // Keep track of user variables.
1886         const MDNode *Var =
1887           MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1888
1889         // Variable is in a register, we need to check for clobbers.
1890         if (isDbgValueInDefinedReg(MI))
1891           LiveUserVar[MI->getOperand(0).getReg()] = Var;
1892
1893         // Check the history of this variable.
1894         SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1895         if (History.empty()) {
1896           UserVariables.push_back(Var);
1897           // The first mention of a function argument gets the FunctionBeginSym
1898           // label, so arguments are visible when breaking at function entry.
1899           DIVariable DV(Var);
1900           if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1901               DISubprogram(getDISubprogram(DV.getContext()))
1902                 .describes(MF->getFunction()))
1903             LabelsBeforeInsn[MI] = FunctionBeginSym;
1904         } else {
1905           // We have seen this variable before. Try to coalesce DBG_VALUEs.
1906           const MachineInstr *Prev = History.back();
1907           if (Prev->isDebugValue()) {
1908             // Coalesce identical entries at the end of History.
1909             if (History.size() >= 2 &&
1910                 Prev->isIdenticalTo(History[History.size() - 2])) {
1911               DEBUG(dbgs() << "Coalesce identical DBG_VALUE entries:\n"
1912                     << "\t" << *Prev 
1913                     << "\t" << *History[History.size() - 2] << "\n");
1914               History.pop_back();
1915             }
1916
1917             // Terminate old register assignments that don't reach MI;
1918             MachineFunction::const_iterator PrevMBB = Prev->getParent();
1919             if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1920                 isDbgValueInDefinedReg(Prev)) {
1921               // Previous register assignment needs to terminate at the end of
1922               // its basic block.
1923               MachineBasicBlock::const_iterator LastMI =
1924                 PrevMBB->getLastNonDebugInstr();
1925               if (LastMI == PrevMBB->end()) {
1926                 // Drop DBG_VALUE for empty range.
1927                 DEBUG(dbgs() << "Drop DBG_VALUE for empty range:\n"
1928                       << "\t" << *Prev << "\n");
1929                 History.pop_back();
1930               }
1931               else {
1932                 // Terminate after LastMI.
1933                 History.push_back(LastMI);
1934               }
1935             }
1936           }
1937         }
1938         History.push_back(MI);
1939       } else {
1940         // Not a DBG_VALUE instruction.
1941         if (!MI->isLabel())
1942           AtBlockEntry = false;
1943
1944         // First known non DBG_VALUE location marks beginning of function
1945         // body.
1946         if (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown())
1947           PrologEndLoc = MI->getDebugLoc();
1948
1949         // Check if the instruction clobbers any registers with debug vars.
1950         for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1951                MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1952           if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1953             continue;
1954           for (const unsigned *AI = TRI->getOverlaps(MOI->getReg());
1955                unsigned Reg = *AI; ++AI) {
1956             const MDNode *Var = LiveUserVar[Reg];
1957             if (!Var)
1958               continue;
1959             // Reg is now clobbered.
1960             LiveUserVar[Reg] = 0;
1961
1962             // Was MD last defined by a DBG_VALUE referring to Reg?
1963             DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1964             if (HistI == DbgValues.end())
1965               continue;
1966             SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1967             if (History.empty())
1968               continue;
1969             const MachineInstr *Prev = History.back();
1970             // Sanity-check: Register assignments are terminated at the end of
1971             // their block.
1972             if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1973               continue;
1974             // Is the variable still in Reg?
1975             if (!isDbgValueInDefinedReg(Prev) ||
1976                 Prev->getOperand(0).getReg() != Reg)
1977               continue;
1978             // Var is clobbered. Make sure the next instruction gets a label.
1979             History.push_back(MI);
1980           }
1981         }
1982       }
1983     }
1984   }
1985
1986   for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1987        I != E; ++I) {
1988     SmallVectorImpl<const MachineInstr*> &History = I->second;
1989     if (History.empty())
1990       continue;
1991
1992     // Make sure the final register assignments are terminated.
1993     const MachineInstr *Prev = History.back();
1994     if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1995       const MachineBasicBlock *PrevMBB = Prev->getParent();
1996       MachineBasicBlock::const_iterator LastMI = PrevMBB->getLastNonDebugInstr();
1997       if (LastMI == PrevMBB->end())
1998         // Drop DBG_VALUE for empty range.
1999         History.pop_back();
2000       else {
2001         // Terminate after LastMI.
2002         History.push_back(LastMI);
2003       }
2004     }
2005     // Request labels for the full history.
2006     for (unsigned i = 0, e = History.size(); i != e; ++i) {
2007       const MachineInstr *MI = History[i];
2008       if (MI->isDebugValue())
2009         requestLabelBeforeInsn(MI);
2010       else
2011         requestLabelAfterInsn(MI);
2012     }
2013   }
2014
2015   PrevInstLoc = DebugLoc();
2016   PrevLabel = FunctionBeginSym;
2017
2018   // Record beginning of function.
2019   if (!PrologEndLoc.isUnknown()) {
2020     DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
2021                                        MF->getFunction()->getContext());
2022     recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
2023                      FnStartDL.getScope(MF->getFunction()->getContext()),
2024                      DWARF2_FLAG_IS_STMT);
2025   }
2026 }
2027
2028 /// endFunction - Gather and emit post-function debug information.
2029 ///
2030 void DwarfDebug::endFunction(const MachineFunction *MF) {
2031   if (!MMI->hasDebugInfo() || DbgScopeMap.empty()) return;
2032
2033   if (CurrentFnDbgScope) {
2034
2035     // Define end label for subprogram.
2036     FunctionEndSym = Asm->GetTempSymbol("func_end",
2037                                         Asm->getFunctionNumber());
2038     // Assumes in correct section after the entry point.
2039     Asm->OutStreamer.EmitLabel(FunctionEndSym);
2040
2041     SmallPtrSet<const MDNode *, 16> ProcessedVars;
2042     collectVariableInfo(MF, ProcessedVars);
2043
2044     // Construct abstract scopes.
2045     for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2046            AE = AbstractScopesList.end(); AI != AE; ++AI) {
2047       DISubprogram SP((*AI)->getScopeNode());
2048       if (SP.Verify()) {
2049         // Collect info for variables that were optimized out.
2050         StringRef FName = SP.getLinkageName();
2051         if (FName.empty())
2052           FName = SP.getName();
2053         if (NamedMDNode *NMD = 
2054             getFnSpecificMDNode(*(MF->getFunction()->getParent()), FName)) {
2055           for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2056           DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
2057           if (!DV || !ProcessedVars.insert(DV))
2058             continue;
2059           DbgScope *Scope = AbstractScopes.lookup(DV.getContext());
2060           if (Scope)
2061             Scope->addVariable(new DbgVariable(DV));
2062           }
2063         }
2064       }
2065       if (ProcessedSPNodes.count((*AI)->getScopeNode()) == 0)
2066         constructScopeDIE(*AI);
2067     }
2068
2069     DIE *CurFnDIE = constructScopeDIE(CurrentFnDbgScope);
2070
2071     if (!DisableFramePointerElim(*MF))
2072       getCompileUnit(CurrentFnDbgScope->getScopeNode())->addUInt(CurFnDIE, 
2073                                                                  dwarf::DW_AT_APPLE_omit_frame_ptr,
2074                                                                  dwarf::DW_FORM_flag, 1);
2075
2076
2077     DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
2078                                                  MMI->getFrameMoves()));
2079   }
2080
2081   // Clear debug info
2082   CurrentFnDbgScope = NULL;
2083   DeleteContainerPointers(CurrentFnArguments);
2084   DbgVariableToFrameIndexMap.clear();
2085   VarToAbstractVarMap.clear();
2086   DbgVariableToDbgInstMap.clear();
2087   InlinedDbgScopeMap.clear();
2088   DeleteContainerSeconds(DbgScopeMap);
2089   UserVariables.clear();
2090   DbgValues.clear();
2091   DeleteContainerSeconds(AbstractScopes);
2092   AbstractScopesList.clear();
2093   AbstractVariables.clear();
2094   LabelsBeforeInsn.clear();
2095   LabelsAfterInsn.clear();
2096   PrevLabel = NULL;
2097 }
2098
2099 /// recordVariableFrameIndex - Record a variable's index.
2100 void DwarfDebug::recordVariableFrameIndex(const DbgVariable *V, int Index) {
2101   assert (V && "Invalid DbgVariable!");
2102   DbgVariableToFrameIndexMap[V] = Index;
2103 }
2104
2105 /// findVariableFrameIndex - Return true if frame index for the variable
2106 /// is found. Update FI to hold value of the index.
2107 bool DwarfDebug::findVariableFrameIndex(const DbgVariable *V, int *FI) {
2108   assert (V && "Invalid DbgVariable!");
2109   DenseMap<const DbgVariable *, int>::iterator I =
2110     DbgVariableToFrameIndexMap.find(V);
2111   if (I == DbgVariableToFrameIndexMap.end())
2112     return false;
2113   *FI = I->second;
2114   return true;
2115 }
2116
2117 /// findDbgScope - Find DbgScope for the debug loc.
2118 DbgScope *DwarfDebug::findDbgScope(DebugLoc DL) {
2119   if (DL.isUnknown())
2120     return NULL;
2121
2122   DbgScope *Scope = NULL;
2123   LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2124   if (MDNode *IA = DL.getInlinedAt(Ctx))
2125     Scope = InlinedDbgScopeMap.lookup(DebugLoc::getFromDILocation(IA));
2126   else
2127     Scope = DbgScopeMap.lookup(DL.getScope(Ctx));
2128   return Scope;
2129 }
2130
2131
2132 /// recordSourceLine - Register a source line with debug info. Returns the
2133 /// unique label that was emitted and which provides correspondence to
2134 /// the source line list.
2135 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
2136                                   unsigned Flags) {
2137   StringRef Fn;
2138   StringRef Dir;
2139   unsigned Src = 1;
2140   if (S) {
2141     DIDescriptor Scope(S);
2142
2143     if (Scope.isCompileUnit()) {
2144       DICompileUnit CU(S);
2145       Fn = CU.getFilename();
2146       Dir = CU.getDirectory();
2147     } else if (Scope.isFile()) {
2148       DIFile F(S);
2149       Fn = F.getFilename();
2150       Dir = F.getDirectory();
2151     } else if (Scope.isSubprogram()) {
2152       DISubprogram SP(S);
2153       Fn = SP.getFilename();
2154       Dir = SP.getDirectory();
2155     } else if (Scope.isLexicalBlock()) {
2156       DILexicalBlock DB(S);
2157       Fn = DB.getFilename();
2158       Dir = DB.getDirectory();
2159     } else
2160       assert(0 && "Unexpected scope info");
2161
2162     Src = GetOrCreateSourceID(Fn, Dir);
2163   }
2164   Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
2165 }
2166
2167 //===----------------------------------------------------------------------===//
2168 // Emit Methods
2169 //===----------------------------------------------------------------------===//
2170
2171 /// computeSizeAndOffset - Compute the size and offset of a DIE.
2172 ///
2173 unsigned
2174 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
2175   // Get the children.
2176   const std::vector<DIE *> &Children = Die->getChildren();
2177
2178   // If not last sibling and has children then add sibling offset attribute.
2179   if (!Last && !Children.empty())
2180     Die->addSiblingOffset(DIEValueAllocator);
2181
2182   // Record the abbreviation.
2183   assignAbbrevNumber(Die->getAbbrev());
2184
2185   // Get the abbreviation for this DIE.
2186   unsigned AbbrevNumber = Die->getAbbrevNumber();
2187   const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2188
2189   // Set DIE offset
2190   Die->setOffset(Offset);
2191
2192   // Start the size with the size of abbreviation code.
2193   Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2194
2195   const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2196   const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2197
2198   // Size the DIE attribute values.
2199   for (unsigned i = 0, N = Values.size(); i < N; ++i)
2200     // Size attribute value.
2201     Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
2202
2203   // Size the DIE children if any.
2204   if (!Children.empty()) {
2205     assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2206            "Children flag not set");
2207
2208     for (unsigned j = 0, M = Children.size(); j < M; ++j)
2209       Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
2210
2211     // End of children marker.
2212     Offset += sizeof(int8_t);
2213   }
2214
2215   Die->setSize(Offset - Die->getOffset());
2216   return Offset;
2217 }
2218
2219 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
2220 ///
2221 void DwarfDebug::computeSizeAndOffsets() {
2222   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2223          E = CUMap.end(); I != E; ++I) {
2224     // Compute size of compile unit header.
2225     unsigned Offset = 
2226       sizeof(int32_t) + // Length of Compilation Unit Info
2227       sizeof(int16_t) + // DWARF version number
2228       sizeof(int32_t) + // Offset Into Abbrev. Section
2229       sizeof(int8_t);   // Pointer Size (in bytes)
2230     computeSizeAndOffset(I->second->getCUDie(), Offset, true);
2231   }
2232 }
2233
2234 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
2235 /// temporary label to it if SymbolStem is specified.
2236 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
2237                                 const char *SymbolStem = 0) {
2238   Asm->OutStreamer.SwitchSection(Section);
2239   if (!SymbolStem) return 0;
2240
2241   MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
2242   Asm->OutStreamer.EmitLabel(TmpSym);
2243   return TmpSym;
2244 }
2245
2246 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
2247 /// the start of each one.
2248 void DwarfDebug::EmitSectionLabels() {
2249   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2250
2251   // Dwarf sections base addresses.
2252   DwarfInfoSectionSym =
2253     EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
2254   DwarfAbbrevSectionSym =
2255     EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
2256   EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
2257
2258   if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
2259     EmitSectionSym(Asm, MacroInfo);
2260
2261   EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
2262   EmitSectionSym(Asm, TLOF.getDwarfLocSection());
2263   EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
2264   EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2265   DwarfStrSectionSym =
2266     EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
2267   DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
2268                                              "debug_range");
2269
2270   DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
2271                                            "section_debug_loc");
2272
2273   TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
2274   EmitSectionSym(Asm, TLOF.getDataSection());
2275 }
2276
2277 /// emitDIE - Recursively emits a debug information entry.
2278 ///
2279 void DwarfDebug::emitDIE(DIE *Die) {
2280   // Get the abbreviation for this DIE.
2281   unsigned AbbrevNumber = Die->getAbbrevNumber();
2282   const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2283
2284   // Emit the code (index) for the abbreviation.
2285   if (Asm->isVerbose())
2286     Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
2287                                 Twine::utohexstr(Die->getOffset()) + ":0x" +
2288                                 Twine::utohexstr(Die->getSize()) + " " +
2289                                 dwarf::TagString(Abbrev->getTag()));
2290   Asm->EmitULEB128(AbbrevNumber);
2291
2292   const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2293   const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2294
2295   // Emit the DIE attribute values.
2296   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2297     unsigned Attr = AbbrevData[i].getAttribute();
2298     unsigned Form = AbbrevData[i].getForm();
2299     assert(Form && "Too many attributes for DIE (check abbreviation)");
2300
2301     if (Asm->isVerbose())
2302       Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2303
2304     switch (Attr) {
2305     case dwarf::DW_AT_sibling:
2306       Asm->EmitInt32(Die->getSiblingOffset());
2307       break;
2308     case dwarf::DW_AT_abstract_origin: {
2309       DIEEntry *E = cast<DIEEntry>(Values[i]);
2310       DIE *Origin = E->getEntry();
2311       unsigned Addr = Origin->getOffset();
2312       Asm->EmitInt32(Addr);
2313       break;
2314     }
2315     case dwarf::DW_AT_ranges: {
2316       // DW_AT_range Value encodes offset in debug_range section.
2317       DIEInteger *V = cast<DIEInteger>(Values[i]);
2318
2319       if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
2320         Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
2321                                  V->getValue(),
2322                                  4);
2323       } else {
2324         Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
2325                                        V->getValue(),
2326                                        DwarfDebugRangeSectionSym,
2327                                        4);
2328       }
2329       break;
2330     }
2331     case dwarf::DW_AT_location: {
2332       if (UseDotDebugLocEntry.count(Die) != 0) {
2333         DIELabel *L = cast<DIELabel>(Values[i]);
2334         Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2335       } else
2336         Values[i]->EmitValue(Asm, Form);
2337       break;
2338     }
2339     case dwarf::DW_AT_accessibility: {
2340       if (Asm->isVerbose()) {
2341         DIEInteger *V = cast<DIEInteger>(Values[i]);
2342         Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2343       }
2344       Values[i]->EmitValue(Asm, Form);
2345       break;
2346     }
2347     default:
2348       // Emit an attribute using the defined form.
2349       Values[i]->EmitValue(Asm, Form);
2350       break;
2351     }
2352   }
2353
2354   // Emit the DIE children if any.
2355   if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2356     const std::vector<DIE *> &Children = Die->getChildren();
2357
2358     for (unsigned j = 0, M = Children.size(); j < M; ++j)
2359       emitDIE(Children[j]);
2360
2361     if (Asm->isVerbose())
2362       Asm->OutStreamer.AddComment("End Of Children Mark");
2363     Asm->EmitInt8(0);
2364   }
2365 }
2366
2367 /// emitDebugInfo - Emit the debug info section.
2368 ///
2369 void DwarfDebug::emitDebugInfo() {
2370   // Start debug info section.
2371   Asm->OutStreamer.SwitchSection(
2372                             Asm->getObjFileLowering().getDwarfInfoSection());
2373   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2374          E = CUMap.end(); I != E; ++I) {
2375     CompileUnit *TheCU = I->second;
2376     DIE *Die = TheCU->getCUDie();
2377
2378     // Emit the compile units header.
2379     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
2380                                                   TheCU->getID()));
2381
2382     // Emit size of content not including length itself
2383     unsigned ContentSize = Die->getSize() +
2384       sizeof(int16_t) + // DWARF version number
2385       sizeof(int32_t) + // Offset Into Abbrev. Section
2386       sizeof(int8_t);   // Pointer Size (in bytes)
2387
2388     Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2389     Asm->EmitInt32(ContentSize);
2390     Asm->OutStreamer.AddComment("DWARF version number");
2391     Asm->EmitInt16(dwarf::DWARF_VERSION);
2392     Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2393     Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
2394                            DwarfAbbrevSectionSym);
2395     Asm->OutStreamer.AddComment("Address Size (in bytes)");
2396     Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2397
2398     emitDIE(Die);
2399     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
2400   }
2401 }
2402
2403 /// emitAbbreviations - Emit the abbreviation section.
2404 ///
2405 void DwarfDebug::emitAbbreviations() const {
2406   // Check to see if it is worth the effort.
2407   if (!Abbreviations.empty()) {
2408     // Start the debug abbrev section.
2409     Asm->OutStreamer.SwitchSection(
2410                             Asm->getObjFileLowering().getDwarfAbbrevSection());
2411
2412     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
2413
2414     // For each abbrevation.
2415     for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2416       // Get abbreviation data
2417       const DIEAbbrev *Abbrev = Abbreviations[i];
2418
2419       // Emit the abbrevations code (base 1 index.)
2420       Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2421
2422       // Emit the abbreviations data.
2423       Abbrev->Emit(Asm);
2424     }
2425
2426     // Mark end of abbreviations.
2427     Asm->EmitULEB128(0, "EOM(3)");
2428
2429     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
2430   }
2431 }
2432
2433 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
2434 /// the line matrix.
2435 ///
2436 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2437   // Define last address of section.
2438   Asm->OutStreamer.AddComment("Extended Op");
2439   Asm->EmitInt8(0);
2440
2441   Asm->OutStreamer.AddComment("Op size");
2442   Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
2443   Asm->OutStreamer.AddComment("DW_LNE_set_address");
2444   Asm->EmitInt8(dwarf::DW_LNE_set_address);
2445
2446   Asm->OutStreamer.AddComment("Section end label");
2447
2448   Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2449                                    Asm->getTargetData().getPointerSize(),
2450                                    0/*AddrSpace*/);
2451
2452   // Mark end of matrix.
2453   Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2454   Asm->EmitInt8(0);
2455   Asm->EmitInt8(1);
2456   Asm->EmitInt8(1);
2457 }
2458
2459 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2460 ///
2461 void DwarfDebug::emitDebugPubNames() {
2462   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2463          E = CUMap.end(); I != E; ++I) {
2464     CompileUnit *TheCU = I->second;
2465     // Start the dwarf pubnames section.
2466     Asm->OutStreamer.SwitchSection(
2467       Asm->getObjFileLowering().getDwarfPubNamesSection());
2468
2469     Asm->OutStreamer.AddComment("Length of Public Names Info");
2470     Asm->EmitLabelDifference(
2471       Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
2472       Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
2473
2474     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
2475                                                   TheCU->getID()));
2476
2477     Asm->OutStreamer.AddComment("DWARF Version");
2478     Asm->EmitInt16(dwarf::DWARF_VERSION);
2479
2480     Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2481     Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
2482                            DwarfInfoSectionSym);
2483
2484     Asm->OutStreamer.AddComment("Compilation Unit Length");
2485     Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
2486                              Asm->GetTempSymbol("info_begin", TheCU->getID()),
2487                              4);
2488
2489     const StringMap<DIE*> &Globals = TheCU->getGlobals();
2490     for (StringMap<DIE*>::const_iterator
2491            GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2492       const char *Name = GI->getKeyData();
2493       DIE *Entity = GI->second;
2494
2495       Asm->OutStreamer.AddComment("DIE offset");
2496       Asm->EmitInt32(Entity->getOffset());
2497
2498       if (Asm->isVerbose())
2499         Asm->OutStreamer.AddComment("External Name");
2500       Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
2501     }
2502
2503     Asm->OutStreamer.AddComment("End Mark");
2504     Asm->EmitInt32(0);
2505     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
2506                                                   TheCU->getID()));
2507   }
2508 }
2509
2510 void DwarfDebug::emitDebugPubTypes() {
2511   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2512          E = CUMap.end(); I != E; ++I) {
2513     CompileUnit *TheCU = I->second;
2514     // Start the dwarf pubnames section.
2515     Asm->OutStreamer.SwitchSection(
2516       Asm->getObjFileLowering().getDwarfPubTypesSection());
2517     Asm->OutStreamer.AddComment("Length of Public Types Info");
2518     Asm->EmitLabelDifference(
2519       Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
2520       Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
2521
2522     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2523                                                   TheCU->getID()));
2524
2525     if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2526     Asm->EmitInt16(dwarf::DWARF_VERSION);
2527
2528     Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2529     Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
2530                            DwarfInfoSectionSym);
2531
2532     Asm->OutStreamer.AddComment("Compilation Unit Length");
2533     Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
2534                              Asm->GetTempSymbol("info_begin", TheCU->getID()),
2535                              4);
2536
2537     const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2538     for (StringMap<DIE*>::const_iterator
2539            GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2540       const char *Name = GI->getKeyData();
2541       DIE *Entity = GI->second;
2542
2543       if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2544       Asm->EmitInt32(Entity->getOffset());
2545
2546       if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2547       Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
2548     }
2549
2550     Asm->OutStreamer.AddComment("End Mark");
2551     Asm->EmitInt32(0);
2552     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2553                                                   TheCU->getID()));
2554   }
2555 }
2556
2557 /// emitDebugStr - Emit visible names into a debug str section.
2558 ///
2559 void DwarfDebug::emitDebugStr() {
2560   // Check to see if it is worth the effort.
2561   if (StringPool.empty()) return;
2562
2563   // Start the dwarf str section.
2564   Asm->OutStreamer.SwitchSection(
2565                                 Asm->getObjFileLowering().getDwarfStrSection());
2566
2567   // Get all of the string pool entries and put them in an array by their ID so
2568   // we can sort them.
2569   SmallVector<std::pair<unsigned,
2570       StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2571
2572   for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2573        I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
2574     Entries.push_back(std::make_pair(I->second.second, &*I));
2575
2576   array_pod_sort(Entries.begin(), Entries.end());
2577
2578   for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2579     // Emit a label for reference from debug information entries.
2580     Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2581
2582     // Emit the string itself.
2583     Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
2584   }
2585 }
2586
2587 /// emitDebugLoc - Emit visible names into a debug loc section.
2588 ///
2589 void DwarfDebug::emitDebugLoc() {
2590   if (DotDebugLocEntries.empty())
2591     return;
2592
2593   for (SmallVector<DotDebugLocEntry, 4>::iterator
2594          I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2595        I != E; ++I) {
2596     DotDebugLocEntry &Entry = *I;
2597     if (I + 1 != DotDebugLocEntries.end())
2598       Entry.Merge(I+1);
2599   }
2600
2601   // Start the dwarf loc section.
2602   Asm->OutStreamer.SwitchSection(
2603     Asm->getObjFileLowering().getDwarfLocSection());
2604   unsigned char Size = Asm->getTargetData().getPointerSize();
2605   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2606   unsigned index = 1;
2607   for (SmallVector<DotDebugLocEntry, 4>::iterator
2608          I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2609        I != E; ++I, ++index) {
2610     DotDebugLocEntry &Entry = *I;
2611     if (Entry.isMerged()) continue;
2612     if (Entry.isEmpty()) {
2613       Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2614       Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2615       Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2616     } else {
2617       Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
2618       Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
2619       DIVariable DV(Entry.Variable);
2620       Asm->OutStreamer.AddComment("Loc expr size");
2621       MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2622       MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2623       Asm->EmitLabelDifference(end, begin, 2);
2624       Asm->OutStreamer.EmitLabel(begin);
2625       if (Entry.isInt()) {
2626         DIBasicType BTy(DV.getType());
2627         if (BTy.Verify() &&
2628             (BTy.getEncoding()  == dwarf::DW_ATE_signed 
2629              || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2630           Asm->OutStreamer.AddComment("DW_OP_consts");
2631           Asm->EmitInt8(dwarf::DW_OP_consts);
2632           Asm->EmitSLEB128(Entry.getInt());
2633         } else {
2634           Asm->OutStreamer.AddComment("DW_OP_constu");
2635           Asm->EmitInt8(dwarf::DW_OP_constu);
2636           Asm->EmitULEB128(Entry.getInt());
2637         }
2638       } else if (Entry.isLocation()) {
2639         if (!DV.hasComplexAddress()) 
2640           // Regular entry.
2641           Asm->EmitDwarfRegOp(Entry.Loc);
2642         else {
2643           // Complex address entry.
2644           unsigned N = DV.getNumAddrElements();
2645           unsigned i = 0;
2646           if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2647             if (Entry.Loc.getOffset()) {
2648               i = 2;
2649               Asm->EmitDwarfRegOp(Entry.Loc);
2650               Asm->OutStreamer.AddComment("DW_OP_deref");
2651               Asm->EmitInt8(dwarf::DW_OP_deref);
2652               Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2653               Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2654               Asm->EmitSLEB128(DV.getAddrElement(1));
2655             } else {
2656               // If first address element is OpPlus then emit
2657               // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2658               MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2659               Asm->EmitDwarfRegOp(Loc);
2660               i = 2;
2661             }
2662           } else {
2663             Asm->EmitDwarfRegOp(Entry.Loc);
2664           }
2665           
2666           // Emit remaining complex address elements.
2667           for (; i < N; ++i) {
2668             uint64_t Element = DV.getAddrElement(i);
2669             if (Element == DIBuilder::OpPlus) {
2670               Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2671               Asm->EmitULEB128(DV.getAddrElement(++i));
2672             } else if (Element == DIBuilder::OpDeref)
2673               Asm->EmitInt8(dwarf::DW_OP_deref);
2674             else llvm_unreachable("unknown Opcode found in complex address");
2675           }
2676         }
2677       }
2678       // else ... ignore constant fp. There is not any good way to
2679       // to represent them here in dwarf.
2680       Asm->OutStreamer.EmitLabel(end);
2681     }
2682   }
2683 }
2684
2685 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2686 ///
2687 void DwarfDebug::EmitDebugARanges() {
2688   // Start the dwarf aranges section.
2689   Asm->OutStreamer.SwitchSection(
2690                           Asm->getObjFileLowering().getDwarfARangesSection());
2691 }
2692
2693 /// emitDebugRanges - Emit visible names into a debug ranges section.
2694 ///
2695 void DwarfDebug::emitDebugRanges() {
2696   // Start the dwarf ranges section.
2697   Asm->OutStreamer.SwitchSection(
2698     Asm->getObjFileLowering().getDwarfRangesSection());
2699   unsigned char Size = Asm->getTargetData().getPointerSize();
2700   for (SmallVector<const MCSymbol *, 8>::iterator
2701          I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2702        I != E; ++I) {
2703     if (*I)
2704       Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
2705     else
2706       Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2707   }
2708 }
2709
2710 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2711 ///
2712 void DwarfDebug::emitDebugMacInfo() {
2713   if (const MCSection *LineInfo =
2714       Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2715     // Start the dwarf macinfo section.
2716     Asm->OutStreamer.SwitchSection(LineInfo);
2717   }
2718 }
2719
2720 /// emitDebugInlineInfo - Emit inline info using following format.
2721 /// Section Header:
2722 /// 1. length of section
2723 /// 2. Dwarf version number
2724 /// 3. address size.
2725 ///
2726 /// Entries (one "entry" for each function that was inlined):
2727 ///
2728 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2729 ///   otherwise offset into __debug_str for regular function name.
2730 /// 2. offset into __debug_str section for regular function name.
2731 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2732 /// instances for the function.
2733 ///
2734 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2735 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2736 /// __debug_info section, and the low_pc is the starting address for the
2737 /// inlining instance.
2738 void DwarfDebug::emitDebugInlineInfo() {
2739   if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
2740     return;
2741
2742   if (!FirstCU)
2743     return;
2744
2745   Asm->OutStreamer.SwitchSection(
2746                         Asm->getObjFileLowering().getDwarfDebugInlineSection());
2747
2748   Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2749   Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2750                            Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2751
2752   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2753
2754   Asm->OutStreamer.AddComment("Dwarf Version");
2755   Asm->EmitInt16(dwarf::DWARF_VERSION);
2756   Asm->OutStreamer.AddComment("Address Size (in bytes)");
2757   Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2758
2759   for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2760          E = InlinedSPNodes.end(); I != E; ++I) {
2761
2762     const MDNode *Node = *I;
2763     DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2764       = InlineInfo.find(Node);
2765     SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2766     DISubprogram SP(Node);
2767     StringRef LName = SP.getLinkageName();
2768     StringRef Name = SP.getName();
2769
2770     Asm->OutStreamer.AddComment("MIPS linkage name");
2771     if (LName.empty()) {
2772       Asm->OutStreamer.EmitBytes(Name, 0);
2773       Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
2774     } else
2775       Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2776                              DwarfStrSectionSym);
2777
2778     Asm->OutStreamer.AddComment("Function name");
2779     Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2780     Asm->EmitULEB128(Labels.size(), "Inline count");
2781
2782     for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2783            LE = Labels.end(); LI != LE; ++LI) {
2784       if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2785       Asm->EmitInt32(LI->second->getOffset());
2786
2787       if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2788       Asm->OutStreamer.EmitSymbolValue(LI->first,
2789                                        Asm->getTargetData().getPointerSize(),0);
2790     }
2791   }
2792
2793   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2794 }