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