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