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