Add support to preserve type info for the variables that are removed by the optimizer.
[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 "llvm/Constants.h"
18 #include "llvm/Module.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineModuleInfo.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCSection.h"
23 #include "llvm/MC/MCStreamer.h"
24 #include "llvm/MC/MCSymbol.h"
25 #include "llvm/Target/Mangler.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetFrameInfo.h"
28 #include "llvm/Target/TargetLoweringObjectFile.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetRegisterInfo.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/Analysis/DebugInfo.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/ValueHandle.h"
39 #include "llvm/Support/FormattedStream.h"
40 #include "llvm/Support/Timer.h"
41 #include "llvm/System/Path.h"
42 using namespace llvm;
43
44 static cl::opt<bool> PrintDbgScope("print-dbgscope", cl::Hidden,
45      cl::desc("Print DbgScope information for each machine instruction"));
46
47 static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
48      cl::desc("Disable debug info printing"));
49
50 static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
51      cl::desc("Make an absense of debug location information explicit."),
52      cl::init(false));
53
54 namespace {
55   const char *DWARFGroupName = "DWARF Emission";
56   const char *DbgTimerName = "DWARF Debug Writer";
57 } // end anonymous namespace
58
59 //===----------------------------------------------------------------------===//
60
61 /// Configuration values for initial hash set sizes (log2).
62 ///
63 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
64
65 namespace llvm {
66
67 //===----------------------------------------------------------------------===//
68 /// CompileUnit - This dwarf writer support class manages information associate
69 /// with a source file.
70 class CompileUnit {
71   /// ID - File identifier for source.
72   ///
73   unsigned ID;
74
75   /// Die - Compile unit debug information entry.
76   ///
77   const OwningPtr<DIE> CUDie;
78
79   /// IndexTyDie - An anonymous type for index type.  Owned by CUDie.
80   DIE *IndexTyDie;
81
82   /// GVToDieMap - Tracks the mapping of unit level debug informaton
83   /// variables to debug information entries.
84   /// FIXME : Rename GVToDieMap -> NodeToDieMap
85   DenseMap<const MDNode *, DIE *> GVToDieMap;
86
87   /// GVToDIEEntryMap - Tracks the mapping of unit level debug informaton
88   /// descriptors to debug information entries using a DIEEntry proxy.
89   /// FIXME : Rename
90   DenseMap<const MDNode *, DIEEntry *> GVToDIEEntryMap;
91
92   /// Globals - A map of globally visible named entities for this unit.
93   ///
94   StringMap<DIE*> Globals;
95
96   /// GlobalTypes - A map of globally visible types for this unit.
97   ///
98   StringMap<DIE*> GlobalTypes;
99
100 public:
101   CompileUnit(unsigned I, DIE *D)
102     : ID(I), CUDie(D), IndexTyDie(0) {}
103
104   // Accessors.
105   unsigned getID()                  const { return ID; }
106   DIE* getCUDie()                   const { return CUDie.get(); }
107   const StringMap<DIE*> &getGlobals()     const { return Globals; }
108   const StringMap<DIE*> &getGlobalTypes() const { return GlobalTypes; }
109
110   /// hasContent - Return true if this compile unit has something to write out.
111   ///
112   bool hasContent() const { return !CUDie->getChildren().empty(); }
113
114   /// addGlobal - Add a new global entity to the compile unit.
115   ///
116   void addGlobal(StringRef Name, DIE *Die) { Globals[Name] = Die; }
117
118   /// addGlobalType - Add a new global type to the compile unit.
119   ///
120   void addGlobalType(StringRef Name, DIE *Die) { 
121     GlobalTypes[Name] = Die; 
122   }
123
124   /// getDIE - Returns the debug information entry map slot for the
125   /// specified debug variable.
126   DIE *getDIE(const MDNode *N) { return GVToDieMap.lookup(N); }
127
128   /// insertDIE - Insert DIE into the map.
129   void insertDIE(const MDNode *N, DIE *D) {
130     GVToDieMap.insert(std::make_pair(N, D));
131   }
132
133   /// getDIEEntry - Returns the debug information entry for the speciefied
134   /// debug variable.
135   DIEEntry *getDIEEntry(const MDNode *N) { 
136     DenseMap<const MDNode *, DIEEntry *>::iterator I = GVToDIEEntryMap.find(N);
137     if (I == GVToDIEEntryMap.end())
138       return NULL;
139     return I->second;
140   }
141
142   /// insertDIEEntry - Insert debug information entry into the map.
143   void insertDIEEntry(const MDNode *N, DIEEntry *E) {
144     GVToDIEEntryMap.insert(std::make_pair(N, E));
145   }
146
147   /// addDie - Adds or interns the DIE to the compile unit.
148   ///
149   void addDie(DIE *Buffer) {
150     this->CUDie->addChild(Buffer);
151   }
152
153   // getIndexTyDie - Get an anonymous type for index type.
154   DIE *getIndexTyDie() {
155     return IndexTyDie;
156   }
157
158   // setIndexTyDie - Set D as anonymous type for index which can be reused
159   // later.
160   void setIndexTyDie(DIE *D) {
161     IndexTyDie = D;
162   }
163
164 };
165
166 //===----------------------------------------------------------------------===//
167 /// DbgVariable - This class is used to track local variable information.
168 ///
169 class DbgVariable {
170   DIVariable Var;                    // Variable Descriptor.
171   unsigned FrameIndex;               // Variable frame index.
172   const MachineInstr *DbgValueMInsn; // DBG_VALUE
173   // DbgValueLabel - DBG_VALUE is effective from this label.
174   MCSymbol *DbgValueLabel;
175   DbgVariable *const AbstractVar;    // Abstract variable for this variable.
176   DIE *TheDIE;
177 public:
178   // AbsVar may be NULL.
179   DbgVariable(DIVariable V, unsigned I, DbgVariable *AbsVar)
180     : Var(V), FrameIndex(I), DbgValueMInsn(0), 
181       DbgValueLabel(0), AbstractVar(AbsVar), TheDIE(0) {}
182   DbgVariable(DIVariable V, const MachineInstr *MI, DbgVariable *AbsVar)
183     : Var(V), FrameIndex(0), DbgValueMInsn(MI), DbgValueLabel(0),
184       AbstractVar(AbsVar), TheDIE(0)
185     {}
186
187   // Accessors.
188   DIVariable getVariable()           const { return Var; }
189   unsigned getFrameIndex()           const { return FrameIndex; }
190   const MachineInstr *getDbgValue()  const { return DbgValueMInsn; }
191   MCSymbol *getDbgValueLabel()       const { return DbgValueLabel; }
192   void setDbgValueLabel(MCSymbol *L)       { DbgValueLabel = L; }
193   DbgVariable *getAbstractVariable() const { return AbstractVar; }
194   void setDIE(DIE *D)                      { TheDIE = D; }
195   DIE *getDIE()                      const { return TheDIE; }
196   bool hasLocation()                       { 
197     return DbgValueMInsn || FrameIndex != ~0U; 
198   }
199 };
200
201 //===----------------------------------------------------------------------===//
202 /// DbgRange - This is used to track range of instructions with identical
203 /// debug info scope.
204 ///
205 typedef std::pair<const MachineInstr *, const MachineInstr *> DbgRange;
206
207 //===----------------------------------------------------------------------===//
208 /// DbgScope - This class is used to track scope information.
209 ///
210 class DbgScope {
211   DbgScope *Parent;                   // Parent to this scope.
212   DIDescriptor Desc;                  // Debug info descriptor for scope.
213   // Location at which this scope is inlined.
214   AssertingVH<const MDNode> InlinedAtLocation;  
215   bool AbstractScope;                 // Abstract Scope
216   const MachineInstr *LastInsn;       // Last instruction of this scope.
217   const MachineInstr *FirstInsn;      // First instruction of this scope.
218   unsigned DFSIn, DFSOut;
219   // Scopes defined in scope.  Contents not owned.
220   SmallVector<DbgScope *, 4> Scopes;
221   // Variables declared in scope.  Contents owned.
222   SmallVector<DbgVariable *, 8> Variables;
223   SmallVector<DbgRange, 4> Ranges;
224   // Private state for dump()
225   mutable unsigned IndentLevel;
226 public:
227   DbgScope(DbgScope *P, DIDescriptor D, const MDNode *I = 0)
228     : Parent(P), Desc(D), InlinedAtLocation(I), AbstractScope(false),
229       LastInsn(0), FirstInsn(0),
230       DFSIn(0), DFSOut(0), IndentLevel(0) {}
231   virtual ~DbgScope();
232
233   // Accessors.
234   DbgScope *getParent()          const { return Parent; }
235   void setParent(DbgScope *P)          { Parent = P; }
236   DIDescriptor getDesc()         const { return Desc; }
237   const MDNode *getInlinedAt()         const { return InlinedAtLocation; }
238   const MDNode *getScopeNode()         const { return Desc; }
239   const SmallVector<DbgScope *, 4> &getScopes() { return Scopes; }
240   const SmallVector<DbgVariable *, 8> &getVariables() { return Variables; }
241   const SmallVector<DbgRange, 4> &getRanges() { return Ranges; }
242
243   /// openInsnRange - This scope covers instruction range starting from MI.
244   void openInsnRange(const MachineInstr *MI) {
245     if (!FirstInsn) 
246       FirstInsn = MI;
247     
248     if (Parent)
249       Parent->openInsnRange(MI);
250   }
251
252   /// extendInsnRange - Extend the current instruction range covered by 
253   /// this scope.
254   void extendInsnRange(const MachineInstr *MI) {
255     assert (FirstInsn && "MI Range is not open!");
256     LastInsn = MI;
257     if (Parent)
258       Parent->extendInsnRange(MI);
259   }
260
261   /// closeInsnRange - Create a range based on FirstInsn and LastInsn collected
262   /// until now. This is used when a new scope is encountered while walking
263   /// machine instructions.
264   void closeInsnRange(DbgScope *NewScope = NULL) {
265     assert (LastInsn && "Last insn missing!");
266     Ranges.push_back(DbgRange(FirstInsn, LastInsn));
267     FirstInsn = NULL;    
268     LastInsn = NULL;
269     // If Parent dominates NewScope then do not close Parent's instruction 
270     // range.
271     if (Parent && (!NewScope || !Parent->dominates(NewScope)))
272       Parent->closeInsnRange(NewScope);
273   }
274
275   void setAbstractScope() { AbstractScope = true; }
276   bool isAbstractScope() const { return AbstractScope; }
277
278   // Depth First Search support to walk and mainpluate DbgScope hierarchy.
279   unsigned getDFSOut() const { return DFSOut; }
280   void setDFSOut(unsigned O) { DFSOut = O; }
281   unsigned getDFSIn() const  { return DFSIn; }
282   void setDFSIn(unsigned I)  { DFSIn = I; }
283   bool dominates(const DbgScope *S) {
284     if (S == this) 
285       return true;
286     if (DFSIn < S->getDFSIn() && DFSOut > S->getDFSOut())
287       return true;
288     return false;
289   }
290
291   /// addScope - Add a scope to the scope.
292   ///
293   void addScope(DbgScope *S) { Scopes.push_back(S); }
294
295   /// addVariable - Add a variable to the scope.
296   ///
297   void addVariable(DbgVariable *V) { Variables.push_back(V); }
298
299 #ifndef NDEBUG
300   void dump() const;
301 #endif
302 };
303
304 } // end llvm namespace
305
306 #ifndef NDEBUG
307 void DbgScope::dump() const {
308   raw_ostream &err = dbgs();
309   err.indent(IndentLevel);
310   const MDNode *N = Desc;
311   N->dump();
312   if (AbstractScope)
313     err << "Abstract Scope\n";
314
315   IndentLevel += 2;
316   if (!Scopes.empty())
317     err << "Children ...\n";
318   for (unsigned i = 0, e = Scopes.size(); i != e; ++i)
319     if (Scopes[i] != this)
320       Scopes[i]->dump();
321
322   IndentLevel -= 2;
323 }
324 #endif
325
326 DbgScope::~DbgScope() {
327   for (unsigned j = 0, M = Variables.size(); j < M; ++j)
328     delete Variables[j];
329 }
330
331 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
332   : Asm(A), MMI(Asm->MMI), FirstCU(0),
333     AbbreviationsSet(InitAbbreviationsSetSize), 
334     CurrentFnDbgScope(0), PrevLabel(NULL) {
335   NextStringPoolNumber = 0;
336       
337   DwarfFrameSectionSym = DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
338   DwarfStrSectionSym = TextSectionSym = 0;
339   DwarfDebugRangeSectionSym = 0;
340   FunctionBeginSym = 0;
341   if (TimePassesIsEnabled) {
342       NamedRegionTimer T(DbgTimerName, DWARFGroupName);
343       beginModule(M);
344   } else {
345       beginModule(M);
346   }
347 }
348 DwarfDebug::~DwarfDebug() {
349   for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j)
350     DIEBlocks[j]->~DIEBlock();
351 }
352
353 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
354   std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
355   if (Entry.first) return Entry.first;
356
357   Entry.second = NextStringPoolNumber++;
358   return Entry.first = Asm->GetTempSymbol("string", Entry.second);
359 }
360
361
362 /// assignAbbrevNumber - Define a unique number for the abbreviation.
363 ///
364 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
365   // Profile the node so that we can make it unique.
366   FoldingSetNodeID ID;
367   Abbrev.Profile(ID);
368
369   // Check the set for priors.
370   DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
371
372   // If it's newly added.
373   if (InSet == &Abbrev) {
374     // Add to abbreviation list.
375     Abbreviations.push_back(&Abbrev);
376
377     // Assign the vector position + 1 as its number.
378     Abbrev.setNumber(Abbreviations.size());
379   } else {
380     // Assign existing abbreviation number.
381     Abbrev.setNumber(InSet->getNumber());
382   }
383 }
384
385 /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug
386 /// information entry.
387 DIEEntry *DwarfDebug::createDIEEntry(DIE *Entry) {
388   DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry);
389   return Value;
390 }
391
392 /// addUInt - Add an unsigned integer attribute data and value.
393 ///
394 void DwarfDebug::addUInt(DIE *Die, unsigned Attribute,
395                          unsigned Form, uint64_t Integer) {
396   if (!Form) Form = DIEInteger::BestForm(false, Integer);
397   DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
398   Die->addValue(Attribute, Form, Value);
399 }
400
401 /// addSInt - Add an signed integer attribute data and value.
402 ///
403 void DwarfDebug::addSInt(DIE *Die, unsigned Attribute,
404                          unsigned Form, int64_t Integer) {
405   if (!Form) Form = DIEInteger::BestForm(true, Integer);
406   DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer);
407   Die->addValue(Attribute, Form, Value);
408 }
409
410 /// addString - Add a string attribute data and value. DIEString only
411 /// keeps string reference. 
412 void DwarfDebug::addString(DIE *Die, unsigned Attribute, unsigned Form,
413                            StringRef String) {
414   DIEValue *Value = new (DIEValueAllocator) DIEString(String);
415   Die->addValue(Attribute, Form, Value);
416 }
417
418 /// addLabel - Add a Dwarf label attribute data and value.
419 ///
420 void DwarfDebug::addLabel(DIE *Die, unsigned Attribute, unsigned Form,
421                           const MCSymbol *Label) {
422   DIEValue *Value = new (DIEValueAllocator) DIELabel(Label);
423   Die->addValue(Attribute, Form, Value);
424 }
425
426 /// addDelta - Add a label delta attribute data and value.
427 ///
428 void DwarfDebug::addDelta(DIE *Die, unsigned Attribute, unsigned Form,
429                           const MCSymbol *Hi, const MCSymbol *Lo) {
430   DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo);
431   Die->addValue(Attribute, Form, Value);
432 }
433
434 /// addDIEEntry - Add a DIE attribute data and value.
435 ///
436 void DwarfDebug::addDIEEntry(DIE *Die, unsigned Attribute, unsigned Form,
437                              DIE *Entry) {
438   Die->addValue(Attribute, Form, createDIEEntry(Entry));
439 }
440
441
442 /// addBlock - Add block data.
443 ///
444 void DwarfDebug::addBlock(DIE *Die, unsigned Attribute, unsigned Form,
445                           DIEBlock *Block) {
446   Block->ComputeSize(Asm);
447   DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on.
448   Die->addValue(Attribute, Block->BestForm(), Block);
449 }
450
451 /// addSourceLine - Add location information to specified debug information
452 /// entry.
453 void DwarfDebug::addSourceLine(DIE *Die, const DIVariable *V) {
454   // Verify variable.
455   if (!V->Verify())
456     return;
457
458   unsigned Line = V->getLineNumber();
459   unsigned FileID = GetOrCreateSourceID(V->getContext().getDirectory(),
460                                         V->getContext().getFilename());
461   assert(FileID && "Invalid file id");
462   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
463   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
464 }
465
466 /// addSourceLine - Add location information to specified debug information
467 /// entry.
468 void DwarfDebug::addSourceLine(DIE *Die, const DIGlobalVariable *G) {
469   // Verify global variable.
470   if (!G->Verify())
471     return;
472
473   unsigned Line = G->getLineNumber();
474   unsigned FileID = GetOrCreateSourceID(G->getContext().getDirectory(),
475                                         G->getContext().getFilename());
476   assert(FileID && "Invalid file id");
477   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
478   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
479 }
480
481 /// addSourceLine - Add location information to specified debug information
482 /// entry.
483 void DwarfDebug::addSourceLine(DIE *Die, const DISubprogram *SP) {
484   // Verify subprogram.
485   if (!SP->Verify())
486     return;
487   // If the line number is 0, don't add it.
488   if (SP->getLineNumber() == 0)
489     return;
490
491   unsigned Line = SP->getLineNumber();
492   if (!SP->getContext().Verify())
493     return;
494   unsigned FileID = GetOrCreateSourceID(SP->getDirectory(),
495                                         SP->getFilename());
496   assert(FileID && "Invalid file id");
497   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
498   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
499 }
500
501 /// addSourceLine - Add location information to specified debug information
502 /// entry.
503 void DwarfDebug::addSourceLine(DIE *Die, const DIType *Ty) {
504   // Verify type.
505   if (!Ty->Verify())
506     return;
507
508   unsigned Line = Ty->getLineNumber();
509   if (!Ty->getContext().Verify())
510     return;
511   unsigned FileID = GetOrCreateSourceID(Ty->getContext().getDirectory(),
512                                         Ty->getContext().getFilename());
513   assert(FileID && "Invalid file id");
514   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
515   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
516 }
517
518 /// addSourceLine - Add location information to specified debug information
519 /// entry.
520 void DwarfDebug::addSourceLine(DIE *Die, const DINameSpace *NS) {
521   // Verify namespace.
522   if (!NS->Verify())
523     return;
524
525   unsigned Line = NS->getLineNumber();
526   StringRef FN = NS->getFilename();
527   StringRef Dir = NS->getDirectory();
528
529   unsigned FileID = GetOrCreateSourceID(Dir, FN);
530   assert(FileID && "Invalid file id");
531   addUInt(Die, dwarf::DW_AT_decl_file, 0, FileID);
532   addUInt(Die, dwarf::DW_AT_decl_line, 0, Line);
533 }
534
535 /* Byref variables, in Blocks, are declared by the programmer as
536    "SomeType VarName;", but the compiler creates a
537    __Block_byref_x_VarName struct, and gives the variable VarName
538    either the struct, or a pointer to the struct, as its type.  This
539    is necessary for various behind-the-scenes things the compiler
540    needs to do with by-reference variables in blocks.
541
542    However, as far as the original *programmer* is concerned, the
543    variable should still have type 'SomeType', as originally declared.
544
545    The following function dives into the __Block_byref_x_VarName
546    struct to find the original type of the variable.  This will be
547    passed back to the code generating the type for the Debug
548    Information Entry for the variable 'VarName'.  'VarName' will then
549    have the original type 'SomeType' in its debug information.
550
551    The original type 'SomeType' will be the type of the field named
552    'VarName' inside the __Block_byref_x_VarName struct.
553
554    NOTE: In order for this to not completely fail on the debugger
555    side, the Debug Information Entry for the variable VarName needs to
556    have a DW_AT_location that tells the debugger how to unwind through
557    the pointers and __Block_byref_x_VarName struct to find the actual
558    value of the variable.  The function addBlockByrefType does this.  */
559
560 /// Find the type the programmer originally declared the variable to be
561 /// and return that type.
562 ///
563 DIType DwarfDebug::getBlockByrefType(DIType Ty, std::string Name) {
564
565   DIType subType = Ty;
566   unsigned tag = Ty.getTag();
567
568   if (tag == dwarf::DW_TAG_pointer_type) {
569     DIDerivedType DTy = DIDerivedType(Ty);
570     subType = DTy.getTypeDerivedFrom();
571   }
572
573   DICompositeType blockStruct = DICompositeType(subType);
574   DIArray Elements = blockStruct.getTypeArray();
575
576   for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
577     DIDescriptor Element = Elements.getElement(i);
578     DIDerivedType DT = DIDerivedType(Element);
579     if (Name == DT.getName())
580       return (DT.getTypeDerivedFrom());
581   }
582
583   return Ty;
584 }
585
586 /// addComplexAddress - Start with the address based on the location provided,
587 /// and generate the DWARF information necessary to find the actual variable
588 /// given the extra address information encoded in the DIVariable, starting from
589 /// the starting location.  Add the DWARF information to the die.
590 ///
591 void DwarfDebug::addComplexAddress(DbgVariable *&DV, DIE *Die,
592                                    unsigned Attribute,
593                                    const MachineLocation &Location) {
594   const DIVariable &VD = DV->getVariable();
595   DIType Ty = VD.getType();
596
597   // Decode the original location, and use that as the start of the byref
598   // variable's location.
599   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
600   unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
601   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
602
603   if (Location.isReg()) {
604     if (Reg < 32) {
605       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
606     } else {
607       Reg = Reg - dwarf::DW_OP_reg0;
608       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
609       addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
610     }
611   } else {
612     if (Reg < 32)
613       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
614     else {
615       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
616       addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
617     }
618
619     addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
620   }
621
622   for (unsigned i = 0, N = VD.getNumAddrElements(); i < N; ++i) {
623     uint64_t Element = VD.getAddrElement(i);
624
625     if (Element == DIFactory::OpPlus) {
626       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
627       addUInt(Block, 0, dwarf::DW_FORM_udata, VD.getAddrElement(++i));
628     } else if (Element == DIFactory::OpDeref) {
629       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
630     } else llvm_unreachable("unknown DIFactory Opcode");
631   }
632
633   // Now attach the location information to the DIE.
634   addBlock(Die, Attribute, 0, Block);
635 }
636
637 /* Byref variables, in Blocks, are declared by the programmer as "SomeType
638    VarName;", but the compiler creates a __Block_byref_x_VarName struct, and
639    gives the variable VarName either the struct, or a pointer to the struct, as
640    its type.  This is necessary for various behind-the-scenes things the
641    compiler needs to do with by-reference variables in Blocks.
642
643    However, as far as the original *programmer* is concerned, the variable
644    should still have type 'SomeType', as originally declared.
645
646    The function getBlockByrefType dives into the __Block_byref_x_VarName
647    struct to find the original type of the variable, which is then assigned to
648    the variable's Debug Information Entry as its real type.  So far, so good.
649    However now the debugger will expect the variable VarName to have the type
650    SomeType.  So we need the location attribute for the variable to be an
651    expression that explains to the debugger how to navigate through the
652    pointers and struct to find the actual variable of type SomeType.
653
654    The following function does just that.  We start by getting
655    the "normal" location for the variable. This will be the location
656    of either the struct __Block_byref_x_VarName or the pointer to the
657    struct __Block_byref_x_VarName.
658
659    The struct will look something like:
660
661    struct __Block_byref_x_VarName {
662      ... <various fields>
663      struct __Block_byref_x_VarName *forwarding;
664      ... <various other fields>
665      SomeType VarName;
666      ... <maybe more fields>
667    };
668
669    If we are given the struct directly (as our starting point) we
670    need to tell the debugger to:
671
672    1).  Add the offset of the forwarding field.
673
674    2).  Follow that pointer to get the real __Block_byref_x_VarName
675    struct to use (the real one may have been copied onto the heap).
676
677    3).  Add the offset for the field VarName, to find the actual variable.
678
679    If we started with a pointer to the struct, then we need to
680    dereference that pointer first, before the other steps.
681    Translating this into DWARF ops, we will need to append the following
682    to the current location description for the variable:
683
684    DW_OP_deref                    -- optional, if we start with a pointer
685    DW_OP_plus_uconst <forward_fld_offset>
686    DW_OP_deref
687    DW_OP_plus_uconst <varName_fld_offset>
688
689    That is what this function does.  */
690
691 /// addBlockByrefAddress - Start with the address based on the location
692 /// provided, and generate the DWARF information necessary to find the
693 /// actual Block variable (navigating the Block struct) based on the
694 /// starting location.  Add the DWARF information to the die.  For
695 /// more information, read large comment just above here.
696 ///
697 void DwarfDebug::addBlockByrefAddress(DbgVariable *&DV, DIE *Die,
698                                       unsigned Attribute,
699                                       const MachineLocation &Location) {
700   const DIVariable &VD = DV->getVariable();
701   DIType Ty = VD.getType();
702   DIType TmpTy = Ty;
703   unsigned Tag = Ty.getTag();
704   bool isPointer = false;
705
706   StringRef varName = VD.getName();
707
708   if (Tag == dwarf::DW_TAG_pointer_type) {
709     DIDerivedType DTy = DIDerivedType(Ty);
710     TmpTy = DTy.getTypeDerivedFrom();
711     isPointer = true;
712   }
713
714   DICompositeType blockStruct = DICompositeType(TmpTy);
715
716   // Find the __forwarding field and the variable field in the __Block_byref
717   // struct.
718   DIArray Fields = blockStruct.getTypeArray();
719   DIDescriptor varField = DIDescriptor();
720   DIDescriptor forwardingField = DIDescriptor();
721
722   for (unsigned i = 0, N = Fields.getNumElements(); i < N; ++i) {
723     DIDescriptor Element = Fields.getElement(i);
724     DIDerivedType DT = DIDerivedType(Element);
725     StringRef fieldName = DT.getName();
726     if (fieldName == "__forwarding")
727       forwardingField = Element;
728     else if (fieldName == varName)
729       varField = Element;
730   }
731
732   // Get the offsets for the forwarding field and the variable field.
733   unsigned forwardingFieldOffset =
734     DIDerivedType(forwardingField).getOffsetInBits() >> 3;
735   unsigned varFieldOffset =
736     DIDerivedType(varField).getOffsetInBits() >> 3;
737
738   // Decode the original location, and use that as the start of the byref
739   // variable's location.
740   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
741   unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
742   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
743
744   if (Location.isReg()) {
745     if (Reg < 32)
746       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
747     else {
748       Reg = Reg - dwarf::DW_OP_reg0;
749       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
750       addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
751     }
752   } else {
753     if (Reg < 32)
754       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
755     else {
756       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
757       addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
758     }
759
760     addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
761   }
762
763   // If we started with a pointer to the __Block_byref... struct, then
764   // the first thing we need to do is dereference the pointer (DW_OP_deref).
765   if (isPointer)
766     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
767
768   // Next add the offset for the '__forwarding' field:
769   // DW_OP_plus_uconst ForwardingFieldOffset.  Note there's no point in
770   // adding the offset if it's 0.
771   if (forwardingFieldOffset > 0) {
772     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
773     addUInt(Block, 0, dwarf::DW_FORM_udata, forwardingFieldOffset);
774   }
775
776   // Now dereference the __forwarding field to get to the real __Block_byref
777   // struct:  DW_OP_deref.
778   addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
779
780   // Now that we've got the real __Block_byref... struct, add the offset
781   // for the variable's field to get to the location of the actual variable:
782   // DW_OP_plus_uconst varFieldOffset.  Again, don't add if it's 0.
783   if (varFieldOffset > 0) {
784     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
785     addUInt(Block, 0, dwarf::DW_FORM_udata, varFieldOffset);
786   }
787
788   // Now attach the location information to the DIE.
789   addBlock(Die, Attribute, 0, Block);
790 }
791
792 /// addAddress - Add an address attribute to a die based on the location
793 /// provided.
794 void DwarfDebug::addAddress(DIE *Die, unsigned Attribute,
795                             const MachineLocation &Location) {
796   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
797   unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
798   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
799
800   if (Location.isReg()) {
801     if (Reg < 32) {
802       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_reg0 + Reg);
803     } else {
804       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_regx);
805       addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
806     }
807   } else {
808     if (Reg < 32) {
809       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_breg0 + Reg);
810     } else {
811       addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_bregx);
812       addUInt(Block, 0, dwarf::DW_FORM_udata, Reg);
813     }
814
815     addUInt(Block, 0, dwarf::DW_FORM_sdata, Location.getOffset());
816   }
817
818   addBlock(Die, Attribute, 0, Block);
819 }
820
821 /// addRegisterAddress - Add register location entry in variable DIE.
822 bool DwarfDebug::addRegisterAddress(DIE *Die, DbgVariable *DV,
823                                     const MachineOperand &MO) {
824   assert (MO.isReg() && "Invalid machine operand!");
825   if (!MO.getReg())
826     return false;
827   MachineLocation Location;
828   Location.set(MO.getReg());
829   addAddress(Die, dwarf::DW_AT_location, Location);
830   if (MCSymbol *VS = DV->getDbgValueLabel())
831     addLabel(Die, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr, VS);
832   return true;
833 }
834
835 /// addConstantValue - Add constant value entry in variable DIE.
836 bool DwarfDebug::addConstantValue(DIE *Die, DbgVariable *DV, 
837                                   const MachineOperand &MO) {
838   assert (MO.isImm() && "Invalid machine operand!");
839   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
840   unsigned Imm = MO.getImm();
841   addUInt(Block, 0, dwarf::DW_FORM_udata, Imm);
842   addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
843   if (MCSymbol *VS = DV->getDbgValueLabel())
844     addLabel(Die, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr, VS);
845   return true;
846 }
847
848 /// addConstantFPValue - Add constant value entry in variable DIE.
849 bool DwarfDebug::addConstantFPValue(DIE *Die, DbgVariable *DV, 
850                                     const MachineOperand &MO) {
851   assert (MO.isFPImm() && "Invalid machine operand!");
852   DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
853   APFloat FPImm = MO.getFPImm()->getValueAPF();
854   
855   // Get the raw data form of the floating point.
856   const APInt FltVal = FPImm.bitcastToAPInt();
857   const char *FltPtr = (const char*)FltVal.getRawData();
858   
859   int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte.
860   bool LittleEndian = Asm->getTargetData().isLittleEndian();
861   int Incr = (LittleEndian ? 1 : -1);
862   int Start = (LittleEndian ? 0 : NumBytes - 1);
863   int Stop = (LittleEndian ? NumBytes : -1);
864   
865   // Output the constant to DWARF one byte at a time.
866   for (; Start != Stop; Start += Incr)
867     addUInt(Block, 0, dwarf::DW_FORM_data1,
868             (unsigned char)0xFF & FltPtr[Start]);
869   
870   addBlock(Die, dwarf::DW_AT_const_value, 0, Block);
871   
872   if (MCSymbol *VS = DV->getDbgValueLabel())
873     addLabel(Die, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr,
874              VS);
875   return true; 
876 }
877
878
879 /// addToContextOwner - Add Die into the list of its context owner's children.
880 void DwarfDebug::addToContextOwner(DIE *Die, DIDescriptor Context) {
881   if (Context.isType()) {
882     DIE *ContextDIE = getOrCreateTypeDIE(DIType(Context));
883     ContextDIE->addChild(Die);
884   } else if (Context.isNameSpace()) {
885     DIE *ContextDIE = getOrCreateNameSpace(DINameSpace(Context));
886     ContextDIE->addChild(Die);
887   } else if (DIE *ContextDIE = getCompileUnit(Context)->getDIE(Context))
888     ContextDIE->addChild(Die);
889   else 
890     getCompileUnit(Context)->addDie(Die);
891 }
892
893 /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the
894 /// given DIType.
895 DIE *DwarfDebug::getOrCreateTypeDIE(DIType Ty) {
896   CompileUnit *TypeCU = getCompileUnit(Ty);
897   DIE *TyDIE = TypeCU->getDIE(Ty);
898   if (TyDIE)
899     return TyDIE;
900
901   // Create new type.
902   TyDIE = new DIE(dwarf::DW_TAG_base_type);
903   TypeCU->insertDIE(Ty, TyDIE);
904   if (Ty.isBasicType())
905     constructTypeDIE(*TyDIE, DIBasicType(Ty));
906   else if (Ty.isCompositeType())
907     constructTypeDIE(*TyDIE, DICompositeType(Ty));
908   else {
909     assert(Ty.isDerivedType() && "Unknown kind of DIType");
910     constructTypeDIE(*TyDIE, DIDerivedType(Ty));
911   }
912
913   addToContextOwner(TyDIE, Ty.getContext());
914   return TyDIE;
915 }
916
917 /// addType - Add a new type attribute to the specified entity.
918 void DwarfDebug::addType(DIE *Entity, DIType Ty) {
919   if (!Ty.Verify())
920     return;
921
922   // Check for pre-existence.
923   CompileUnit *TypeCU = getCompileUnit(Ty);
924   DIEEntry *Entry = TypeCU->getDIEEntry(Ty);
925   // If it exists then use the existing value.
926   if (Entry) {
927     Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
928     return;
929   }
930
931   // Construct type.
932   DIE *Buffer = getOrCreateTypeDIE(Ty);
933
934   // Set up proxy.
935   Entry = createDIEEntry(Buffer);
936   TypeCU->insertDIEEntry(Ty, Entry);
937
938   Entity->addValue(dwarf::DW_AT_type, dwarf::DW_FORM_ref4, Entry);
939 }
940
941 /// constructTypeDIE - Construct basic type die from DIBasicType.
942 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIBasicType BTy) {
943   // Get core information.
944   StringRef Name = BTy.getName();
945   Buffer.setTag(dwarf::DW_TAG_base_type);
946   addUInt(&Buffer, dwarf::DW_AT_encoding,  dwarf::DW_FORM_data1,
947           BTy.getEncoding());
948
949   // Add name if not anonymous or intermediate type.
950   if (!Name.empty())
951     addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
952   uint64_t Size = BTy.getSizeInBits() >> 3;
953   addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
954 }
955
956 /// constructTypeDIE - Construct derived type die from DIDerivedType.
957 void DwarfDebug::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) {
958   // Get core information.
959   StringRef Name = DTy.getName();
960   uint64_t Size = DTy.getSizeInBits() >> 3;
961   unsigned Tag = DTy.getTag();
962
963   // FIXME - Workaround for templates.
964   if (Tag == dwarf::DW_TAG_inheritance) Tag = dwarf::DW_TAG_reference_type;
965
966   Buffer.setTag(Tag);
967
968   // Map to main type, void will not have a type.
969   DIType FromTy = DTy.getTypeDerivedFrom();
970   addType(&Buffer, FromTy);
971
972   // Add name if not anonymous or intermediate type.
973   if (!Name.empty())
974     addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
975
976   // Add size if non-zero (derived types might be zero-sized.)
977   if (Size)
978     addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
979
980   // Add source line info if available and TyDesc is not a forward declaration.
981   if (!DTy.isForwardDecl())
982     addSourceLine(&Buffer, &DTy);
983 }
984
985 /// constructTypeDIE - Construct type DIE from DICompositeType.
986 void DwarfDebug::constructTypeDIE(DIE &Buffer, DICompositeType CTy) {
987   // Get core information.
988   StringRef Name = CTy.getName();
989
990   uint64_t Size = CTy.getSizeInBits() >> 3;
991   unsigned Tag = CTy.getTag();
992   Buffer.setTag(Tag);
993
994   switch (Tag) {
995   case dwarf::DW_TAG_vector_type:
996   case dwarf::DW_TAG_array_type:
997     constructArrayTypeDIE(Buffer, &CTy);
998     break;
999   case dwarf::DW_TAG_enumeration_type: {
1000     DIArray Elements = CTy.getTypeArray();
1001
1002     // Add enumerators to enumeration type.
1003     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1004       DIE *ElemDie = NULL;
1005       DIDescriptor Enum(Elements.getElement(i));
1006       if (Enum.isEnumerator()) {
1007         ElemDie = constructEnumTypeDIE(DIEnumerator(Enum));
1008         Buffer.addChild(ElemDie);
1009       }
1010     }
1011   }
1012     break;
1013   case dwarf::DW_TAG_subroutine_type: {
1014     // Add return type.
1015     DIArray Elements = CTy.getTypeArray();
1016     DIDescriptor RTy = Elements.getElement(0);
1017     addType(&Buffer, DIType(RTy));
1018
1019     // Add prototype flag.
1020     addUInt(&Buffer, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1021
1022     // Add arguments.
1023     for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
1024       DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1025       DIDescriptor Ty = Elements.getElement(i);
1026       addType(Arg, DIType(Ty));
1027       Buffer.addChild(Arg);
1028     }
1029   }
1030     break;
1031   case dwarf::DW_TAG_structure_type:
1032   case dwarf::DW_TAG_union_type:
1033   case dwarf::DW_TAG_class_type: {
1034     // Add elements to structure type.
1035     DIArray Elements = CTy.getTypeArray();
1036
1037     // A forward struct declared type may not have elements available.
1038     unsigned N = Elements.getNumElements();
1039     if (N == 0)
1040       break;
1041
1042     // Add elements to structure type.
1043     for (unsigned i = 0; i < N; ++i) {
1044       DIDescriptor Element = Elements.getElement(i);
1045       DIE *ElemDie = NULL;
1046       if (Element.isSubprogram())
1047         ElemDie = createSubprogramDIE(DISubprogram(Element));
1048       else if (Element.isVariable()) {
1049         DIVariable DV(Element);
1050         ElemDie = new DIE(dwarf::DW_TAG_variable);
1051         addString(ElemDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1052                   DV.getName());
1053         addType(ElemDie, DV.getType());
1054         addUInt(ElemDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1055         addUInt(ElemDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1056         addSourceLine(ElemDie, &DV);
1057       } else if (Element.isDerivedType())
1058         ElemDie = createMemberDIE(DIDerivedType(Element));
1059       else
1060         continue;
1061       Buffer.addChild(ElemDie);
1062     }
1063
1064     if (CTy.isAppleBlockExtension())
1065       addUInt(&Buffer, dwarf::DW_AT_APPLE_block, dwarf::DW_FORM_flag, 1);
1066
1067     unsigned RLang = CTy.getRunTimeLang();
1068     if (RLang)
1069       addUInt(&Buffer, dwarf::DW_AT_APPLE_runtime_class,
1070               dwarf::DW_FORM_data1, RLang);
1071
1072     DICompositeType ContainingType = CTy.getContainingType();
1073     if (DIDescriptor(ContainingType).isCompositeType())
1074       addDIEEntry(&Buffer, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, 
1075                   getOrCreateTypeDIE(DIType(ContainingType)));
1076     break;
1077   }
1078   default:
1079     break;
1080   }
1081
1082   // Add name if not anonymous or intermediate type.
1083   if (!Name.empty())
1084     addString(&Buffer, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1085
1086   if (Tag == dwarf::DW_TAG_enumeration_type || Tag == dwarf::DW_TAG_class_type ||
1087       Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) {
1088     // Add size if non-zero (derived types might be zero-sized.)
1089     if (Size)
1090       addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, Size);
1091     else {
1092       // Add zero size if it is not a forward declaration.
1093       if (CTy.isForwardDecl())
1094         addUInt(&Buffer, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1095       else
1096         addUInt(&Buffer, dwarf::DW_AT_byte_size, 0, 0);
1097     }
1098
1099     // Add source line info if available.
1100     if (!CTy.isForwardDecl())
1101       addSourceLine(&Buffer, &CTy);
1102   }
1103 }
1104
1105 /// constructSubrangeDIE - Construct subrange DIE from DISubrange.
1106 void DwarfDebug::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy){
1107   int64_t L = SR.getLo();
1108   int64_t H = SR.getHi();
1109   DIE *DW_Subrange = new DIE(dwarf::DW_TAG_subrange_type);
1110
1111   addDIEEntry(DW_Subrange, dwarf::DW_AT_type, dwarf::DW_FORM_ref4, IndexTy);
1112   if (L)
1113     addSInt(DW_Subrange, dwarf::DW_AT_lower_bound, 0, L);
1114   addSInt(DW_Subrange, dwarf::DW_AT_upper_bound, 0, H);
1115
1116   Buffer.addChild(DW_Subrange);
1117 }
1118
1119 /// constructArrayTypeDIE - Construct array type DIE from DICompositeType.
1120 void DwarfDebug::constructArrayTypeDIE(DIE &Buffer,
1121                                        DICompositeType *CTy) {
1122   Buffer.setTag(dwarf::DW_TAG_array_type);
1123   if (CTy->getTag() == dwarf::DW_TAG_vector_type)
1124     addUInt(&Buffer, dwarf::DW_AT_GNU_vector, dwarf::DW_FORM_flag, 1);
1125
1126   // Emit derived type.
1127   addType(&Buffer, CTy->getTypeDerivedFrom());
1128   DIArray Elements = CTy->getTypeArray();
1129
1130   // Get an anonymous type for index type.
1131   CompileUnit *TheCU = getCompileUnit(*CTy);
1132   DIE *IdxTy = TheCU->getIndexTyDie();
1133   if (!IdxTy) {
1134     // Construct an anonymous type for index type.
1135     IdxTy = new DIE(dwarf::DW_TAG_base_type);
1136     addUInt(IdxTy, dwarf::DW_AT_byte_size, 0, sizeof(int32_t));
1137     addUInt(IdxTy, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1,
1138             dwarf::DW_ATE_signed);
1139     TheCU->addDie(IdxTy);
1140     TheCU->setIndexTyDie(IdxTy);
1141   }
1142
1143   // Add subranges to array type.
1144   for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1145     DIDescriptor Element = Elements.getElement(i);
1146     if (Element.getTag() == dwarf::DW_TAG_subrange_type)
1147       constructSubrangeDIE(Buffer, DISubrange(Element), IdxTy);
1148   }
1149 }
1150
1151 /// constructEnumTypeDIE - Construct enum type DIE from DIEnumerator.
1152 DIE *DwarfDebug::constructEnumTypeDIE(DIEnumerator ETy) {
1153   DIE *Enumerator = new DIE(dwarf::DW_TAG_enumerator);
1154   StringRef Name = ETy.getName();
1155   addString(Enumerator, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1156   int64_t Value = ETy.getEnumValue();
1157   addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value);
1158   return Enumerator;
1159 }
1160
1161 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm 
1162 /// printer to not emit usual symbol prefix before the symbol name is used then
1163 /// return linkage name after skipping this special LLVM prefix.
1164 static StringRef getRealLinkageName(StringRef LinkageName) {
1165   char One = '\1';
1166   if (LinkageName.startswith(StringRef(&One, 1)))
1167     return LinkageName.substr(1);
1168   return LinkageName;
1169 }
1170
1171 /// createGlobalVariableDIE - Create new DIE using GV.
1172 DIE *DwarfDebug::createGlobalVariableDIE(const DIGlobalVariable &GV) {
1173   // If the global variable was optmized out then no need to create debug info
1174   // entry.
1175   if (!GV.getGlobal()) return NULL;
1176   if (GV.getDisplayName().empty()) return NULL;
1177
1178   DIE *GVDie = new DIE(dwarf::DW_TAG_variable);
1179   addString(GVDie, dwarf::DW_AT_name, dwarf::DW_FORM_string,
1180             GV.getDisplayName());
1181
1182   StringRef LinkageName = GV.getLinkageName();
1183   if (!LinkageName.empty())
1184     addString(GVDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1185               getRealLinkageName(LinkageName));
1186
1187   addType(GVDie, GV.getType());
1188   if (!GV.isLocalToUnit())
1189     addUInt(GVDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1190   addSourceLine(GVDie, &GV);
1191
1192   return GVDie;
1193 }
1194
1195 /// createMemberDIE - Create new member DIE.
1196 DIE *DwarfDebug::createMemberDIE(const DIDerivedType &DT) {
1197   DIE *MemberDie = new DIE(DT.getTag());
1198   StringRef Name = DT.getName();
1199   if (!Name.empty())
1200     addString(MemberDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1201   
1202   addType(MemberDie, DT.getTypeDerivedFrom());
1203
1204   addSourceLine(MemberDie, &DT);
1205
1206   DIEBlock *MemLocationDie = new (DIEValueAllocator) DIEBlock();
1207   addUInt(MemLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst);
1208
1209   uint64_t Size = DT.getSizeInBits();
1210   uint64_t FieldSize = DT.getOriginalTypeSize();
1211
1212   if (Size != FieldSize) {
1213     // Handle bitfield.
1214     addUInt(MemberDie, dwarf::DW_AT_byte_size, 0, DT.getOriginalTypeSize()>>3);
1215     addUInt(MemberDie, dwarf::DW_AT_bit_size, 0, DT.getSizeInBits());
1216
1217     uint64_t Offset = DT.getOffsetInBits();
1218     uint64_t AlignMask = ~(DT.getAlignInBits() - 1);
1219     uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1220     uint64_t FieldOffset = (HiMark - FieldSize);
1221     Offset -= FieldOffset;
1222
1223     // Maybe we need to work from the other end.
1224     if (Asm->getTargetData().isLittleEndian())
1225       Offset = FieldSize - (Offset + Size);
1226     addUInt(MemberDie, dwarf::DW_AT_bit_offset, 0, Offset);
1227
1228     // Here WD_AT_data_member_location points to the anonymous
1229     // field that includes this bit field.
1230     addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, FieldOffset >> 3);
1231
1232   } else
1233     // This is not a bitfield.
1234     addUInt(MemLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits() >> 3);
1235
1236   if (DT.getTag() == dwarf::DW_TAG_inheritance
1237       && DT.isVirtual()) {
1238
1239     // For C++, virtual base classes are not at fixed offset. Use following
1240     // expression to extract appropriate offset from vtable.
1241     // BaseAddr = ObAddr + *((*ObAddr) - Offset)
1242
1243     DIEBlock *VBaseLocationDie = new (DIEValueAllocator) DIEBlock();
1244     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_dup);
1245     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1246     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1247     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_udata, DT.getOffsetInBits());
1248     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_minus);
1249     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_deref);
1250     addUInt(VBaseLocationDie, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_plus);
1251
1252     addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, 
1253              VBaseLocationDie);
1254   } else
1255     addBlock(MemberDie, dwarf::DW_AT_data_member_location, 0, MemLocationDie);
1256
1257   if (DT.isProtected())
1258     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1259             dwarf::DW_ACCESS_protected);
1260   else if (DT.isPrivate())
1261     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1262             dwarf::DW_ACCESS_private);
1263   else if (DT.getTag() == dwarf::DW_TAG_inheritance)
1264     addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_flag,
1265             dwarf::DW_ACCESS_public);
1266   if (DT.isVirtual())
1267     addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag,
1268             dwarf::DW_VIRTUALITY_virtual);
1269   return MemberDie;
1270 }
1271
1272 /// createSubprogramDIE - Create new DIE using SP.
1273 DIE *DwarfDebug::createSubprogramDIE(const DISubprogram &SP, bool MakeDecl) {
1274   CompileUnit *SPCU = getCompileUnit(SP);
1275   DIE *SPDie = SPCU->getDIE(SP);
1276   if (SPDie)
1277     return SPDie;
1278
1279   SPDie = new DIE(dwarf::DW_TAG_subprogram);
1280   // Constructors and operators for anonymous aggregates do not have names.
1281   if (!SP.getName().empty())
1282     addString(SPDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, SP.getName());
1283
1284   StringRef LinkageName = SP.getLinkageName();
1285   if (!LinkageName.empty())
1286     addString(SPDie, dwarf::DW_AT_MIPS_linkage_name, dwarf::DW_FORM_string,
1287               getRealLinkageName(LinkageName));
1288
1289   addSourceLine(SPDie, &SP);
1290
1291   // Add prototyped tag, if C or ObjC.
1292   unsigned Lang = SP.getCompileUnit().getLanguage();
1293   if (Lang == dwarf::DW_LANG_C99 || Lang == dwarf::DW_LANG_C89 ||
1294       Lang == dwarf::DW_LANG_ObjC)
1295     addUInt(SPDie, dwarf::DW_AT_prototyped, dwarf::DW_FORM_flag, 1);
1296
1297   // Add Return Type.
1298   DICompositeType SPTy = SP.getType();
1299   DIArray Args = SPTy.getTypeArray();
1300   unsigned SPTag = SPTy.getTag();
1301
1302   if (Args.getNumElements() == 0 || SPTag != dwarf::DW_TAG_subroutine_type)
1303     addType(SPDie, SPTy);
1304   else
1305     addType(SPDie, DIType(Args.getElement(0)));
1306
1307   unsigned VK = SP.getVirtuality();
1308   if (VK) {
1309     addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_flag, VK);
1310     DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1311     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_constu);
1312     addUInt(Block, 0, dwarf::DW_FORM_data1, SP.getVirtualIndex());
1313     addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, 0, Block);
1314     ContainingTypeMap.insert(std::make_pair(SPDie, 
1315                                             SP.getContainingType()));
1316   }
1317
1318   if (MakeDecl || !SP.isDefinition()) {
1319     addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1320
1321     // Add arguments. Do not add arguments for subprogram definition. They will
1322     // be handled while processing variables.
1323     DICompositeType SPTy = SP.getType();
1324     DIArray Args = SPTy.getTypeArray();
1325     unsigned SPTag = SPTy.getTag();
1326
1327     if (SPTag == dwarf::DW_TAG_subroutine_type)
1328       for (unsigned i = 1, N =  Args.getNumElements(); i < N; ++i) {
1329         DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1330         DIType ATy = DIType(DIType(Args.getElement(i)));
1331         addType(Arg, ATy);
1332         if (ATy.isArtificial())
1333           addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1334         SPDie->addChild(Arg);
1335       }
1336   }
1337
1338   if (SP.isArtificial())
1339     addUInt(SPDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1340
1341   if (!SP.isLocalToUnit())
1342     addUInt(SPDie, dwarf::DW_AT_external, dwarf::DW_FORM_flag, 1);
1343   
1344   if (SP.isOptimized())
1345     addUInt(SPDie, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1346
1347   // DW_TAG_inlined_subroutine may refer to this DIE.
1348   SPCU->insertDIE(SP, SPDie);
1349
1350   return SPDie;
1351 }
1352
1353 DbgScope *DwarfDebug::getOrCreateAbstractScope(const MDNode *N) {
1354   assert(N && "Invalid Scope encoding!");
1355
1356   DbgScope *AScope = AbstractScopes.lookup(N);
1357   if (AScope)
1358     return AScope;
1359
1360   DbgScope *Parent = NULL;
1361
1362   DIDescriptor Scope(N);
1363   if (Scope.isLexicalBlock()) {
1364     DILexicalBlock DB(N);
1365     DIDescriptor ParentDesc = DB.getContext();
1366     Parent = getOrCreateAbstractScope(ParentDesc);
1367   }
1368
1369   AScope = new DbgScope(Parent, DIDescriptor(N), NULL);
1370
1371   if (Parent)
1372     Parent->addScope(AScope);
1373   AScope->setAbstractScope();
1374   AbstractScopes[N] = AScope;
1375   if (DIDescriptor(N).isSubprogram())
1376     AbstractScopesList.push_back(AScope);
1377   return AScope;
1378 }
1379
1380 /// isSubprogramContext - Return true if Context is either a subprogram
1381 /// or another context nested inside a subprogram.
1382 static bool isSubprogramContext(const MDNode *Context) {
1383   if (!Context)
1384     return false;
1385   DIDescriptor D(Context);
1386   if (D.isSubprogram())
1387     return true;
1388   if (D.isType())
1389     return isSubprogramContext(DIType(Context).getContext());
1390   return false;
1391 }
1392
1393 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
1394 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
1395 /// If there are global variables in this scope then create and insert
1396 /// DIEs for these variables.
1397 DIE *DwarfDebug::updateSubprogramScopeDIE(const MDNode *SPNode) {
1398   CompileUnit *SPCU = getCompileUnit(SPNode);
1399   DIE *SPDie = SPCU->getDIE(SPNode);
1400   assert(SPDie && "Unable to find subprogram DIE!");
1401   DISubprogram SP(SPNode);
1402   
1403   // There is not any need to generate specification DIE for a function
1404   // defined at compile unit level. If a function is defined inside another
1405   // function then gdb prefers the definition at top level and but does not
1406   // expect specification DIE in parent function. So avoid creating 
1407   // specification DIE for a function defined inside a function.
1408   if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
1409       !SP.getContext().isFile() && 
1410       !isSubprogramContext(SP.getContext())) {
1411     addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1412     
1413     // Add arguments. 
1414     DICompositeType SPTy = SP.getType();
1415     DIArray Args = SPTy.getTypeArray();
1416     unsigned SPTag = SPTy.getTag();
1417     if (SPTag == dwarf::DW_TAG_subroutine_type)
1418       for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
1419         DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
1420         DIType ATy = DIType(DIType(Args.getElement(i)));
1421         addType(Arg, ATy);
1422         if (ATy.isArtificial())
1423           addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1424         SPDie->addChild(Arg);
1425       }
1426     DIE *SPDeclDie = SPDie;
1427     SPDie = new DIE(dwarf::DW_TAG_subprogram);
1428     addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4, 
1429                 SPDeclDie);
1430     SPCU->addDie(SPDie);
1431   }
1432   
1433   addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1434            Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
1435   addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
1436            Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
1437   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
1438   MachineLocation Location(RI->getFrameRegister(*Asm->MF));
1439   addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
1440
1441   return SPDie;
1442 }
1443
1444 /// constructLexicalScope - Construct new DW_TAG_lexical_block
1445 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
1446 DIE *DwarfDebug::constructLexicalScopeDIE(DbgScope *Scope) {
1447
1448   DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
1449   if (Scope->isAbstractScope())
1450     return ScopeDIE;
1451
1452   const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1453   if (Ranges.empty())
1454     return 0;
1455
1456   SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1457   if (Ranges.size() > 1) {
1458     // .debug_range section has not been laid out yet. Emit offset in
1459     // .debug_range as a uint, size 4, for now. emitDIE will handle 
1460     // DW_AT_ranges appropriately.
1461     addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
1462             DebugRangeSymbols.size() * Asm->getTargetData().getPointerSize());
1463     for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
1464          RE = Ranges.end(); RI != RE; ++RI) {
1465       DebugRangeSymbols.push_back(LabelsBeforeInsn.lookup(RI->first));
1466       DebugRangeSymbols.push_back(LabelsAfterInsn.lookup(RI->second));
1467     }
1468     DebugRangeSymbols.push_back(NULL);
1469     DebugRangeSymbols.push_back(NULL);
1470     return ScopeDIE;
1471   }
1472
1473   MCSymbol *Start = LabelsBeforeInsn.lookup(RI->first);
1474   MCSymbol *End = LabelsAfterInsn.lookup(RI->second);
1475
1476   if (Start == 0 || End == 0) return 0;
1477
1478   assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
1479   assert(End->isDefined() && "Invalid end label for an inlined scope!");
1480   
1481   addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
1482   addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
1483
1484   return ScopeDIE;
1485 }
1486
1487 /// constructInlinedScopeDIE - This scope represents inlined body of
1488 /// a function. Construct DIE to represent this concrete inlined copy
1489 /// of the function.
1490 DIE *DwarfDebug::constructInlinedScopeDIE(DbgScope *Scope) {
1491
1492   const SmallVector<DbgRange, 4> &Ranges = Scope->getRanges();
1493   assert (Ranges.empty() == false 
1494           && "DbgScope does not have instruction markers!");
1495
1496   // FIXME : .debug_inlined section specification does not clearly state how
1497   // to emit inlined scope that is split into multiple instruction ranges.
1498   // For now, use first instruction range and emit low_pc/high_pc pair and
1499   // corresponding .debug_inlined section entry for this pair.
1500   SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin();
1501   MCSymbol *StartLabel = LabelsBeforeInsn.lookup(RI->first);
1502   MCSymbol *EndLabel = LabelsAfterInsn.lookup(RI->second);
1503
1504   if (StartLabel == 0 || EndLabel == 0) {
1505     assert (0 && "Unexpected Start and End  labels for a inlined scope!");
1506     return 0;
1507   }
1508   assert(StartLabel->isDefined() &&
1509          "Invalid starting label for an inlined scope!");
1510   assert(EndLabel->isDefined() &&
1511          "Invalid end label for an inlined scope!");
1512
1513   if (!Scope->getScopeNode())
1514     return NULL;
1515   DIScope DS(Scope->getScopeNode());
1516   DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
1517
1518   DISubprogram InlinedSP = getDISubprogram(DS);
1519   CompileUnit *TheCU = getCompileUnit(InlinedSP);
1520   DIE *OriginDIE = TheCU->getDIE(InlinedSP);
1521   assert(OriginDIE && "Unable to find Origin DIE!");
1522   addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
1523               dwarf::DW_FORM_ref4, OriginDIE);
1524
1525   addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, StartLabel);
1526   addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, EndLabel);
1527
1528   InlinedSubprogramDIEs.insert(OriginDIE);
1529
1530   // Track the start label for this inlined function.
1531   DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
1532     I = InlineInfo.find(InlinedSP);
1533
1534   if (I == InlineInfo.end()) {
1535     InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel,
1536                                                              ScopeDIE));
1537     InlinedSPNodes.push_back(InlinedSP);
1538   } else
1539     I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
1540
1541   DILocation DL(Scope->getInlinedAt());
1542   addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, TheCU->getID());
1543   addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
1544
1545   return ScopeDIE;
1546 }
1547
1548
1549 /// constructVariableDIE - Construct a DIE for the given DbgVariable.
1550 DIE *DwarfDebug::constructVariableDIE(DbgVariable *DV, DbgScope *Scope) {
1551   // Get the descriptor.
1552   const DIVariable &VD = DV->getVariable();
1553   StringRef Name = VD.getName();
1554   if (Name.empty())
1555     return NULL;
1556
1557   // Translate tag to proper Dwarf tag.  The result variable is dropped for
1558   // now.
1559   unsigned Tag;
1560   switch (VD.getTag()) {
1561   case dwarf::DW_TAG_return_variable:
1562     return NULL;
1563   case dwarf::DW_TAG_arg_variable:
1564     Tag = dwarf::DW_TAG_formal_parameter;
1565     break;
1566   case dwarf::DW_TAG_auto_variable:    // fall thru
1567   default:
1568     Tag = dwarf::DW_TAG_variable;
1569     break;
1570   }
1571
1572   // Define variable debug information entry.
1573   DIE *VariableDie = new DIE(Tag);
1574
1575
1576   DIE *AbsDIE = NULL;
1577   if (DbgVariable *AV = DV->getAbstractVariable())
1578     AbsDIE = AV->getDIE();
1579
1580   if (AbsDIE) {
1581     DIScope DS(Scope->getScopeNode());
1582     DISubprogram InlinedSP = getDISubprogram(DS);
1583     DIE *OriginSPDIE = getCompileUnit(InlinedSP)->getDIE(InlinedSP);
1584     (void) OriginSPDIE;
1585     assert(OriginSPDIE && "Unable to find Origin DIE for the SP!");
1586     DIE *AbsDIE = DV->getAbstractVariable()->getDIE();
1587     assert(AbsDIE && "Unable to find Origin DIE for the Variable!");
1588     addDIEEntry(VariableDie, dwarf::DW_AT_abstract_origin,
1589                 dwarf::DW_FORM_ref4, AbsDIE);
1590   }
1591   else {
1592     addString(VariableDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, Name);
1593     addSourceLine(VariableDie, &VD);
1594
1595     // Add variable type.
1596     // FIXME: isBlockByrefVariable should be reformulated in terms of complex
1597     // addresses instead.
1598     if (VD.isBlockByrefVariable())
1599       addType(VariableDie, getBlockByrefType(VD.getType(), Name));
1600     else
1601       addType(VariableDie, VD.getType());
1602   }
1603
1604   // Add variable address.
1605   if (!Scope->isAbstractScope()) {
1606     // Check if variable is described by DBG_VALUE instruction.
1607     if (const MachineInstr *DVInsn = DV->getDbgValue()) {
1608       bool updated = false;
1609       // FIXME : Handle getNumOperands != 3 
1610       if (DVInsn->getNumOperands() == 3) {
1611         if (DVInsn->getOperand(0).isReg())
1612           updated = addRegisterAddress(VariableDie, DV, DVInsn->getOperand(0));
1613         else if (DVInsn->getOperand(0).isImm())
1614           updated = addConstantValue(VariableDie, DV, DVInsn->getOperand(0));
1615         else if (DVInsn->getOperand(0).isFPImm()) 
1616           updated = addConstantFPValue(VariableDie, DV, DVInsn->getOperand(0));
1617       } else {
1618         MachineLocation Location = Asm->getDebugValueLocation(DVInsn);
1619         if (Location.getReg()) {
1620           addAddress(VariableDie, dwarf::DW_AT_location, Location);
1621           if (MCSymbol *VS = DV->getDbgValueLabel())
1622             addLabel(VariableDie, dwarf::DW_AT_start_scope, dwarf::DW_FORM_addr,
1623                      VS);
1624           updated = true;
1625         }
1626       }
1627       if (!updated) {
1628         // If variableDie is not updated then DBG_VALUE instruction does not
1629         // have valid variable info.
1630         delete VariableDie;
1631         return NULL;
1632       }
1633     } 
1634     else {
1635       MachineLocation Location;
1636       unsigned FrameReg;
1637       const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
1638       if (DV->hasLocation()) {
1639         int Offset = RI->getFrameIndexReference(*Asm->MF, DV->getFrameIndex(),
1640                                                 FrameReg);
1641         Location.set(FrameReg, Offset);
1642         
1643         if (VD.hasComplexAddress())
1644           addComplexAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1645         else if (VD.isBlockByrefVariable())
1646           addBlockByrefAddress(DV, VariableDie, dwarf::DW_AT_location, Location);
1647         else
1648           addAddress(VariableDie, dwarf::DW_AT_location, Location);
1649       }
1650     }
1651   }
1652
1653   if (Tag == dwarf::DW_TAG_formal_parameter && VD.getType().isArtificial())
1654     addUInt(VariableDie, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
1655   DV->setDIE(VariableDie);
1656   return VariableDie;
1657
1658 }
1659
1660 void DwarfDebug::addPubTypes(DISubprogram SP) {
1661   DICompositeType SPTy = SP.getType();
1662   unsigned SPTag = SPTy.getTag();
1663   if (SPTag != dwarf::DW_TAG_subroutine_type) 
1664     return;
1665
1666   DIArray Args = SPTy.getTypeArray();
1667   for (unsigned i = 0, e = Args.getNumElements(); i != e; ++i) {
1668     DIType ATy(Args.getElement(i));
1669     if (!ATy.Verify())
1670       continue;
1671     DICompositeType CATy = getDICompositeType(ATy);
1672     if (DIDescriptor(CATy).Verify() && !CATy.getName().empty()
1673         && !CATy.isForwardDecl()) {
1674       CompileUnit *TheCU = getCompileUnit(CATy);
1675       if (DIEEntry *Entry = TheCU->getDIEEntry(CATy))
1676         TheCU->addGlobalType(CATy.getName(), Entry->getEntry());
1677     }
1678   }
1679 }
1680
1681 /// constructScopeDIE - Construct a DIE for this scope.
1682 DIE *DwarfDebug::constructScopeDIE(DbgScope *Scope) {
1683   if (!Scope || !Scope->getScopeNode())
1684     return NULL;
1685  
1686   DIScope DS(Scope->getScopeNode());
1687   DIE *ScopeDIE = NULL;
1688   if (Scope->getInlinedAt())
1689     ScopeDIE = constructInlinedScopeDIE(Scope);
1690   else if (DS.isSubprogram()) {
1691     if (Scope->isAbstractScope())
1692       ScopeDIE = getCompileUnit(DS)->getDIE(DS);
1693     else
1694       ScopeDIE = updateSubprogramScopeDIE(DS);
1695   }
1696   else
1697     ScopeDIE = constructLexicalScopeDIE(Scope);
1698   if (!ScopeDIE) return NULL;
1699   
1700   // Add variables to scope.
1701   const SmallVector<DbgVariable *, 8> &Variables = Scope->getVariables();
1702   for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1703     DIE *VariableDIE = constructVariableDIE(Variables[i], Scope);
1704     if (VariableDIE)
1705       ScopeDIE->addChild(VariableDIE);
1706   }
1707
1708   // Add nested scopes.
1709   const SmallVector<DbgScope *, 4> &Scopes = Scope->getScopes();
1710   for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1711     // Define the Scope debug information entry.
1712     DIE *NestedDIE = constructScopeDIE(Scopes[j]);
1713     if (NestedDIE)
1714       ScopeDIE->addChild(NestedDIE);
1715   }
1716
1717   if (DS.isSubprogram()) 
1718     addPubTypes(DISubprogram(DS));
1719  
1720  return ScopeDIE;
1721 }
1722
1723 /// GetOrCreateSourceID - Look up the source id with the given directory and
1724 /// source file names. If none currently exists, create a new id and insert it
1725 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
1726 /// maps as well.
1727 unsigned DwarfDebug::GetOrCreateSourceID(StringRef DirName, StringRef FileName){
1728   unsigned DId;
1729   StringMap<unsigned>::iterator DI = DirectoryIdMap.find(DirName);
1730   if (DI != DirectoryIdMap.end()) {
1731     DId = DI->getValue();
1732   } else {
1733     DId = DirectoryNames.size() + 1;
1734     DirectoryIdMap[DirName] = DId;
1735     DirectoryNames.push_back(DirName);
1736   }
1737
1738   unsigned FId;
1739   StringMap<unsigned>::iterator FI = SourceFileIdMap.find(FileName);
1740   if (FI != SourceFileIdMap.end()) {
1741     FId = FI->getValue();
1742   } else {
1743     FId = SourceFileNames.size() + 1;
1744     SourceFileIdMap[FileName] = FId;
1745     SourceFileNames.push_back(FileName);
1746   }
1747
1748   DenseMap<std::pair<unsigned, unsigned>, unsigned>::iterator SI =
1749     SourceIdMap.find(std::make_pair(DId, FId));
1750   if (SI != SourceIdMap.end())
1751     return SI->second;
1752
1753   unsigned SrcId = SourceIds.size() + 1;  // DW_AT_decl_file cannot be 0.
1754   SourceIdMap[std::make_pair(DId, FId)] = SrcId;
1755   SourceIds.push_back(std::make_pair(DId, FId));
1756
1757   return SrcId;
1758 }
1759
1760 /// getOrCreateNameSpace - Create a DIE for DINameSpace.
1761 DIE *DwarfDebug::getOrCreateNameSpace(DINameSpace NS) {
1762   CompileUnit *TheCU = getCompileUnit(NS);
1763   DIE *NDie = TheCU->getDIE(NS);
1764   if (NDie)
1765     return NDie;
1766   NDie = new DIE(dwarf::DW_TAG_namespace);
1767   TheCU->insertDIE(NS, NDie);
1768   if (!NS.getName().empty())
1769     addString(NDie, dwarf::DW_AT_name, dwarf::DW_FORM_string, NS.getName());
1770   addSourceLine(NDie, &NS);
1771   addToContextOwner(NDie, NS.getContext());
1772   return NDie;
1773 }
1774
1775 /// constructCompileUnit - Create new CompileUnit for the given 
1776 /// metadata node with tag DW_TAG_compile_unit.
1777 void DwarfDebug::constructCompileUnit(const MDNode *N) {
1778   DICompileUnit DIUnit(N);
1779   StringRef FN = DIUnit.getFilename();
1780   StringRef Dir = DIUnit.getDirectory();
1781   unsigned ID = GetOrCreateSourceID(Dir, FN);
1782
1783   DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
1784   addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
1785             DIUnit.getProducer());
1786   addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data1,
1787           DIUnit.getLanguage());
1788   addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
1789   // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
1790   // simplifies debug range entries.
1791   addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_data4, 0);
1792   // DW_AT_stmt_list is a offset of line number information for this
1793   // compile unit in debug_line section. It is always zero when only one
1794   // compile unit is emitted in one object file.
1795   addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
1796
1797   if (!Dir.empty())
1798     addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
1799   if (DIUnit.isOptimized())
1800     addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
1801
1802   StringRef Flags = DIUnit.getFlags();
1803   if (!Flags.empty())
1804     addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string, Flags);
1805
1806   unsigned RVer = DIUnit.getRunTimeVersion();
1807   if (RVer)
1808     addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
1809             dwarf::DW_FORM_data1, RVer);
1810
1811   CompileUnit *NewCU = new CompileUnit(ID, Die);
1812   if (!FirstCU)
1813     FirstCU = NewCU;
1814   CUMap.insert(std::make_pair(N, NewCU));
1815 }
1816
1817 /// getCompielUnit - Get CompileUnit DIE.
1818 CompileUnit *DwarfDebug::getCompileUnit(const MDNode *N) const {
1819   assert (N && "Invalid DwarfDebug::getCompileUnit argument!");
1820   DIDescriptor D(N);
1821   const MDNode *CUNode = NULL;
1822   if (D.isCompileUnit())
1823     CUNode = N;
1824   else if (D.isSubprogram())
1825     CUNode = DISubprogram(N).getCompileUnit();
1826   else if (D.isType())
1827     CUNode = DIType(N).getCompileUnit();
1828   else if (D.isGlobalVariable())
1829     CUNode = DIGlobalVariable(N).getCompileUnit();
1830   else if (D.isVariable())
1831     CUNode = DIVariable(N).getCompileUnit();
1832   else if (D.isNameSpace())
1833     CUNode = DINameSpace(N).getCompileUnit();
1834   else if (D.isFile())
1835     CUNode = DIFile(N).getCompileUnit();
1836   else
1837     return FirstCU;
1838
1839   DenseMap<const MDNode *, CompileUnit *>::const_iterator I
1840     = CUMap.find(CUNode);
1841   if (I == CUMap.end())
1842     return FirstCU;
1843   return I->second;
1844 }
1845
1846
1847 /// constructGlobalVariableDIE - Construct global variable DIE.
1848 void DwarfDebug::constructGlobalVariableDIE(const MDNode *N) {
1849   DIGlobalVariable DI_GV(N);
1850
1851   // If debug information is malformed then ignore it.
1852   if (DI_GV.Verify() == false)
1853     return;
1854
1855   // Check for pre-existence.
1856   CompileUnit *TheCU = getCompileUnit(N);
1857   if (TheCU->getDIE(DI_GV))
1858     return;
1859
1860   DIE *VariableDie = createGlobalVariableDIE(DI_GV);
1861   if (!VariableDie)
1862     return;
1863
1864   // Add to map.
1865   TheCU->insertDIE(N, VariableDie);
1866
1867   // Add to context owner.
1868   DIDescriptor GVContext = DI_GV.getContext();
1869   // Do not create specification DIE if context is either compile unit
1870   // or a subprogram.
1871   if (DI_GV.isDefinition() && !GVContext.isCompileUnit() &&
1872       !GVContext.isFile() && 
1873       !isSubprogramContext(GVContext)) {
1874     // Create specification DIE.
1875     DIE *VariableSpecDIE = new DIE(dwarf::DW_TAG_variable);
1876     addDIEEntry(VariableSpecDIE, dwarf::DW_AT_specification,
1877                 dwarf::DW_FORM_ref4, VariableDie);
1878     DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1879     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1880     addLabel(Block, 0, dwarf::DW_FORM_udata,
1881              Asm->Mang->getSymbol(DI_GV.getGlobal()));
1882     addBlock(VariableSpecDIE, dwarf::DW_AT_location, 0, Block);
1883     addUInt(VariableDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
1884     TheCU->addDie(VariableSpecDIE);
1885   } else {
1886     DIEBlock *Block = new (DIEValueAllocator) DIEBlock();
1887     addUInt(Block, 0, dwarf::DW_FORM_data1, dwarf::DW_OP_addr);
1888     addLabel(Block, 0, dwarf::DW_FORM_udata,
1889              Asm->Mang->getSymbol(DI_GV.getGlobal()));
1890     addBlock(VariableDie, dwarf::DW_AT_location, 0, Block);
1891   }
1892   addToContextOwner(VariableDie, GVContext);
1893   
1894   // Expose as global. FIXME - need to check external flag.
1895   TheCU->addGlobal(DI_GV.getName(), VariableDie);
1896
1897   DIType GTy = DI_GV.getType();
1898   if (GTy.isCompositeType() && !GTy.getName().empty()
1899       && !GTy.isForwardDecl()) {
1900     DIEEntry *Entry = TheCU->getDIEEntry(GTy);
1901     assert(Entry && "Missing global type!");
1902     TheCU->addGlobalType(GTy.getName(), Entry->getEntry());
1903   }
1904   return;
1905 }
1906
1907 /// construct SubprogramDIE - Construct subprogram DIE.
1908 void DwarfDebug::constructSubprogramDIE(const MDNode *N) {
1909   DISubprogram SP(N);
1910
1911   // Check for pre-existence.
1912   CompileUnit *TheCU = getCompileUnit(N);
1913   if (TheCU->getDIE(N))
1914     return;
1915
1916   if (!SP.isDefinition())
1917     // This is a method declaration which will be handled while constructing
1918     // class type.
1919     return;
1920
1921   DIE *SubprogramDie = createSubprogramDIE(SP);
1922
1923   // Add to map.
1924   TheCU->insertDIE(N, SubprogramDie);
1925
1926   // Add to context owner.
1927   addToContextOwner(SubprogramDie, SP.getContext());
1928
1929   // Expose as global.
1930   TheCU->addGlobal(SP.getName(), SubprogramDie);
1931
1932   return;
1933 }
1934
1935 /// beginModule - Emit all Dwarf sections that should come prior to the
1936 /// content. Create global DIEs and emit initial debug info sections.
1937 /// This is inovked by the target AsmPrinter.
1938 void DwarfDebug::beginModule(Module *M) {
1939   if (DisableDebugInfoPrinting)
1940     return;
1941
1942   DebugInfoFinder DbgFinder;
1943   DbgFinder.processModule(*M);
1944
1945   bool HasDebugInfo = false;
1946   
1947   // Scan all the compile-units to see if there are any marked as the main unit.
1948   // if not, we do not generate debug info.
1949   for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1950        E = DbgFinder.compile_unit_end(); I != E; ++I) {
1951     if (DICompileUnit(*I).isMain()) {
1952       HasDebugInfo = true;
1953       break;
1954     }
1955   }
1956   
1957   if (!HasDebugInfo) return;
1958
1959   // Tell MMI that we have debug info.
1960   MMI->setDebugInfoAvailability(true);
1961   
1962   // Emit initial sections.
1963   EmitSectionLabels();
1964   
1965   // Create all the compile unit DIEs.
1966   for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
1967          E = DbgFinder.compile_unit_end(); I != E; ++I)
1968     constructCompileUnit(*I);
1969
1970   // Create DIEs for each subprogram.
1971   for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
1972          E = DbgFinder.subprogram_end(); I != E; ++I)
1973     constructSubprogramDIE(*I);
1974
1975   // Create DIEs for each global variable.
1976   for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
1977          E = DbgFinder.global_variable_end(); I != E; ++I)
1978     constructGlobalVariableDIE(*I);
1979
1980   // Prime section data.
1981   SectionMap.insert(Asm->getObjFileLowering().getTextSection());
1982
1983   // Print out .file directives to specify files for .loc directives. These are
1984   // printed out early so that they precede any .loc directives.
1985   if (Asm->MAI->hasDotLocAndDotFile()) {
1986     for (unsigned i = 1, e = getNumSourceIds()+1; i != e; ++i) {
1987       // Remember source id starts at 1.
1988       std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(i);
1989       // FIXME: don't use sys::path for this!  This should not depend on the
1990       // host.
1991       sys::Path FullPath(getSourceDirectoryName(Id.first));
1992       bool AppendOk =
1993         FullPath.appendComponent(getSourceFileName(Id.second));
1994       assert(AppendOk && "Could not append filename to directory!");
1995       AppendOk = false;
1996       Asm->OutStreamer.EmitDwarfFileDirective(i, FullPath.str());
1997     }
1998   }
1999 }
2000
2001 /// endModule - Emit all Dwarf sections that should come after the content.
2002 ///
2003 void DwarfDebug::endModule() {
2004   if (!FirstCU) return;
2005
2006   // Attach DW_AT_inline attribute with inlined subprogram DIEs.
2007   for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
2008          AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
2009     DIE *ISP = *AI;
2010     addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
2011   }
2012
2013   for (DenseMap<DIE *, const MDNode *>::iterator CI = ContainingTypeMap.begin(),
2014          CE = ContainingTypeMap.end(); CI != CE; ++CI) {
2015     DIE *SPDie = CI->first;
2016     const MDNode *N = dyn_cast_or_null<MDNode>(CI->second);
2017     if (!N) continue;
2018     DIE *NDie = getCompileUnit(N)->getDIE(N);
2019     if (!NDie) continue;
2020     addDIEEntry(SPDie, dwarf::DW_AT_containing_type, dwarf::DW_FORM_ref4, NDie);
2021   }
2022
2023   // Standard sections final addresses.
2024   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
2025   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
2026   Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
2027   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
2028
2029   // End text sections.
2030   for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2031     Asm->OutStreamer.SwitchSection(SectionMap[i]);
2032     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
2033   }
2034
2035   // Emit common frame information.
2036   emitCommonDebugFrame();
2037
2038   // Emit function debug frame information
2039   for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2040          E = DebugFrames.end(); I != E; ++I)
2041     emitFunctionDebugFrame(*I);
2042
2043   // Compute DIE offsets and sizes.
2044   computeSizeAndOffsets();
2045
2046   // Emit all the DIEs into a debug info section
2047   emitDebugInfo();
2048
2049   // Corresponding abbreviations into a abbrev section.
2050   emitAbbreviations();
2051
2052   // Emit source line correspondence into a debug line section.
2053   emitDebugLines();
2054
2055   // Emit info into a debug pubnames section.
2056   emitDebugPubNames();
2057
2058   // Emit info into a debug pubtypes section.
2059   emitDebugPubTypes();
2060
2061   // Emit info into a debug loc section.
2062   emitDebugLoc();
2063
2064   // Emit info into a debug aranges section.
2065   EmitDebugARanges();
2066
2067   // Emit info into a debug ranges section.
2068   emitDebugRanges();
2069
2070   // Emit info into a debug macinfo section.
2071   emitDebugMacInfo();
2072
2073   // Emit inline info.
2074   emitDebugInlineInfo();
2075
2076   // Emit info into a debug str section.
2077   emitDebugStr();
2078   
2079   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2080          E = CUMap.end(); I != E; ++I)
2081     delete I->second;
2082   FirstCU = NULL;  // Reset for the next Module, if any.
2083 }
2084
2085 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
2086 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
2087                                               unsigned FrameIdx,
2088                                               DebugLoc ScopeLoc) {
2089
2090   DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
2091   if (AbsDbgVariable)
2092     return AbsDbgVariable;
2093
2094   LLVMContext &Ctx = Var->getContext();
2095   DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
2096   if (!Scope)
2097     return NULL;
2098
2099   AbsDbgVariable = new DbgVariable(Var, FrameIdx,
2100                                    NULL /* No more-abstract variable*/);
2101   Scope->addVariable(AbsDbgVariable);
2102   AbstractVariables[Var] = AbsDbgVariable;
2103   return AbsDbgVariable;
2104 }
2105
2106 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
2107 /// FIXME : Refactor findAbstractVariable.
2108 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &Var,
2109                                               const MachineInstr *MI,
2110                                               DebugLoc ScopeLoc) {
2111
2112   DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
2113   if (AbsDbgVariable)
2114     return AbsDbgVariable;
2115
2116   LLVMContext &Ctx = Var->getContext();
2117   DbgScope *Scope = AbstractScopes.lookup(ScopeLoc.getScope(Ctx));
2118   if (!Scope)
2119     return NULL;
2120
2121   AbsDbgVariable = new DbgVariable(Var, MI,
2122                                    NULL /* No more-abstract variable*/);
2123   Scope->addVariable(AbsDbgVariable);
2124   AbstractVariables[Var] = AbsDbgVariable;
2125   DbgValueStartMap[MI] = AbsDbgVariable;
2126   return AbsDbgVariable;
2127 }
2128
2129 /// collectVariableInfo - Populate DbgScope entries with variables' info.
2130 void DwarfDebug::collectVariableInfo(const MachineFunction *MF) {
2131   const LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2132   SmallPtrSet<const MDNode *, 16> Processed;
2133   MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
2134   for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
2135          VE = VMap.end(); VI != VE; ++VI) {
2136     const MDNode *Var = VI->first;
2137     if (!Var) continue;
2138     Processed.insert(Var);
2139     DIVariable DV(Var);
2140     const std::pair<unsigned, DebugLoc> &VP = VI->second;
2141
2142     DbgScope *Scope = 0;
2143     if (const MDNode *IA = VP.second.getInlinedAt(Ctx))
2144       Scope = ConcreteScopes.lookup(IA);
2145     if (Scope == 0)
2146       Scope = DbgScopeMap.lookup(VP.second.getScope(Ctx));
2147     
2148     // If variable scope is not found then skip this variable.
2149     if (Scope == 0)
2150       continue;
2151
2152     DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.first, VP.second);
2153     DbgVariable *RegVar = new DbgVariable(DV, VP.first, AbsDbgVariable);
2154     Scope->addVariable(RegVar);
2155   }
2156
2157   // Collect variable information from DBG_VALUE machine instructions;
2158   for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2159        I != E; ++I) {
2160     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2161          II != IE; ++II) {
2162       const MachineInstr *MInsn = II;
2163       if (!MInsn->isDebugValue())
2164         continue;
2165
2166       // Ignore Undef values.
2167       if (MInsn->getOperand(0).isReg() && !MInsn->getOperand(0).getReg())
2168         continue;
2169
2170       DIVariable DV(
2171         const_cast<const MDNode *>(MInsn->getOperand(MInsn->getNumOperands() - 1)
2172                                .getMetadata()));
2173       if (DV.getTag() == dwarf::DW_TAG_arg_variable)  {
2174         // FIXME Handle inlined subroutine arguments.
2175         DbgVariable *ArgVar = new DbgVariable(DV, MInsn, NULL);
2176         CurrentFnDbgScope->addVariable(ArgVar);
2177         DbgValueStartMap[MInsn] = ArgVar;
2178         continue;
2179       }
2180
2181       DebugLoc DL = MInsn->getDebugLoc();
2182       if (DL.isUnknown()) continue;
2183       DbgScope *Scope = 0;
2184       if (const MDNode *IA = DL.getInlinedAt(Ctx))
2185         Scope = ConcreteScopes.lookup(IA);
2186       if (Scope == 0)
2187         Scope = DbgScopeMap.lookup(DL.getScope(Ctx));
2188       
2189       // If variable scope is not found then skip this variable.
2190       if (Scope == 0)
2191         continue;
2192
2193       Processed.insert(DV);
2194       DbgVariable *AbsDbgVariable = findAbstractVariable(DV, MInsn, DL);
2195       DbgVariable *RegVar = new DbgVariable(DV, MInsn, AbsDbgVariable);
2196       DbgValueStartMap[MInsn] = RegVar;
2197       Scope->addVariable(RegVar);
2198     }
2199   }
2200
2201   // Collect info for variables that were optimized out.
2202   if (NamedMDNode *NMD = 
2203       MF->getFunction()->getParent()->getNamedMetadata("llvm.dbg.lv")) {
2204     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
2205       DIVariable DV(cast_or_null<MDNode>(NMD->getOperand(i)));
2206       if (!Processed.insert(DV))
2207         continue;
2208       DbgScope *Scope = DbgScopeMap.lookup(DV.getContext());
2209       if (Scope)
2210         Scope->addVariable(new DbgVariable(DV, ~0U, NULL));
2211     }
2212   }
2213
2214 }
2215
2216 /// beginScope - Process beginning of a scope.
2217 void DwarfDebug::beginScope(const MachineInstr *MI) {
2218   // Check location.
2219   DebugLoc DL = MI->getDebugLoc();
2220   if (DL.isUnknown()) {
2221     if (UnknownLocations) {
2222       // This instruction has no debug location. If the preceding instruction
2223       // did, emit debug location information to indicate that the debug
2224       // location is now unknown.
2225       MCSymbol *Label = NULL;
2226       if (DL == PrevInstLoc)
2227         Label = PrevLabel;
2228       else {
2229         Label = recordSourceLine(DL.getLine(), DL.getCol(), 0);
2230         PrevInstLoc = DL;
2231         PrevLabel = Label;
2232       }
2233
2234       // If this instruction begins a scope then note down corresponding label.
2235       if (InsnsBeginScopeSet.count(MI) != 0)
2236         LabelsBeforeInsn[MI] = Label;
2237     }
2238
2239     return;
2240   }
2241
2242   const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
2243   
2244   // FIXME: Should only verify each scope once!
2245   if (!DIScope(Scope).Verify())
2246     return;
2247
2248   // DBG_VALUE instruction establishes new value.
2249   if (MI->isDebugValue()) {
2250     DenseMap<const MachineInstr *, DbgVariable *>::iterator DI
2251       = DbgValueStartMap.find(MI);
2252     if (DI != DbgValueStartMap.end()) {
2253       MCSymbol *Label = NULL;
2254       if (DL == PrevInstLoc)
2255         Label = PrevLabel;
2256       else {
2257         Label = recordSourceLine(DL.getLine(), DL.getCol(), Scope);
2258         PrevInstLoc = DL;
2259         PrevLabel = Label;
2260       }
2261       DI->second->setDbgValueLabel(Label);
2262     }
2263     return;
2264   }
2265
2266   // Emit a label to indicate location change. This is used for line 
2267   // table even if this instruction does not start a new scope.
2268   MCSymbol *Label = NULL;
2269   if (DL == PrevInstLoc)
2270     Label = PrevLabel;
2271   else {
2272     Label = recordSourceLine(DL.getLine(), DL.getCol(), Scope);
2273     PrevInstLoc = DL;
2274     PrevLabel = Label;
2275   }
2276
2277   // If this instruction begins a scope then note down corresponding label.
2278   if (InsnsBeginScopeSet.count(MI) != 0)
2279     LabelsBeforeInsn[MI] = Label;
2280 }
2281
2282 /// endScope - Process end of a scope.
2283 void DwarfDebug::endScope(const MachineInstr *MI) {
2284   if (InsnsEndScopeSet.count(MI) != 0) {
2285     // Emit a label if this instruction ends a scope.
2286     MCSymbol *Label = MMI->getContext().CreateTempSymbol();
2287     Asm->OutStreamer.EmitLabel(Label);
2288     LabelsAfterInsn[MI] = Label;
2289   }
2290 }
2291
2292 /// getOrCreateDbgScope - Create DbgScope for the scope.
2293 DbgScope *DwarfDebug::getOrCreateDbgScope(const MDNode *Scope, const MDNode *InlinedAt) {
2294   if (!InlinedAt) {
2295     DbgScope *WScope = DbgScopeMap.lookup(Scope);
2296     if (WScope)
2297       return WScope;
2298     WScope = new DbgScope(NULL, DIDescriptor(Scope), NULL);
2299     DbgScopeMap.insert(std::make_pair(Scope, WScope));
2300     if (DIDescriptor(Scope).isLexicalBlock()) {
2301       DbgScope *Parent = 
2302         getOrCreateDbgScope(DILexicalBlock(Scope).getContext(), NULL);
2303       WScope->setParent(Parent);
2304       Parent->addScope(WScope);
2305     }
2306
2307     if (!WScope->getParent()) {
2308       StringRef SPName = DISubprogram(Scope).getLinkageName();
2309       if (SPName == Asm->MF->getFunction()->getName())
2310         CurrentFnDbgScope = WScope;
2311     }
2312     
2313     return WScope;
2314   }
2315
2316   DbgScope *WScope = DbgScopeMap.lookup(InlinedAt);
2317   if (WScope)
2318     return WScope;
2319
2320   WScope = new DbgScope(NULL, DIDescriptor(Scope), InlinedAt);
2321   DbgScopeMap.insert(std::make_pair(InlinedAt, WScope));
2322   DILocation DL(InlinedAt);
2323   DbgScope *Parent =
2324     getOrCreateDbgScope(DL.getScope(), DL.getOrigLocation());
2325   WScope->setParent(Parent);
2326   Parent->addScope(WScope);
2327
2328   ConcreteScopes[InlinedAt] = WScope;
2329   getOrCreateAbstractScope(Scope);
2330
2331   return WScope;
2332 }
2333
2334 /// hasValidLocation - Return true if debug location entry attached with
2335 /// machine instruction encodes valid location info.
2336 static bool hasValidLocation(LLVMContext &Ctx,
2337                              const MachineInstr *MInsn,
2338                              const MDNode *&Scope, const MDNode *&InlinedAt) {
2339   if (MInsn->isDebugValue())
2340     return false;
2341   DebugLoc DL = MInsn->getDebugLoc();
2342   if (DL.isUnknown()) return false;
2343       
2344   const MDNode *S = DL.getScope(Ctx);
2345   
2346   // There is no need to create another DIE for compile unit. For all
2347   // other scopes, create one DbgScope now. This will be translated
2348   // into a scope DIE at the end.
2349   if (DIScope(S).isCompileUnit()) return false;
2350      
2351   Scope = S;
2352   InlinedAt = DL.getInlinedAt(Ctx);
2353   return true;
2354 }
2355
2356 /// calculateDominanceGraph - Calculate dominance graph for DbgScope
2357 /// hierarchy.
2358 static void calculateDominanceGraph(DbgScope *Scope) {
2359   assert (Scope && "Unable to calculate scop edominance graph!");
2360   SmallVector<DbgScope *, 4> WorkStack;
2361   WorkStack.push_back(Scope);
2362   unsigned Counter = 0;
2363   while (!WorkStack.empty()) {
2364     DbgScope *WS = WorkStack.back();
2365     const SmallVector<DbgScope *, 4> &Children = WS->getScopes();
2366     bool visitedChildren = false;
2367     for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2368            SE = Children.end(); SI != SE; ++SI) {
2369       DbgScope *ChildScope = *SI;
2370       if (!ChildScope->getDFSOut()) {
2371         WorkStack.push_back(ChildScope);
2372         visitedChildren = true;
2373         ChildScope->setDFSIn(++Counter);
2374         break;
2375       }
2376     }
2377     if (!visitedChildren) {
2378       WorkStack.pop_back();
2379       WS->setDFSOut(++Counter);
2380     }
2381   }
2382 }
2383
2384 /// printDbgScopeInfo - Print DbgScope info for each machine instruction.
2385 static 
2386 void printDbgScopeInfo(LLVMContext &Ctx, const MachineFunction *MF,
2387                        DenseMap<const MachineInstr *, DbgScope *> &MI2ScopeMap)
2388 {
2389 #ifndef NDEBUG
2390   unsigned PrevDFSIn = 0;
2391   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2392        I != E; ++I) {
2393     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2394          II != IE; ++II) {
2395       const MachineInstr *MInsn = II;
2396       const MDNode *Scope = NULL;
2397       const MDNode *InlinedAt = NULL;
2398
2399       // Check if instruction has valid location information.
2400       if (hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2401         dbgs() << " [ ";
2402         if (InlinedAt) 
2403           dbgs() << "*";
2404         DenseMap<const MachineInstr *, DbgScope *>::iterator DI = 
2405           MI2ScopeMap.find(MInsn);
2406         if (DI != MI2ScopeMap.end()) {
2407           DbgScope *S = DI->second;
2408           dbgs() << S->getDFSIn();
2409           PrevDFSIn = S->getDFSIn();
2410         } else
2411           dbgs() << PrevDFSIn;
2412       } else 
2413         dbgs() << " [ x" << PrevDFSIn;
2414       dbgs() << " ]";
2415       MInsn->dump();
2416     }
2417     dbgs() << "\n";
2418   }
2419 #endif
2420 }
2421 /// extractScopeInformation - Scan machine instructions in this function
2422 /// and collect DbgScopes. Return true, if at least one scope was found.
2423 bool DwarfDebug::extractScopeInformation() {
2424   // If scope information was extracted using .dbg intrinsics then there is not
2425   // any need to extract these information by scanning each instruction.
2426   if (!DbgScopeMap.empty())
2427     return false;
2428
2429   // Scan each instruction and create scopes. First build working set of scopes.
2430   LLVMContext &Ctx = Asm->MF->getFunction()->getContext();
2431   SmallVector<DbgRange, 4> MIRanges;
2432   DenseMap<const MachineInstr *, DbgScope *> MI2ScopeMap;
2433   const MDNode *PrevScope = NULL;
2434   const MDNode *PrevInlinedAt = NULL;
2435   const MachineInstr *RangeBeginMI = NULL;
2436   const MachineInstr *PrevMI = NULL;
2437   for (MachineFunction::const_iterator I = Asm->MF->begin(), E = Asm->MF->end();
2438        I != E; ++I) {
2439     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
2440          II != IE; ++II) {
2441       const MachineInstr *MInsn = II;
2442       const MDNode *Scope = NULL;
2443       const MDNode *InlinedAt = NULL;
2444
2445       // Check if instruction has valid location information.
2446       if (!hasValidLocation(Ctx, MInsn, Scope, InlinedAt)) {
2447         PrevMI = MInsn;
2448         continue;
2449       }
2450       
2451       // If scope has not changed then skip this instruction.
2452       if (Scope == PrevScope && PrevInlinedAt == InlinedAt) {
2453         PrevMI = MInsn;
2454         continue;
2455       }
2456
2457       if (RangeBeginMI) {      
2458         // If we have alread seen a beginning of a instruction range and 
2459         // current instruction scope does not match scope of first instruction
2460         // in this range then create a new instruction range.
2461         DbgRange R(RangeBeginMI, PrevMI);
2462         MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
2463         MIRanges.push_back(R);
2464       } 
2465
2466       // This is a beginning of a new instruction range.
2467       RangeBeginMI = MInsn;
2468       
2469       // Reset previous markers.
2470       PrevMI = MInsn;
2471       PrevScope = Scope;
2472       PrevInlinedAt = InlinedAt;
2473     }
2474   }
2475
2476   // Create last instruction range.
2477   if (RangeBeginMI && PrevMI && PrevScope) {
2478     DbgRange R(RangeBeginMI, PrevMI);
2479     MIRanges.push_back(R);
2480     MI2ScopeMap[RangeBeginMI] = getOrCreateDbgScope(PrevScope, PrevInlinedAt);
2481   }
2482   
2483   if (!CurrentFnDbgScope)
2484     return false;
2485
2486   calculateDominanceGraph(CurrentFnDbgScope);
2487   if (PrintDbgScope)
2488     printDbgScopeInfo(Ctx, Asm->MF, MI2ScopeMap);
2489
2490   // Find ranges of instructions covered by each DbgScope;
2491   DbgScope *PrevDbgScope = NULL;
2492   for (SmallVector<DbgRange, 4>::const_iterator RI = MIRanges.begin(),
2493          RE = MIRanges.end(); RI != RE; ++RI) {
2494     const DbgRange &R = *RI;
2495     DbgScope *S = MI2ScopeMap.lookup(R.first);
2496     assert (S && "Lost DbgScope for a machine instruction!");
2497     if (PrevDbgScope && !PrevDbgScope->dominates(S))
2498       PrevDbgScope->closeInsnRange(S);
2499     S->openInsnRange(R.first);
2500     S->extendInsnRange(R.second);
2501     PrevDbgScope = S;
2502   }
2503
2504   if (PrevDbgScope)
2505     PrevDbgScope->closeInsnRange();
2506
2507   identifyScopeMarkers();
2508
2509   return !DbgScopeMap.empty();
2510 }
2511
2512 /// identifyScopeMarkers() - 
2513 /// Each DbgScope has first instruction and last instruction to mark beginning
2514 /// and end of a scope respectively. Create an inverse map that list scopes
2515 /// starts (and ends) with an instruction. One instruction may start (or end)
2516 /// multiple scopes. Ignore scopes that are not reachable.
2517 void DwarfDebug::identifyScopeMarkers() {
2518   SmallVector<DbgScope *, 4> WorkList;
2519   WorkList.push_back(CurrentFnDbgScope);
2520   while (!WorkList.empty()) {
2521     DbgScope *S = WorkList.pop_back_val();
2522     
2523     const SmallVector<DbgScope *, 4> &Children = S->getScopes();
2524     if (!Children.empty()) 
2525       for (SmallVector<DbgScope *, 4>::const_iterator SI = Children.begin(),
2526              SE = Children.end(); SI != SE; ++SI)
2527         WorkList.push_back(*SI);
2528
2529     if (S->isAbstractScope())
2530       continue;
2531     
2532     const SmallVector<DbgRange, 4> &Ranges = S->getRanges();
2533     if (Ranges.empty())
2534       continue;
2535     for (SmallVector<DbgRange, 4>::const_iterator RI = Ranges.begin(),
2536            RE = Ranges.end(); RI != RE; ++RI) {
2537       assert(RI->first && "DbgRange does not have first instruction!");      
2538       assert(RI->second && "DbgRange does not have second instruction!");      
2539       InsnsBeginScopeSet.insert(RI->first);
2540       InsnsEndScopeSet.insert(RI->second);
2541     }
2542   }
2543 }
2544
2545 /// FindFirstDebugLoc - Find the first debug location in the function. This
2546 /// is intended to be an approximation for the source position of the
2547 /// beginning of the function.
2548 static DebugLoc FindFirstDebugLoc(const MachineFunction *MF) {
2549   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
2550        I != E; ++I)
2551     for (MachineBasicBlock::const_iterator MBBI = I->begin(), MBBE = I->end();
2552          MBBI != MBBE; ++MBBI) {
2553       DebugLoc DL = MBBI->getDebugLoc();
2554       if (!DL.isUnknown())
2555         return DL;
2556     }
2557   return DebugLoc();
2558 }
2559
2560 /// beginFunction - Gather pre-function debug information.  Assumes being
2561 /// emitted immediately after the function entry point.
2562 void DwarfDebug::beginFunction(const MachineFunction *MF) {
2563   if (!MMI->hasDebugInfo()) return;
2564   if (!extractScopeInformation()) return;
2565   
2566   collectVariableInfo(MF);
2567
2568   FunctionBeginSym = Asm->GetTempSymbol("func_begin",
2569                                         Asm->getFunctionNumber());
2570   // Assumes in correct section after the entry point.
2571   Asm->OutStreamer.EmitLabel(FunctionBeginSym);
2572
2573   // Emit label for the implicitly defined dbg.stoppoint at the start of the
2574   // function.
2575   DebugLoc FDL = FindFirstDebugLoc(MF);
2576   if (FDL.isUnknown()) return;
2577   
2578   const MDNode *Scope = FDL.getScope(MF->getFunction()->getContext());
2579   
2580   DISubprogram SP = getDISubprogram(Scope);
2581   unsigned Line, Col;
2582   if (SP.Verify()) {
2583     Line = SP.getLineNumber();
2584     Col = 0;
2585   } else {
2586     Line = FDL.getLine();
2587     Col = FDL.getCol();
2588   }
2589   
2590   recordSourceLine(Line, Col, Scope);
2591 }
2592
2593 /// endFunction - Gather and emit post-function debug information.
2594 ///
2595 void DwarfDebug::endFunction(const MachineFunction *MF) {
2596   if (!MMI->hasDebugInfo() || DbgScopeMap.empty()) return;
2597
2598   if (CurrentFnDbgScope) {
2599     // Define end label for subprogram.
2600     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("func_end",
2601                                                   Asm->getFunctionNumber()));
2602     
2603     // Get function line info.
2604     if (!Lines.empty()) {
2605       // Get section line info.
2606       unsigned ID = SectionMap.insert(Asm->getCurrentSection());
2607       if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2608       std::vector<SrcLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2609       // Append the function info to section info.
2610       SectionLineInfos.insert(SectionLineInfos.end(),
2611                               Lines.begin(), Lines.end());
2612     }
2613     
2614     // Construct abstract scopes.
2615     for (SmallVector<DbgScope *, 4>::iterator AI = AbstractScopesList.begin(),
2616            AE = AbstractScopesList.end(); AI != AE; ++AI)
2617       constructScopeDIE(*AI);
2618     
2619     DIE *CurFnDIE = constructScopeDIE(CurrentFnDbgScope);
2620     
2621     if (!DisableFramePointerElim(*MF))
2622       addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr, 
2623               dwarf::DW_FORM_flag, 1);
2624
2625
2626     DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
2627                                                  MMI->getFrameMoves()));
2628   }
2629
2630   // Clear debug info
2631   CurrentFnDbgScope = NULL;
2632   DeleteContainerSeconds(DbgScopeMap);
2633   InsnsBeginScopeSet.clear();
2634   InsnsEndScopeSet.clear();
2635   DbgValueStartMap.clear();
2636   ConcreteScopes.clear();
2637   DeleteContainerSeconds(AbstractScopes);
2638   AbstractScopesList.clear();
2639   AbstractVariables.clear();
2640   LabelsBeforeInsn.clear();
2641   LabelsAfterInsn.clear();
2642   Lines.clear();
2643   PrevLabel = NULL;
2644 }
2645
2646 /// recordSourceLine - Register a source line with debug info. Returns the
2647 /// unique label that was emitted and which provides correspondence to
2648 /// the source line list.
2649 MCSymbol *DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S) {
2650   StringRef Dir;
2651   StringRef Fn;
2652
2653   unsigned Src = 1;
2654   if (S) {
2655     DIDescriptor Scope(S);
2656
2657     if (Scope.isCompileUnit()) {
2658       DICompileUnit CU(S);
2659       Dir = CU.getDirectory();
2660       Fn = CU.getFilename();
2661     } else if (Scope.isSubprogram()) {
2662       DISubprogram SP(S);
2663       Dir = SP.getDirectory();
2664       Fn = SP.getFilename();
2665     } else if (Scope.isLexicalBlock()) {
2666       DILexicalBlock DB(S);
2667       Dir = DB.getDirectory();
2668       Fn = DB.getFilename();
2669     } else
2670       assert(0 && "Unexpected scope info");
2671
2672     Src = GetOrCreateSourceID(Dir, Fn);
2673   }
2674
2675   MCSymbol *Label = MMI->getContext().CreateTempSymbol();
2676   Lines.push_back(SrcLineInfo(Line, Col, Src, Label));
2677
2678   Asm->OutStreamer.EmitLabel(Label);
2679   return Label;
2680 }
2681
2682 //===----------------------------------------------------------------------===//
2683 // Emit Methods
2684 //===----------------------------------------------------------------------===//
2685
2686 /// computeSizeAndOffset - Compute the size and offset of a DIE.
2687 ///
2688 unsigned
2689 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
2690   // Get the children.
2691   const std::vector<DIE *> &Children = Die->getChildren();
2692
2693   // If not last sibling and has children then add sibling offset attribute.
2694   if (!Last && !Children.empty())
2695     Die->addSiblingOffset(DIEValueAllocator);
2696
2697   // Record the abbreviation.
2698   assignAbbrevNumber(Die->getAbbrev());
2699
2700   // Get the abbreviation for this DIE.
2701   unsigned AbbrevNumber = Die->getAbbrevNumber();
2702   const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2703
2704   // Set DIE offset
2705   Die->setOffset(Offset);
2706
2707   // Start the size with the size of abbreviation code.
2708   Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
2709
2710   const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2711   const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2712
2713   // Size the DIE attribute values.
2714   for (unsigned i = 0, N = Values.size(); i < N; ++i)
2715     // Size attribute value.
2716     Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
2717
2718   // Size the DIE children if any.
2719   if (!Children.empty()) {
2720     assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
2721            "Children flag not set");
2722
2723     for (unsigned j = 0, M = Children.size(); j < M; ++j)
2724       Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
2725
2726     // End of children marker.
2727     Offset += sizeof(int8_t);
2728   }
2729
2730   Die->setSize(Offset - Die->getOffset());
2731   return Offset;
2732 }
2733
2734 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
2735 ///
2736 void DwarfDebug::computeSizeAndOffsets() {
2737   unsigned PrevOffset = 0;
2738   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2739          E = CUMap.end(); I != E; ++I) {
2740     // Compute size of compile unit header.
2741     static unsigned Offset = PrevOffset +
2742       sizeof(int32_t) + // Length of Compilation Unit Info
2743       sizeof(int16_t) + // DWARF version number
2744       sizeof(int32_t) + // Offset Into Abbrev. Section
2745       sizeof(int8_t);   // Pointer Size (in bytes)
2746     computeSizeAndOffset(I->second->getCUDie(), Offset, true);
2747     PrevOffset = Offset;
2748   }
2749 }
2750
2751 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
2752 /// temporary label to it if SymbolStem is specified.
2753 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
2754                                 const char *SymbolStem = 0) {
2755   Asm->OutStreamer.SwitchSection(Section);
2756   if (!SymbolStem) return 0;
2757   
2758   MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
2759   Asm->OutStreamer.EmitLabel(TmpSym);
2760   return TmpSym;
2761 }
2762
2763 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
2764 /// the start of each one.
2765 void DwarfDebug::EmitSectionLabels() {
2766   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
2767
2768   // Dwarf sections base addresses.
2769   if (Asm->MAI->doesDwarfRequireFrameSection()) {
2770     DwarfFrameSectionSym =
2771       EmitSectionSym(Asm, TLOF.getDwarfFrameSection(), "section_debug_frame");
2772    }
2773
2774   DwarfInfoSectionSym = 
2775     EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
2776   DwarfAbbrevSectionSym = 
2777     EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
2778   EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
2779   
2780   if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
2781     EmitSectionSym(Asm, MacroInfo);
2782
2783   EmitSectionSym(Asm, TLOF.getDwarfLineSection());
2784   EmitSectionSym(Asm, TLOF.getDwarfLocSection());
2785   EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
2786   EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2787   DwarfStrSectionSym = 
2788     EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
2789   DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
2790                                              "debug_range");
2791
2792   TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
2793   EmitSectionSym(Asm, TLOF.getDataSection());
2794 }
2795
2796 /// emitDIE - Recusively Emits a debug information entry.
2797 ///
2798 void DwarfDebug::emitDIE(DIE *Die) {
2799   // Get the abbreviation for this DIE.
2800   unsigned AbbrevNumber = Die->getAbbrevNumber();
2801   const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2802
2803   // Emit the code (index) for the abbreviation.
2804   if (Asm->isVerbose())
2805     Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
2806                                 Twine::utohexstr(Die->getOffset()) + ":0x" +
2807                                 Twine::utohexstr(Die->getSize()) + " " +
2808                                 dwarf::TagString(Abbrev->getTag()));
2809   Asm->EmitULEB128(AbbrevNumber);
2810
2811   const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2812   const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2813
2814   // Emit the DIE attribute values.
2815   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2816     unsigned Attr = AbbrevData[i].getAttribute();
2817     unsigned Form = AbbrevData[i].getForm();
2818     assert(Form && "Too many attributes for DIE (check abbreviation)");
2819
2820     if (Asm->isVerbose())
2821       Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2822     
2823     switch (Attr) {
2824     case dwarf::DW_AT_sibling:
2825       Asm->EmitInt32(Die->getSiblingOffset());
2826       break;
2827     case dwarf::DW_AT_abstract_origin: {
2828       DIEEntry *E = cast<DIEEntry>(Values[i]);
2829       DIE *Origin = E->getEntry();
2830       unsigned Addr = Origin->getOffset();
2831       Asm->EmitInt32(Addr);
2832       break;
2833     }
2834     case dwarf::DW_AT_ranges: {
2835       // DW_AT_range Value encodes offset in debug_range section.
2836       DIEInteger *V = cast<DIEInteger>(Values[i]);
2837       Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
2838                                      V->getValue(),
2839                                      DwarfDebugRangeSectionSym,
2840                                      4);
2841       break;
2842     }
2843     default:
2844       // Emit an attribute using the defined form.
2845       Values[i]->EmitValue(Asm, Form);
2846       break;
2847     }
2848   }
2849
2850   // Emit the DIE children if any.
2851   if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2852     const std::vector<DIE *> &Children = Die->getChildren();
2853
2854     for (unsigned j = 0, M = Children.size(); j < M; ++j)
2855       emitDIE(Children[j]);
2856
2857     if (Asm->isVerbose())
2858       Asm->OutStreamer.AddComment("End Of Children Mark");
2859     Asm->EmitInt8(0);
2860   }
2861 }
2862
2863 /// emitDebugInfo - Emit the debug info section.
2864 ///
2865 void DwarfDebug::emitDebugInfo() {
2866   // Start debug info section.
2867   Asm->OutStreamer.SwitchSection(
2868                             Asm->getObjFileLowering().getDwarfInfoSection());
2869   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2870          E = CUMap.end(); I != E; ++I) {
2871     CompileUnit *TheCU = I->second;
2872     DIE *Die = TheCU->getCUDie();
2873     
2874     // Emit the compile units header.
2875     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
2876                                                   TheCU->getID()));
2877     
2878     // Emit size of content not including length itself
2879     unsigned ContentSize = Die->getSize() +
2880       sizeof(int16_t) + // DWARF version number
2881       sizeof(int32_t) + // Offset Into Abbrev. Section
2882       sizeof(int8_t) +  // Pointer Size (in bytes)
2883       sizeof(int32_t);  // FIXME - extra pad for gdb bug.
2884     
2885     Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2886     Asm->EmitInt32(ContentSize);
2887     Asm->OutStreamer.AddComment("DWARF version number");
2888     Asm->EmitInt16(dwarf::DWARF_VERSION);
2889     Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2890     Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
2891                            DwarfAbbrevSectionSym);
2892     Asm->OutStreamer.AddComment("Address Size (in bytes)");
2893     Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2894     
2895     emitDIE(Die);
2896     // FIXME - extra padding for gdb bug.
2897     Asm->OutStreamer.AddComment("4 extra padding bytes for GDB");
2898     Asm->EmitInt8(0);
2899     Asm->EmitInt8(0);
2900     Asm->EmitInt8(0);
2901     Asm->EmitInt8(0);
2902     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
2903   }
2904 }
2905
2906 /// emitAbbreviations - Emit the abbreviation section.
2907 ///
2908 void DwarfDebug::emitAbbreviations() const {
2909   // Check to see if it is worth the effort.
2910   if (!Abbreviations.empty()) {
2911     // Start the debug abbrev section.
2912     Asm->OutStreamer.SwitchSection(
2913                             Asm->getObjFileLowering().getDwarfAbbrevSection());
2914
2915     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
2916
2917     // For each abbrevation.
2918     for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2919       // Get abbreviation data
2920       const DIEAbbrev *Abbrev = Abbreviations[i];
2921
2922       // Emit the abbrevations code (base 1 index.)
2923       Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2924
2925       // Emit the abbreviations data.
2926       Abbrev->Emit(Asm);
2927     }
2928
2929     // Mark end of abbreviations.
2930     Asm->EmitULEB128(0, "EOM(3)");
2931
2932     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
2933   }
2934 }
2935
2936 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
2937 /// the line matrix.
2938 ///
2939 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2940   // Define last address of section.
2941   Asm->OutStreamer.AddComment("Extended Op");
2942   Asm->EmitInt8(0);
2943   
2944   Asm->OutStreamer.AddComment("Op size");
2945   Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
2946   Asm->OutStreamer.AddComment("DW_LNE_set_address");
2947   Asm->EmitInt8(dwarf::DW_LNE_set_address);
2948
2949   Asm->OutStreamer.AddComment("Section end label");
2950
2951   Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2952                                    Asm->getTargetData().getPointerSize(),
2953                                    0/*AddrSpace*/);
2954
2955   // Mark end of matrix.
2956   Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2957   Asm->EmitInt8(0);
2958   Asm->EmitInt8(1);
2959   Asm->EmitInt8(1);
2960 }
2961
2962 /// emitDebugLines - Emit source line information.
2963 ///
2964 void DwarfDebug::emitDebugLines() {
2965   // If the target is using .loc/.file, the assembler will be emitting the
2966   // .debug_line table automatically.
2967   if (Asm->MAI->hasDotLocAndDotFile())
2968     return;
2969
2970   // Minimum line delta, thus ranging from -10..(255-10).
2971   const int MinLineDelta = -(dwarf::DW_LNS_fixed_advance_pc + 1);
2972   // Maximum line delta, thus ranging from -10..(255-10).
2973   const int MaxLineDelta = 255 + MinLineDelta;
2974
2975   // Start the dwarf line section.
2976   Asm->OutStreamer.SwitchSection(
2977                             Asm->getObjFileLowering().getDwarfLineSection());
2978
2979   // Construct the section header.
2980   Asm->OutStreamer.AddComment("Length of Source Line Info");
2981   Asm->EmitLabelDifference(Asm->GetTempSymbol("line_end"),
2982                            Asm->GetTempSymbol("line_begin"), 4);
2983   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_begin"));
2984
2985   Asm->OutStreamer.AddComment("DWARF version number");
2986   Asm->EmitInt16(dwarf::DWARF_VERSION); 
2987
2988   Asm->OutStreamer.AddComment("Prolog Length");
2989   Asm->EmitLabelDifference(Asm->GetTempSymbol("line_prolog_end"),
2990                            Asm->GetTempSymbol("line_prolog_begin"), 4);
2991   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_begin"));
2992
2993   Asm->OutStreamer.AddComment("Minimum Instruction Length");
2994   Asm->EmitInt8(1);
2995   Asm->OutStreamer.AddComment("Default is_stmt_start flag");
2996   Asm->EmitInt8(1);
2997   Asm->OutStreamer.AddComment("Line Base Value (Special Opcodes)");
2998   Asm->EmitInt8(MinLineDelta);
2999   Asm->OutStreamer.AddComment("Line Range Value (Special Opcodes)");
3000   Asm->EmitInt8(MaxLineDelta);
3001   Asm->OutStreamer.AddComment("Special Opcode Base");
3002   Asm->EmitInt8(-MinLineDelta);
3003
3004   // Line number standard opcode encodings argument count
3005   Asm->OutStreamer.AddComment("DW_LNS_copy arg count");
3006   Asm->EmitInt8(0);
3007   Asm->OutStreamer.AddComment("DW_LNS_advance_pc arg count");
3008   Asm->EmitInt8(1);
3009   Asm->OutStreamer.AddComment("DW_LNS_advance_line arg count");
3010   Asm->EmitInt8(1);
3011   Asm->OutStreamer.AddComment("DW_LNS_set_file arg count");
3012   Asm->EmitInt8(1);
3013   Asm->OutStreamer.AddComment("DW_LNS_set_column arg count");
3014   Asm->EmitInt8(1);
3015   Asm->OutStreamer.AddComment("DW_LNS_negate_stmt arg count");
3016   Asm->EmitInt8(0);
3017   Asm->OutStreamer.AddComment("DW_LNS_set_basic_block arg count");
3018   Asm->EmitInt8(0);
3019   Asm->OutStreamer.AddComment("DW_LNS_const_add_pc arg count");
3020   Asm->EmitInt8(0);
3021   Asm->OutStreamer.AddComment("DW_LNS_fixed_advance_pc arg count");
3022   Asm->EmitInt8(1);
3023
3024   // Emit directories.
3025   for (unsigned DI = 1, DE = getNumSourceDirectories()+1; DI != DE; ++DI) {
3026     const std::string &Dir = getSourceDirectoryName(DI);
3027     if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Directory");
3028     Asm->OutStreamer.EmitBytes(StringRef(Dir.c_str(), Dir.size()+1), 0);
3029   }
3030
3031   Asm->OutStreamer.AddComment("End of directories");
3032   Asm->EmitInt8(0);
3033
3034   // Emit files.
3035   for (unsigned SI = 1, SE = getNumSourceIds()+1; SI != SE; ++SI) {
3036     // Remember source id starts at 1.
3037     std::pair<unsigned, unsigned> Id = getSourceDirectoryAndFileIds(SI);
3038     const std::string &FN = getSourceFileName(Id.second);
3039     if (Asm->isVerbose()) Asm->OutStreamer.AddComment("Source");
3040     Asm->OutStreamer.EmitBytes(StringRef(FN.c_str(), FN.size()+1), 0);
3041     
3042     Asm->EmitULEB128(Id.first, "Directory #");
3043     Asm->EmitULEB128(0, "Mod date");
3044     Asm->EmitULEB128(0, "File size");
3045   }
3046
3047   Asm->OutStreamer.AddComment("End of files");
3048   Asm->EmitInt8(0);
3049
3050   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_prolog_end"));
3051
3052   // A sequence for each text section.
3053   unsigned SecSrcLinesSize = SectionSourceLines.size();
3054
3055   for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
3056     // Isolate current sections line info.
3057     const std::vector<SrcLineInfo> &LineInfos = SectionSourceLines[j];
3058
3059     // Dwarf assumes we start with first line of first source file.
3060     unsigned Source = 1;
3061     unsigned Line = 1;
3062
3063     // Construct rows of the address, source, line, column matrix.
3064     for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
3065       const SrcLineInfo &LineInfo = LineInfos[i];
3066       MCSymbol *Label = LineInfo.getLabel();
3067       if (!Label->isDefined()) continue; // Not emitted, in dead code.
3068
3069       if (Asm->isVerbose()) {
3070         std::pair<unsigned, unsigned> SrcID =
3071           getSourceDirectoryAndFileIds(LineInfo.getSourceID());
3072         Asm->OutStreamer.AddComment(Twine(getSourceDirectoryName(SrcID.first)) +
3073                                     "/" +
3074                                     Twine(getSourceFileName(SrcID.second)) +
3075                                     ":" + Twine(LineInfo.getLine()));
3076       }
3077
3078       // Define the line address.
3079       Asm->OutStreamer.AddComment("Extended Op");
3080       Asm->EmitInt8(0);
3081       Asm->OutStreamer.AddComment("Op size");
3082       Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
3083
3084       Asm->OutStreamer.AddComment("DW_LNE_set_address");
3085       Asm->EmitInt8(dwarf::DW_LNE_set_address); 
3086
3087       Asm->OutStreamer.AddComment("Location label");
3088       Asm->OutStreamer.EmitSymbolValue(Label,
3089                                        Asm->getTargetData().getPointerSize(),
3090                                        0/*AddrSpace*/);
3091       
3092       // If change of source, then switch to the new source.
3093       if (Source != LineInfo.getSourceID()) {
3094         Source = LineInfo.getSourceID();
3095         Asm->OutStreamer.AddComment("DW_LNS_set_file");
3096         Asm->EmitInt8(dwarf::DW_LNS_set_file); 
3097         Asm->EmitULEB128(Source, "New Source");
3098       }
3099
3100       // If change of line.
3101       if (Line != LineInfo.getLine()) {
3102         // Determine offset.
3103         int Offset = LineInfo.getLine() - Line;
3104         int Delta = Offset - MinLineDelta;
3105
3106         // Update line.
3107         Line = LineInfo.getLine();
3108
3109         // If delta is small enough and in range...
3110         if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
3111           // ... then use fast opcode.
3112           Asm->OutStreamer.AddComment("Line Delta");
3113           Asm->EmitInt8(Delta - MinLineDelta);
3114         } else {
3115           // ... otherwise use long hand.
3116           Asm->OutStreamer.AddComment("DW_LNS_advance_line");
3117           Asm->EmitInt8(dwarf::DW_LNS_advance_line);
3118           Asm->EmitSLEB128(Offset, "Line Offset");
3119           Asm->OutStreamer.AddComment("DW_LNS_copy");
3120           Asm->EmitInt8(dwarf::DW_LNS_copy);
3121         }
3122       } else {
3123         // Copy the previous row (different address or source)
3124         Asm->OutStreamer.AddComment("DW_LNS_copy");
3125         Asm->EmitInt8(dwarf::DW_LNS_copy);
3126       }
3127     }
3128
3129     emitEndOfLineMatrix(j + 1);
3130   }
3131
3132   if (SecSrcLinesSize == 0)
3133     // Because we're emitting a debug_line section, we still need a line
3134     // table. The linker and friends expect it to exist. If there's nothing to
3135     // put into it, emit an empty table.
3136     emitEndOfLineMatrix(1);
3137
3138   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("line_end"));
3139 }
3140
3141 /// emitCommonDebugFrame - Emit common frame info into a debug frame section.
3142 ///
3143 void DwarfDebug::emitCommonDebugFrame() {
3144   if (!Asm->MAI->doesDwarfRequireFrameSection())
3145     return;
3146
3147   int stackGrowth = Asm->getTargetData().getPointerSize();
3148   if (Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3149       TargetFrameInfo::StackGrowsDown)
3150     stackGrowth *= -1;
3151
3152   // Start the dwarf frame section.
3153   Asm->OutStreamer.SwitchSection(
3154                               Asm->getObjFileLowering().getDwarfFrameSection());
3155
3156   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common"));
3157   Asm->OutStreamer.AddComment("Length of Common Information Entry");
3158   Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_frame_common_end"),
3159                            Asm->GetTempSymbol("debug_frame_common_begin"), 4);
3160
3161   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_begin"));
3162   Asm->OutStreamer.AddComment("CIE Identifier Tag");
3163   Asm->EmitInt32((int)dwarf::DW_CIE_ID);
3164   Asm->OutStreamer.AddComment("CIE Version");
3165   Asm->EmitInt8(dwarf::DW_CIE_VERSION);
3166   Asm->OutStreamer.AddComment("CIE Augmentation");
3167   Asm->OutStreamer.EmitIntValue(0, 1, /*addrspace*/0); // nul terminator.
3168   Asm->EmitULEB128(1, "CIE Code Alignment Factor");
3169   Asm->EmitSLEB128(stackGrowth, "CIE Data Alignment Factor");
3170   Asm->OutStreamer.AddComment("CIE RA Column");
3171   const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
3172   Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
3173
3174   std::vector<MachineMove> Moves;
3175   RI->getInitialFrameState(Moves);
3176
3177   Asm->EmitFrameMoves(Moves, 0, false);
3178
3179   Asm->EmitAlignment(2);
3180   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_frame_common_end"));
3181 }
3182
3183 /// emitFunctionDebugFrame - Emit per function frame info into a debug frame
3184 /// section.
3185 void DwarfDebug::
3186 emitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
3187   if (!Asm->MAI->doesDwarfRequireFrameSection())
3188     return;
3189
3190   // Start the dwarf frame section.
3191   Asm->OutStreamer.SwitchSection(
3192                               Asm->getObjFileLowering().getDwarfFrameSection());
3193
3194   Asm->OutStreamer.AddComment("Length of Frame Information Entry");
3195   MCSymbol *DebugFrameBegin =
3196     Asm->GetTempSymbol("debug_frame_begin", DebugFrameInfo.Number);
3197   MCSymbol *DebugFrameEnd =
3198     Asm->GetTempSymbol("debug_frame_end", DebugFrameInfo.Number);
3199   Asm->EmitLabelDifference(DebugFrameEnd, DebugFrameBegin, 4);
3200
3201   Asm->OutStreamer.EmitLabel(DebugFrameBegin);
3202
3203   Asm->OutStreamer.AddComment("FDE CIE offset");
3204   Asm->EmitSectionOffset(Asm->GetTempSymbol("debug_frame_common"), 
3205                          DwarfFrameSectionSym);
3206
3207   Asm->OutStreamer.AddComment("FDE initial location");
3208   MCSymbol *FuncBeginSym =
3209     Asm->GetTempSymbol("func_begin", DebugFrameInfo.Number);
3210   Asm->OutStreamer.EmitSymbolValue(FuncBeginSym,
3211                                    Asm->getTargetData().getPointerSize(),
3212                                    0/*AddrSpace*/);
3213   
3214   
3215   Asm->OutStreamer.AddComment("FDE address range");
3216   Asm->EmitLabelDifference(Asm->GetTempSymbol("func_end",DebugFrameInfo.Number),
3217                            FuncBeginSym, Asm->getTargetData().getPointerSize());
3218
3219   Asm->EmitFrameMoves(DebugFrameInfo.Moves, FuncBeginSym, false);
3220
3221   Asm->EmitAlignment(2);
3222   Asm->OutStreamer.EmitLabel(DebugFrameEnd);
3223 }
3224
3225 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
3226 ///
3227 void DwarfDebug::emitDebugPubNames() {
3228   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3229          E = CUMap.end(); I != E; ++I) {
3230     CompileUnit *TheCU = I->second;
3231     // Start the dwarf pubnames section.
3232     Asm->OutStreamer.SwitchSection(
3233       Asm->getObjFileLowering().getDwarfPubNamesSection());
3234     
3235     Asm->OutStreamer.AddComment("Length of Public Names Info");
3236     Asm->EmitLabelDifference(
3237       Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
3238       Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
3239     
3240     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
3241                                                   TheCU->getID()));
3242     
3243     Asm->OutStreamer.AddComment("DWARF Version");
3244     Asm->EmitInt16(dwarf::DWARF_VERSION); 
3245     
3246     Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
3247     Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()), 
3248                            DwarfInfoSectionSym);
3249     
3250     Asm->OutStreamer.AddComment("Compilation Unit Length");
3251     Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
3252                              Asm->GetTempSymbol("info_begin", TheCU->getID()),
3253                              4);
3254     
3255     const StringMap<DIE*> &Globals = TheCU->getGlobals();
3256     for (StringMap<DIE*>::const_iterator
3257            GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3258       const char *Name = GI->getKeyData();
3259       DIE *Entity = GI->second;
3260       
3261       Asm->OutStreamer.AddComment("DIE offset");
3262       Asm->EmitInt32(Entity->getOffset());
3263       
3264       if (Asm->isVerbose())
3265         Asm->OutStreamer.AddComment("External Name");
3266       Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
3267     }
3268     
3269     Asm->OutStreamer.AddComment("End Mark");
3270     Asm->EmitInt32(0);
3271     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
3272                                                 TheCU->getID()));
3273   }
3274 }
3275
3276 void DwarfDebug::emitDebugPubTypes() {
3277   for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
3278          E = CUMap.end(); I != E; ++I) {
3279     CompileUnit *TheCU = I->second;
3280     // Start the dwarf pubnames section.
3281     Asm->OutStreamer.SwitchSection(
3282       Asm->getObjFileLowering().getDwarfPubTypesSection());
3283     Asm->OutStreamer.AddComment("Length of Public Types Info");
3284     Asm->EmitLabelDifference(
3285       Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
3286       Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
3287     
3288     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
3289                                                   TheCU->getID()));
3290     
3291     if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
3292     Asm->EmitInt16(dwarf::DWARF_VERSION);
3293     
3294     Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
3295     Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
3296                            DwarfInfoSectionSym);
3297     
3298     Asm->OutStreamer.AddComment("Compilation Unit Length");
3299     Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
3300                              Asm->GetTempSymbol("info_begin", TheCU->getID()),
3301                              4);
3302     
3303     const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
3304     for (StringMap<DIE*>::const_iterator
3305            GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
3306       const char *Name = GI->getKeyData();
3307       DIE * Entity = GI->second;
3308       
3309       if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3310       Asm->EmitInt32(Entity->getOffset());
3311       
3312       if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
3313       Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
3314     }
3315     
3316     Asm->OutStreamer.AddComment("End Mark");
3317     Asm->EmitInt32(0); 
3318     Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
3319                                                   TheCU->getID()));
3320   }
3321 }
3322
3323 /// emitDebugStr - Emit visible names into a debug str section.
3324 ///
3325 void DwarfDebug::emitDebugStr() {
3326   // Check to see if it is worth the effort.
3327   if (StringPool.empty()) return;
3328   
3329   // Start the dwarf str section.
3330   Asm->OutStreamer.SwitchSection(
3331                                 Asm->getObjFileLowering().getDwarfStrSection());
3332
3333   // Get all of the string pool entries and put them in an array by their ID so
3334   // we can sort them.
3335   SmallVector<std::pair<unsigned, 
3336       StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
3337   
3338   for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
3339        I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
3340     Entries.push_back(std::make_pair(I->second.second, &*I));
3341   
3342   array_pod_sort(Entries.begin(), Entries.end());
3343   
3344   for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
3345     // Emit a label for reference from debug information entries.
3346     Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
3347     
3348     // Emit the string itself.
3349     Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
3350   }
3351 }
3352
3353 /// emitDebugLoc - Emit visible names into a debug loc section.
3354 ///
3355 void DwarfDebug::emitDebugLoc() {
3356   // Start the dwarf loc section.
3357   Asm->OutStreamer.SwitchSection(
3358                               Asm->getObjFileLowering().getDwarfLocSection());
3359 }
3360
3361 /// EmitDebugARanges - Emit visible names into a debug aranges section.
3362 ///
3363 void DwarfDebug::EmitDebugARanges() {
3364   // Start the dwarf aranges section.
3365   Asm->OutStreamer.SwitchSection(
3366                           Asm->getObjFileLowering().getDwarfARangesSection());
3367 }
3368
3369 /// emitDebugRanges - Emit visible names into a debug ranges section.
3370 ///
3371 void DwarfDebug::emitDebugRanges() {
3372   // Start the dwarf ranges section.
3373   Asm->OutStreamer.SwitchSection(
3374     Asm->getObjFileLowering().getDwarfRangesSection());
3375   unsigned char Size = Asm->getTargetData().getPointerSize();
3376   for (SmallVector<const MCSymbol *, 8>::iterator
3377          I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end(); 
3378        I != E; ++I) {
3379     if (*I)
3380       Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
3381     else
3382       Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
3383   }
3384 }
3385
3386 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
3387 ///
3388 void DwarfDebug::emitDebugMacInfo() {
3389   if (const MCSection *LineInfo =
3390       Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
3391     // Start the dwarf macinfo section.
3392     Asm->OutStreamer.SwitchSection(LineInfo);
3393   }
3394 }
3395
3396 /// emitDebugInlineInfo - Emit inline info using following format.
3397 /// Section Header:
3398 /// 1. length of section
3399 /// 2. Dwarf version number
3400 /// 3. address size.
3401 ///
3402 /// Entries (one "entry" for each function that was inlined):
3403 ///
3404 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
3405 ///   otherwise offset into __debug_str for regular function name.
3406 /// 2. offset into __debug_str section for regular function name.
3407 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
3408 /// instances for the function.
3409 ///
3410 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
3411 /// inlined instance; the die_offset points to the inlined_subroutine die in the
3412 /// __debug_info section, and the low_pc is the starting address for the
3413 /// inlining instance.
3414 void DwarfDebug::emitDebugInlineInfo() {
3415   if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
3416     return;
3417
3418   if (!FirstCU)
3419     return;
3420
3421   Asm->OutStreamer.SwitchSection(
3422                         Asm->getObjFileLowering().getDwarfDebugInlineSection());
3423
3424   Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
3425   Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
3426                            Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
3427
3428   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
3429
3430   Asm->OutStreamer.AddComment("Dwarf Version");
3431   Asm->EmitInt16(dwarf::DWARF_VERSION);
3432   Asm->OutStreamer.AddComment("Address Size (in bytes)");
3433   Asm->EmitInt8(Asm->getTargetData().getPointerSize());
3434
3435   for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
3436          E = InlinedSPNodes.end(); I != E; ++I) {
3437
3438     const MDNode *Node = *I;
3439     DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
3440       = InlineInfo.find(Node);
3441     SmallVector<InlineInfoLabels, 4> &Labels = II->second;
3442     DISubprogram SP(Node);
3443     StringRef LName = SP.getLinkageName();
3444     StringRef Name = SP.getName();
3445
3446     Asm->OutStreamer.AddComment("MIPS linkage name");
3447     if (LName.empty()) {
3448       Asm->OutStreamer.EmitBytes(Name, 0);
3449       Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
3450     } else 
3451       Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
3452                              DwarfStrSectionSym);
3453
3454     Asm->OutStreamer.AddComment("Function name");
3455     Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
3456     Asm->EmitULEB128(Labels.size(), "Inline count");
3457
3458     for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
3459            LE = Labels.end(); LI != LE; ++LI) {
3460       if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
3461       Asm->EmitInt32(LI->second->getOffset());
3462
3463       if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
3464       Asm->OutStreamer.EmitSymbolValue(LI->first,
3465                                        Asm->getTargetData().getPointerSize(),0);
3466     }
3467   }
3468
3469   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
3470 }