74978506d9d6c0aec45ff77eb12fe2ba355cce95
[oota-llvm.git] / lib / CodeGen / DwarfWriter.cpp
1 //===-- llvm/CodeGen/DwarfWriter.cpp - Dwarf Framework ----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by James M. Laskey and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing dwarf info into asm files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/DwarfWriter.h"
15
16 #include "llvm/ADT/FoldingSet.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/UniqueVector.h"
19 #include "llvm/Module.h"
20 #include "llvm/Type.h"
21 #include "llvm/CodeGen/AsmPrinter.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineLocation.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Dwarf.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/DataTypes.h"
29 #include "llvm/Support/Mangler.h"
30 #include "llvm/Target/TargetAsmInfo.h"
31 #include "llvm/Target/MRegisterInfo.h"
32 #include "llvm/Target/TargetData.h"
33 #include "llvm/Target/TargetFrameInfo.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include <ostream>
37 #include <string>
38 using namespace llvm;
39 using namespace llvm::dwarf;
40
41 namespace llvm {
42   
43 //===----------------------------------------------------------------------===//
44
45 /// Configuration values for initial hash set sizes (log2).
46 ///
47 static const unsigned InitDiesSetSize          = 9; // 512
48 static const unsigned InitAbbreviationsSetSize = 9; // 512
49 static const unsigned InitValuesSetSize        = 9; // 512
50
51 //===----------------------------------------------------------------------===//
52 /// Forward declarations.
53 ///
54 class DIE;
55 class DIEValue;
56
57 //===----------------------------------------------------------------------===//
58 /// DWLabel - Labels are used to track locations in the assembler file.
59 /// Labels appear in the form <prefix><Tag><Number>, where the tag is a
60 /// category of label (Ex. location) and number is a value unique in that
61 /// category.
62 class DWLabel {
63 public:
64   /// Tag - Label category tag. Should always be a staticly declared C string.
65   ///
66   const char *Tag;
67   
68   /// Number - Value to make label unique.
69   ///
70   unsigned    Number;
71
72   DWLabel(const char *T, unsigned N) : Tag(T), Number(N) {}
73   
74   void Profile(FoldingSetNodeID &ID) const {
75     ID.AddString(std::string(Tag));
76     ID.AddInteger(Number);
77   }
78   
79 #ifndef NDEBUG
80   void print(std::ostream *O) const {
81     if (O) print(*O);
82   }
83   void print(std::ostream &O) const {
84     O << "." << Tag;
85     if (Number) O << Number;
86   }
87 #endif
88 };
89
90 //===----------------------------------------------------------------------===//
91 /// DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
92 /// Dwarf abbreviation.
93 class DIEAbbrevData {
94 private:
95   /// Attribute - Dwarf attribute code.
96   ///
97   unsigned Attribute;
98   
99   /// Form - Dwarf form code.
100   ///              
101   unsigned Form;                      
102   
103 public:
104   DIEAbbrevData(unsigned A, unsigned F)
105   : Attribute(A)
106   , Form(F)
107   {}
108   
109   // Accessors.
110   unsigned getAttribute() const { return Attribute; }
111   unsigned getForm()      const { return Form; }
112
113   /// Profile - Used to gather unique data for the abbreviation folding set.
114   ///
115   void Profile(FoldingSetNodeID &ID)const  {
116     ID.AddInteger(Attribute);
117     ID.AddInteger(Form);
118   }
119 };
120
121 //===----------------------------------------------------------------------===//
122 /// DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
123 /// information object.
124 class DIEAbbrev : public FoldingSetNode {
125 private:
126   /// Tag - Dwarf tag code.
127   ///
128   unsigned Tag;
129   
130   /// Unique number for node.
131   ///
132   unsigned Number;
133
134   /// ChildrenFlag - Dwarf children flag.
135   ///
136   unsigned ChildrenFlag;
137
138   /// Data - Raw data bytes for abbreviation.
139   ///
140   std::vector<DIEAbbrevData> Data;
141
142 public:
143
144   DIEAbbrev(unsigned T, unsigned C)
145   : Tag(T)
146   , ChildrenFlag(C)
147   , Data()
148   {}
149   ~DIEAbbrev() {}
150   
151   // Accessors.
152   unsigned getTag()                           const { return Tag; }
153   unsigned getNumber()                        const { return Number; }
154   unsigned getChildrenFlag()                  const { return ChildrenFlag; }
155   const std::vector<DIEAbbrevData> &getData() const { return Data; }
156   void setTag(unsigned T)                           { Tag = T; }
157   void setChildrenFlag(unsigned CF)                 { ChildrenFlag = CF; }
158   void setNumber(unsigned N)                        { Number = N; }
159   
160   /// AddAttribute - Adds another set of attribute information to the
161   /// abbreviation.
162   void AddAttribute(unsigned Attribute, unsigned Form) {
163     Data.push_back(DIEAbbrevData(Attribute, Form));
164   }
165   
166   /// AddFirstAttribute - Adds a set of attribute information to the front
167   /// of the abbreviation.
168   void AddFirstAttribute(unsigned Attribute, unsigned Form) {
169     Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
170   }
171   
172   /// Profile - Used to gather unique data for the abbreviation folding set.
173   ///
174   void Profile(FoldingSetNodeID &ID) {
175     ID.AddInteger(Tag);
176     ID.AddInteger(ChildrenFlag);
177     
178     // For each attribute description.
179     for (unsigned i = 0, N = Data.size(); i < N; ++i)
180       Data[i].Profile(ID);
181   }
182   
183   /// Emit - Print the abbreviation using the specified Dwarf writer.
184   ///
185   void Emit(const DwarfDebug &DD) const; 
186       
187 #ifndef NDEBUG
188   void print(std::ostream *O) {
189     if (O) print(*O);
190   }
191   void print(std::ostream &O);
192   void dump();
193 #endif
194 };
195
196 //===----------------------------------------------------------------------===//
197 /// DIE - A structured debug information entry.  Has an abbreviation which
198 /// describes it's organization.
199 class DIE : public FoldingSetNode {
200 protected:
201   /// Abbrev - Buffer for constructing abbreviation.
202   ///
203   DIEAbbrev Abbrev;
204   
205   /// Offset - Offset in debug info section.
206   ///
207   unsigned Offset;
208   
209   /// Size - Size of instance + children.
210   ///
211   unsigned Size;
212   
213   /// Children DIEs.
214   ///
215   std::vector<DIE *> Children;
216   
217   /// Attributes values.
218   ///
219   std::vector<DIEValue *> Values;
220   
221 public:
222   DIE(unsigned Tag)
223   : Abbrev(Tag, DW_CHILDREN_no)
224   , Offset(0)
225   , Size(0)
226   , Children()
227   , Values()
228   {}
229   virtual ~DIE();
230   
231   // Accessors.
232   DIEAbbrev &getAbbrev()                           { return Abbrev; }
233   unsigned   getAbbrevNumber()               const {
234     return Abbrev.getNumber();
235   }
236   unsigned getTag()                          const { return Abbrev.getTag(); }
237   unsigned getOffset()                       const { return Offset; }
238   unsigned getSize()                         const { return Size; }
239   const std::vector<DIE *> &getChildren()    const { return Children; }
240   const std::vector<DIEValue *> &getValues() const { return Values; }
241   void setTag(unsigned Tag)                  { Abbrev.setTag(Tag); }
242   void setOffset(unsigned O)                 { Offset = O; }
243   void setSize(unsigned S)                   { Size = S; }
244   
245   /// AddValue - Add a value and attributes to a DIE.
246   ///
247   void AddValue(unsigned Attribute, unsigned Form, DIEValue *Value) {
248     Abbrev.AddAttribute(Attribute, Form);
249     Values.push_back(Value);
250   }
251   
252   /// SiblingOffset - Return the offset of the debug information entry's
253   /// sibling.
254   unsigned SiblingOffset() const { return Offset + Size; }
255   
256   /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
257   ///
258   void AddSiblingOffset();
259
260   /// AddChild - Add a child to the DIE.
261   ///
262   void AddChild(DIE *Child) {
263     Abbrev.setChildrenFlag(DW_CHILDREN_yes);
264     Children.push_back(Child);
265   }
266   
267   /// Detach - Detaches objects connected to it after copying.
268   ///
269   void Detach() {
270     Children.clear();
271   }
272   
273   /// Profile - Used to gather unique data for the value folding set.
274   ///
275   void Profile(FoldingSetNodeID &ID) ;
276       
277 #ifndef NDEBUG
278   void print(std::ostream *O, unsigned IncIndent = 0) {
279     if (O) print(*O, IncIndent);
280   }
281   void print(std::ostream &O, unsigned IncIndent = 0);
282   void dump();
283 #endif
284 };
285
286 //===----------------------------------------------------------------------===//
287 /// DIEValue - A debug information entry value.
288 ///
289 class DIEValue : public FoldingSetNode {
290 public:
291   enum {
292     isInteger,
293     isString,
294     isLabel,
295     isAsIsLabel,
296     isDelta,
297     isEntry,
298     isBlock
299   };
300   
301   /// Type - Type of data stored in the value.
302   ///
303   unsigned Type;
304   
305   DIEValue(unsigned T)
306   : Type(T)
307   {}
308   virtual ~DIEValue() {}
309   
310   // Accessors
311   unsigned getType()  const { return Type; }
312   
313   // Implement isa/cast/dyncast.
314   static bool classof(const DIEValue *) { return true; }
315   
316   /// EmitValue - Emit value via the Dwarf writer.
317   ///
318   virtual void EmitValue(const DwarfDebug &DD, unsigned Form) const = 0;
319   
320   /// SizeOf - Return the size of a value in bytes.
321   ///
322   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const = 0;
323   
324   /// Profile - Used to gather unique data for the value folding set.
325   ///
326   virtual void Profile(FoldingSetNodeID &ID) = 0;
327       
328 #ifndef NDEBUG
329   void print(std::ostream *O) {
330     if (O) print(*O);
331   }
332   virtual void print(std::ostream &O) = 0;
333   void dump();
334 #endif
335 };
336
337 //===----------------------------------------------------------------------===//
338 /// DWInteger - An integer value DIE.
339 /// 
340 class DIEInteger : public DIEValue {
341 private:
342   uint64_t Integer;
343   
344 public:
345   DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
346
347   // Implement isa/cast/dyncast.
348   static bool classof(const DIEInteger *) { return true; }
349   static bool classof(const DIEValue *I)  { return I->Type == isInteger; }
350   
351   /// BestForm - Choose the best form for integer.
352   ///
353   static unsigned BestForm(bool IsSigned, uint64_t Integer) {
354     if (IsSigned) {
355       if ((char)Integer == (signed)Integer)   return DW_FORM_data1;
356       if ((short)Integer == (signed)Integer)  return DW_FORM_data2;
357       if ((int)Integer == (signed)Integer)    return DW_FORM_data4;
358     } else {
359       if ((unsigned char)Integer == Integer)  return DW_FORM_data1;
360       if ((unsigned short)Integer == Integer) return DW_FORM_data2;
361       if ((unsigned int)Integer == Integer)   return DW_FORM_data4;
362     }
363     return DW_FORM_data8;
364   }
365     
366   /// EmitValue - Emit integer of appropriate size.
367   ///
368   virtual void EmitValue(const DwarfDebug &DD, unsigned Form) const;
369   
370   /// SizeOf - Determine size of integer value in bytes.
371   ///
372   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
373   
374   /// Profile - Used to gather unique data for the value folding set.
375   ///
376   static void Profile(FoldingSetNodeID &ID, unsigned Integer) {
377     ID.AddInteger(isInteger);
378     ID.AddInteger(Integer);
379   }
380   virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Integer); }
381   
382 #ifndef NDEBUG
383   virtual void print(std::ostream &O) {
384     O << "Int: " << (int64_t)Integer
385       << "  0x" << std::hex << Integer << std::dec;
386   }
387 #endif
388 };
389
390 //===----------------------------------------------------------------------===//
391 /// DIEString - A string value DIE.
392 /// 
393 class DIEString : public DIEValue {
394 public:
395   const std::string String;
396   
397   DIEString(const std::string &S) : DIEValue(isString), String(S) {}
398
399   // Implement isa/cast/dyncast.
400   static bool classof(const DIEString *) { return true; }
401   static bool classof(const DIEValue *S) { return S->Type == isString; }
402   
403   /// EmitValue - Emit string value.
404   ///
405   virtual void EmitValue(const DwarfDebug &DD, unsigned Form) const;
406   
407   /// SizeOf - Determine size of string value in bytes.
408   ///
409   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
410     return String.size() + sizeof(char); // sizeof('\0');
411   }
412   
413   /// Profile - Used to gather unique data for the value folding set.
414   ///
415   static void Profile(FoldingSetNodeID &ID, const std::string &String) {
416     ID.AddInteger(isString);
417     ID.AddString(String);
418   }
419   virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, String); }
420   
421 #ifndef NDEBUG
422   virtual void print(std::ostream &O) {
423     O << "Str: \"" << String << "\"";
424   }
425 #endif
426 };
427
428 //===----------------------------------------------------------------------===//
429 /// DIEDwarfLabel - A Dwarf internal label expression DIE.
430 //
431 class DIEDwarfLabel : public DIEValue {
432 public:
433
434   const DWLabel Label;
435   
436   DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
437
438   // Implement isa/cast/dyncast.
439   static bool classof(const DIEDwarfLabel *)  { return true; }
440   static bool classof(const DIEValue *L) { return L->Type == isLabel; }
441   
442   /// EmitValue - Emit label value.
443   ///
444   virtual void EmitValue(const DwarfDebug &DD, unsigned Form) const;
445   
446   /// SizeOf - Determine size of label value in bytes.
447   ///
448   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
449   
450   /// Profile - Used to gather unique data for the value folding set.
451   ///
452   static void Profile(FoldingSetNodeID &ID, const DWLabel &Label) {
453     ID.AddInteger(isLabel);
454     Label.Profile(ID);
455   }
456   virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
457   
458 #ifndef NDEBUG
459   virtual void print(std::ostream &O) {
460     O << "Lbl: ";
461     Label.print(O);
462   }
463 #endif
464 };
465
466
467 //===----------------------------------------------------------------------===//
468 /// DIEObjectLabel - A label to an object in code or data.
469 //
470 class DIEObjectLabel : public DIEValue {
471 public:
472   const std::string Label;
473   
474   DIEObjectLabel(const std::string &L) : DIEValue(isAsIsLabel), Label(L) {}
475
476   // Implement isa/cast/dyncast.
477   static bool classof(const DIEObjectLabel *) { return true; }
478   static bool classof(const DIEValue *L)    { return L->Type == isAsIsLabel; }
479   
480   /// EmitValue - Emit label value.
481   ///
482   virtual void EmitValue(const DwarfDebug &DD, unsigned Form) const;
483   
484   /// SizeOf - Determine size of label value in bytes.
485   ///
486   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
487   
488   /// Profile - Used to gather unique data for the value folding set.
489   ///
490   static void Profile(FoldingSetNodeID &ID, const std::string &Label) {
491     ID.AddInteger(isAsIsLabel);
492     ID.AddString(Label);
493   }
494   virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
495
496 #ifndef NDEBUG
497   virtual void print(std::ostream &O) {
498     O << "Obj: " << Label;
499   }
500 #endif
501 };
502
503 //===----------------------------------------------------------------------===//
504 /// DIEDelta - A simple label difference DIE.
505 /// 
506 class DIEDelta : public DIEValue {
507 public:
508   const DWLabel LabelHi;
509   const DWLabel LabelLo;
510   
511   DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
512   : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
513
514   // Implement isa/cast/dyncast.
515   static bool classof(const DIEDelta *)  { return true; }
516   static bool classof(const DIEValue *D) { return D->Type == isDelta; }
517   
518   /// EmitValue - Emit delta value.
519   ///
520   virtual void EmitValue(const DwarfDebug &DD, unsigned Form) const;
521   
522   /// SizeOf - Determine size of delta value in bytes.
523   ///
524   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
525   
526   /// Profile - Used to gather unique data for the value folding set.
527   ///
528   static void Profile(FoldingSetNodeID &ID, const DWLabel &LabelHi,
529                                             const DWLabel &LabelLo) {
530     ID.AddInteger(isDelta);
531     LabelHi.Profile(ID);
532     LabelLo.Profile(ID);
533   }
534   virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, LabelHi, LabelLo); }
535
536 #ifndef NDEBUG
537   virtual void print(std::ostream &O) {
538     O << "Del: ";
539     LabelHi.print(O);
540     O << "-";
541     LabelLo.print(O);
542   }
543 #endif
544 };
545
546 //===----------------------------------------------------------------------===//
547 /// DIEntry - A pointer to another debug information entry.  An instance of this
548 /// class can also be used as a proxy for a debug information entry not yet
549 /// defined (ie. types.)
550 class DIEntry : public DIEValue {
551 public:
552   DIE *Entry;
553   
554   DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
555   
556   // Implement isa/cast/dyncast.
557   static bool classof(const DIEntry *)   { return true; }
558   static bool classof(const DIEValue *E) { return E->Type == isEntry; }
559   
560   /// EmitValue - Emit debug information entry offset.
561   ///
562   virtual void EmitValue(const DwarfDebug &DD, unsigned Form) const;
563   
564   /// SizeOf - Determine size of debug information entry in bytes.
565   ///
566   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
567     return sizeof(int32_t);
568   }
569   
570   /// Profile - Used to gather unique data for the value folding set.
571   ///
572   static void Profile(FoldingSetNodeID &ID, DIE *Entry) {
573     ID.AddInteger(isEntry);
574     ID.AddPointer(Entry);
575   }
576   virtual void Profile(FoldingSetNodeID &ID) {
577     ID.AddInteger(isEntry);
578     
579     if (Entry) {
580       ID.AddPointer(Entry);
581     } else {
582       ID.AddPointer(this);
583     }
584   }
585   
586 #ifndef NDEBUG
587   virtual void print(std::ostream &O) {
588     O << "Die: 0x" << std::hex << (intptr_t)Entry << std::dec;
589   }
590 #endif
591 };
592
593 //===----------------------------------------------------------------------===//
594 /// DIEBlock - A block of values.  Primarily used for location expressions.
595 //
596 class DIEBlock : public DIEValue, public DIE {
597 public:
598   unsigned Size;                        // Size in bytes excluding size header.
599   
600   DIEBlock()
601   : DIEValue(isBlock)
602   , DIE(0)
603   , Size(0)
604   {}
605   ~DIEBlock()  {
606   }
607   
608   // Implement isa/cast/dyncast.
609   static bool classof(const DIEBlock *)  { return true; }
610   static bool classof(const DIEValue *E) { return E->Type == isBlock; }
611   
612   /// ComputeSize - calculate the size of the block.
613   ///
614   unsigned ComputeSize(DwarfDebug &DD);
615   
616   /// BestForm - Choose the best form for data.
617   ///
618   unsigned BestForm() const {
619     if ((unsigned char)Size == Size)  return DW_FORM_block1;
620     if ((unsigned short)Size == Size) return DW_FORM_block2;
621     if ((unsigned int)Size == Size)   return DW_FORM_block4;
622     return DW_FORM_block;
623   }
624
625   /// EmitValue - Emit block data.
626   ///
627   virtual void EmitValue(const DwarfDebug &DD, unsigned Form) const;
628   
629   /// SizeOf - Determine size of block data in bytes.
630   ///
631   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
632   
633
634   /// Profile - Used to gather unique data for the value folding set.
635   ///
636   virtual void Profile(FoldingSetNodeID &ID) {
637     ID.AddInteger(isBlock);
638     DIE::Profile(ID);
639   }
640   
641 #ifndef NDEBUG
642   virtual void print(std::ostream &O) {
643     O << "Blk: ";
644     DIE::print(O, 5);
645   }
646 #endif
647 };
648
649 //===----------------------------------------------------------------------===//
650 /// CompileUnit - This dwarf writer support class manages information associate
651 /// with a source file.
652 class CompileUnit {
653 private:
654   /// Desc - Compile unit debug descriptor.
655   ///
656   CompileUnitDesc *Desc;
657   
658   /// ID - File identifier for source.
659   ///
660   unsigned ID;
661   
662   /// Die - Compile unit debug information entry.
663   ///
664   DIE *Die;
665   
666   /// DescToDieMap - Tracks the mapping of unit level debug informaton
667   /// descriptors to debug information entries.
668   std::map<DebugInfoDesc *, DIE *> DescToDieMap;
669
670   /// DescToDIEntryMap - Tracks the mapping of unit level debug informaton
671   /// descriptors to debug information entries using a DIEntry proxy.
672   std::map<DebugInfoDesc *, DIEntry *> DescToDIEntryMap;
673
674   /// Globals - A map of globally visible named entities for this unit.
675   ///
676   std::map<std::string, DIE *> Globals;
677
678   /// DiesSet - Used to uniquely define dies within the compile unit.
679   ///
680   FoldingSet<DIE> DiesSet;
681   
682   /// Dies - List of all dies in the compile unit.
683   ///
684   std::vector<DIE *> Dies;
685   
686 public:
687   CompileUnit(CompileUnitDesc *CUD, unsigned I, DIE *D)
688   : Desc(CUD)
689   , ID(I)
690   , Die(D)
691   , DescToDieMap()
692   , DescToDIEntryMap()
693   , Globals()
694   , DiesSet(InitDiesSetSize)
695   , Dies()
696   {}
697   
698   ~CompileUnit() {
699     delete Die;
700     
701     for (unsigned i = 0, N = Dies.size(); i < N; ++i)
702       delete Dies[i];
703   }
704   
705   // Accessors.
706   CompileUnitDesc *getDesc() const { return Desc; }
707   unsigned getID()           const { return ID; }
708   DIE* getDie()              const { return Die; }
709   std::map<std::string, DIE *> &getGlobals() { return Globals; }
710
711   /// hasContent - Return true if this compile unit has something to write out.
712   ///
713   bool hasContent() const {
714     return !Die->getChildren().empty();
715   }
716
717   /// AddGlobal - Add a new global entity to the compile unit.
718   ///
719   void AddGlobal(const std::string &Name, DIE *Die) {
720     Globals[Name] = Die;
721   }
722   
723   /// getDieMapSlotFor - Returns the debug information entry map slot for the
724   /// specified debug descriptor.
725   DIE *&getDieMapSlotFor(DebugInfoDesc *DID) {
726     return DescToDieMap[DID];
727   }
728   
729   /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
730   /// specified debug descriptor.
731   DIEntry *&getDIEntrySlotFor(DebugInfoDesc *DID) {
732     return DescToDIEntryMap[DID];
733   }
734   
735   /// AddDie - Adds or interns the DIE to the compile unit.
736   ///
737   DIE *AddDie(DIE &Buffer) {
738     FoldingSetNodeID ID;
739     Buffer.Profile(ID);
740     void *Where;
741     DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
742     
743     if (!Die) {
744       Die = new DIE(Buffer);
745       DiesSet.InsertNode(Die, Where);
746       this->Die->AddChild(Die);
747       Buffer.Detach();
748     }
749     
750     return Die;
751   }
752 };
753
754 //===----------------------------------------------------------------------===//
755 /// Dwarf - Emits general Dwarf directives. 
756 ///
757 class Dwarf {
758
759 protected:
760
761   //===--------------------------------------------------------------------===//
762   // Core attributes used by the Dwarf writer.
763   //
764   
765   //
766   /// O - Stream to .s file.
767   ///
768   std::ostream &O;
769
770   /// Asm - Target of Dwarf emission.
771   ///
772   AsmPrinter *Asm;
773   
774   /// TAI - Target Asm Printer.
775   const TargetAsmInfo *TAI;
776   
777   /// TD - Target data.
778   const TargetData *TD;
779   
780   /// RI - Register Information.
781   const MRegisterInfo *RI;
782   
783   /// M - Current module.
784   ///
785   Module *M;
786   
787   /// MF - Current machine function.
788   ///
789   MachineFunction *MF;
790   
791   /// MMI - Collected machine module information.
792   ///
793   MachineModuleInfo *MMI;
794   
795   /// SubprogramCount - The running count of functions being compiled.
796   ///
797   unsigned SubprogramCount;
798   
799   Dwarf(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
800   : O(OS)
801   , Asm(A)
802   , TAI(T)
803   , TD(Asm->TM.getTargetData())
804   , RI(Asm->TM.getRegisterInfo())
805   , M(NULL)
806   , MF(NULL)
807   , MMI(NULL)
808   , SubprogramCount(0)
809   {
810   }
811
812 public:
813
814   //===--------------------------------------------------------------------===//
815   // Accessors.
816   //
817   AsmPrinter *getAsm() const { return Asm; }
818   MachineModuleInfo *getMMI() const { return MMI; }
819   const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
820
821   /// PrintLabelName - Print label name in form used by Dwarf writer.
822   ///
823   void PrintLabelName(DWLabel Label) const {
824     PrintLabelName(Label.Tag, Label.Number);
825   }
826   void PrintLabelName(const char *Tag, unsigned Number,
827                       bool isInSection = false) const {
828     if (isInSection && TAI->getDwarfSectionOffsetDirective())
829       O << TAI->getDwarfSectionOffsetDirective() << Tag;
830     else
831       O << TAI->getPrivateGlobalPrefix() << Tag;
832     if (Number) O << Number;
833   }
834   
835   /// EmitLabel - Emit location label for internal use by Dwarf.
836   ///
837   void EmitLabel(DWLabel Label) const {
838     EmitLabel(Label.Tag, Label.Number);
839   }
840   void EmitLabel(const char *Tag, unsigned Number) const {
841     PrintLabelName(Tag, Number);
842     O << ":\n";
843   }
844   
845   /// EmitReference - Emit a reference to a label.
846   ///
847   void EmitReference(DWLabel Label, bool IsPCRelative = false) const {
848     EmitReference(Label.Tag, Label.Number, IsPCRelative);
849   }
850   void EmitReference(const char *Tag, unsigned Number,
851                      bool IsPCRelative = false) const {
852     if (TAI->getAddressSize() == sizeof(int32_t))
853       O << TAI->getData32bitsDirective();
854     else
855       O << TAI->getData64bitsDirective();
856       
857     PrintLabelName(Tag, Number);
858     
859     if (IsPCRelative) O << "-" << TAI->getPCSymbol();
860   }
861   void EmitReference(const std::string &Name, bool IsPCRelative = false) const {
862     if (TAI->getAddressSize() == sizeof(int32_t))
863       O << TAI->getData32bitsDirective();
864     else
865       O << TAI->getData64bitsDirective();
866       
867     O << Name;
868     
869     if (IsPCRelative) O << "-" << TAI->getPCSymbol();
870   }
871
872   /// EmitDifference - Emit the difference between two labels.  Some
873   /// assemblers do not behave with absolute expressions with data directives,
874   /// so there is an option (needsSet) to use an intermediary set expression.
875   void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
876                       bool IsSmall = false) const {
877     EmitDifference(LabelHi.Tag, LabelHi.Number,
878                    LabelLo.Tag, LabelLo.Number,
879                    IsSmall);
880   }
881   void EmitDifference(const char *TagHi, unsigned NumberHi,
882                       const char *TagLo, unsigned NumberLo,
883                       bool IsSmall = false) const {
884     if (TAI->needsSet()) {
885       static unsigned SetCounter = 1;
886       
887       O << "\t.set\t";
888       PrintLabelName("set", SetCounter);
889       O << ",";
890       PrintLabelName(TagHi, NumberHi);
891       O << "-";
892       PrintLabelName(TagLo, NumberLo);
893       O << "\n";
894       
895       if (IsSmall || TAI->getAddressSize() == sizeof(int32_t))
896         O << TAI->getData32bitsDirective();
897       else
898         O << TAI->getData64bitsDirective();
899         
900       PrintLabelName("set", SetCounter);
901       
902       ++SetCounter;
903     } else {
904       if (IsSmall || TAI->getAddressSize() == sizeof(int32_t))
905         O << TAI->getData32bitsDirective();
906       else
907         O << TAI->getData64bitsDirective();
908         
909       PrintLabelName(TagHi, NumberHi);
910       O << "-";
911       PrintLabelName(TagLo, NumberLo);
912     }
913   }
914
915   void EmitSectionOffset(const char* Label, const char* Section,
916                          unsigned LabelNumber, unsigned SectionNumber,
917                          bool IsSmall = false) const {
918     if (TAI->needsSet()) {
919       static unsigned SetCounter = 1;
920       
921       O << "\t.set\t";
922       PrintLabelName("set", SetCounter);
923       O << ",";
924       PrintLabelName(Label, LabelNumber, true);
925       if (!TAI->isAbsoluteSectionOffsets()) {
926         O << "-";
927         PrintLabelName(Section, SectionNumber);
928       }      
929       O << "\n";
930       
931       if (IsSmall || TAI->getAddressSize() == sizeof(int32_t))
932         O << TAI->getData32bitsDirective();
933       else
934         O << TAI->getData64bitsDirective();
935         
936       PrintLabelName("set", SetCounter);
937       ++SetCounter;
938     } else {
939       if (IsSmall || TAI->getAddressSize() == sizeof(int32_t))
940         O << TAI->getData32bitsDirective();
941       else
942         O << TAI->getData64bitsDirective();
943         
944       PrintLabelName(Label, LabelNumber, true);
945       if (!TAI->isAbsoluteSectionOffsets()) {
946         O << "-";
947         PrintLabelName(Section, SectionNumber);
948       }
949     }    
950   }
951   
952   /// EmitFrameMoves - Emit frame instructions to describe the layout of the
953   /// frame.
954   void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
955                                    std::vector<MachineMove> &Moves) {
956     int stackGrowth =
957         Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
958           TargetFrameInfo::StackGrowsUp ?
959             TAI->getAddressSize() : -TAI->getAddressSize();
960     bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
961
962     for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
963       MachineMove &Move = Moves[i];
964       unsigned LabelID = Move.getLabelID();
965       
966       if (LabelID) {
967         LabelID = MMI->MappedLabel(LabelID);
968       
969         // Throw out move if the label is invalid.
970         if (!LabelID) continue;
971       }
972       
973       const MachineLocation &Dst = Move.getDestination();
974       const MachineLocation &Src = Move.getSource();
975       
976       // Advance row if new location.
977       if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
978         Asm->EmitInt8(DW_CFA_advance_loc4);
979         Asm->EOL("DW_CFA_advance_loc4");
980         EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
981         Asm->EOL();
982         
983         BaseLabelID = LabelID;
984         BaseLabel = "label";
985         IsLocal = true;
986       }
987       
988       // If advancing cfa.
989       if (Dst.isRegister() && Dst.getRegister() == MachineLocation::VirtualFP) {
990         if (!Src.isRegister()) {
991           if (Src.getRegister() == MachineLocation::VirtualFP) {
992             Asm->EmitInt8(DW_CFA_def_cfa_offset);
993             Asm->EOL("DW_CFA_def_cfa_offset");
994           } else {
995             Asm->EmitInt8(DW_CFA_def_cfa);
996             Asm->EOL("DW_CFA_def_cfa");
997             Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getRegister()));
998             Asm->EOL("Register");
999           }
1000           
1001           int Offset = -Src.getOffset();
1002           
1003           Asm->EmitULEB128Bytes(Offset);
1004           Asm->EOL("Offset");
1005         } else {
1006           assert(0 && "Machine move no supported yet.");
1007         }
1008       } else if (Src.isRegister() &&
1009         Src.getRegister() == MachineLocation::VirtualFP) {
1010         if (Dst.isRegister()) {
1011           Asm->EmitInt8(DW_CFA_def_cfa_register);
1012           Asm->EOL("DW_CFA_def_cfa_register");
1013           Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getRegister()));
1014           Asm->EOL("Register");
1015         } else {
1016           assert(0 && "Machine move no supported yet.");
1017         }
1018       } else {
1019         unsigned Reg = RI->getDwarfRegNum(Src.getRegister());
1020         int Offset = Dst.getOffset() / stackGrowth;
1021         
1022         if (Offset < 0) {
1023           Asm->EmitInt8(DW_CFA_offset_extended_sf);
1024           Asm->EOL("DW_CFA_offset_extended_sf");
1025           Asm->EmitULEB128Bytes(Reg);
1026           Asm->EOL("Reg");
1027           Asm->EmitSLEB128Bytes(Offset);
1028           Asm->EOL("Offset");
1029         } else if (Reg < 64) {
1030           Asm->EmitInt8(DW_CFA_offset + Reg);
1031           Asm->EOL("DW_CFA_offset + Reg");
1032           Asm->EmitULEB128Bytes(Offset);
1033           Asm->EOL("Offset");
1034         } else {
1035           Asm->EmitInt8(DW_CFA_offset_extended);
1036           Asm->EOL("DW_CFA_offset_extended");
1037           Asm->EmitULEB128Bytes(Reg);
1038           Asm->EOL("Reg");
1039           Asm->EmitULEB128Bytes(Offset);
1040           Asm->EOL("Offset");
1041         }
1042       }
1043     }
1044   }
1045
1046 };
1047
1048 //===----------------------------------------------------------------------===//
1049 /// DwarfDebug - Emits Dwarf debug directives. 
1050 ///
1051 class DwarfDebug : public Dwarf {
1052
1053 private:
1054   //===--------------------------------------------------------------------===//
1055   // Attributes used to construct specific Dwarf sections.
1056   //
1057   
1058   /// CompileUnits - All the compile units involved in this build.  The index
1059   /// of each entry in this vector corresponds to the sources in MMI.
1060   std::vector<CompileUnit *> CompileUnits;
1061   
1062   /// AbbreviationsSet - Used to uniquely define abbreviations.
1063   ///
1064   FoldingSet<DIEAbbrev> AbbreviationsSet;
1065
1066   /// Abbreviations - A list of all the unique abbreviations in use.
1067   ///
1068   std::vector<DIEAbbrev *> Abbreviations;
1069   
1070   /// ValuesSet - Used to uniquely define values.
1071   ///
1072   FoldingSet<DIEValue> ValuesSet;
1073   
1074   /// Values - A list of all the unique values in use.
1075   ///
1076   std::vector<DIEValue *> Values;
1077   
1078   /// StringPool - A UniqueVector of strings used by indirect references.
1079   ///
1080   UniqueVector<std::string> StringPool;
1081
1082   /// UnitMap - Map debug information descriptor to compile unit.
1083   ///
1084   std::map<DebugInfoDesc *, CompileUnit *> DescToUnitMap;
1085   
1086   /// SectionMap - Provides a unique id per text section.
1087   ///
1088   UniqueVector<std::string> SectionMap;
1089   
1090   /// SectionSourceLines - Tracks line numbers per text section.
1091   ///
1092   std::vector<std::vector<SourceLineInfo> > SectionSourceLines;
1093
1094   /// didInitial - Flag to indicate if initial emission has been done.
1095   ///
1096   bool didInitial;
1097   
1098   /// shouldEmit - Flag to indicate if debug information should be emitted.
1099   ///
1100   bool shouldEmit;
1101
1102 public:
1103   
1104   /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
1105   ///
1106   bool ShouldEmitDwarf() const { return shouldEmit; }
1107
1108   /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1109   ///  
1110   void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1111     // Profile the node so that we can make it unique.
1112     FoldingSetNodeID ID;
1113     Abbrev.Profile(ID);
1114     
1115     // Check the set for priors.
1116     DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1117     
1118     // If it's newly added.
1119     if (InSet == &Abbrev) {
1120       // Add to abbreviation list. 
1121       Abbreviations.push_back(&Abbrev);
1122       // Assign the vector position + 1 as its number.
1123       Abbrev.setNumber(Abbreviations.size());
1124     } else {
1125       // Assign existing abbreviation number.
1126       Abbrev.setNumber(InSet->getNumber());
1127     }
1128   }
1129
1130   /// NewString - Add a string to the constant pool and returns a label.
1131   ///
1132   DWLabel NewString(const std::string &String) {
1133     unsigned StringID = StringPool.insert(String);
1134     return DWLabel("string", StringID);
1135   }
1136   
1137   /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1138   /// entry.
1139   DIEntry *NewDIEntry(DIE *Entry = NULL) {
1140     DIEntry *Value;
1141     
1142     if (Entry) {
1143       FoldingSetNodeID ID;
1144       DIEntry::Profile(ID, Entry);
1145       void *Where;
1146       Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1147       
1148       if (Value) return Value;
1149       
1150       Value = new DIEntry(Entry);
1151       ValuesSet.InsertNode(Value, Where);
1152     } else {
1153       Value = new DIEntry(Entry);
1154     }
1155     
1156     Values.push_back(Value);
1157     return Value;
1158   }
1159   
1160   /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1161   ///
1162   void SetDIEntry(DIEntry *Value, DIE *Entry) {
1163     Value->Entry = Entry;
1164     // Add to values set if not already there.  If it is, we merely have a
1165     // duplicate in the values list (no harm.)
1166     ValuesSet.GetOrInsertNode(Value);
1167   }
1168
1169   /// AddUInt - Add an unsigned integer attribute data and value.
1170   ///
1171   void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1172     if (!Form) Form = DIEInteger::BestForm(false, Integer);
1173
1174     FoldingSetNodeID ID;
1175     DIEInteger::Profile(ID, Integer);
1176     void *Where;
1177     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1178     if (!Value) {
1179       Value = new DIEInteger(Integer);
1180       ValuesSet.InsertNode(Value, Where);
1181       Values.push_back(Value);
1182     }
1183   
1184     Die->AddValue(Attribute, Form, Value);
1185   }
1186       
1187   /// AddSInt - Add an signed integer attribute data and value.
1188   ///
1189   void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1190     if (!Form) Form = DIEInteger::BestForm(true, Integer);
1191
1192     FoldingSetNodeID ID;
1193     DIEInteger::Profile(ID, (uint64_t)Integer);
1194     void *Where;
1195     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1196     if (!Value) {
1197       Value = new DIEInteger(Integer);
1198       ValuesSet.InsertNode(Value, Where);
1199       Values.push_back(Value);
1200     }
1201   
1202     Die->AddValue(Attribute, Form, Value);
1203   }
1204       
1205   /// AddString - Add a std::string attribute data and value.
1206   ///
1207   void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1208                  const std::string &String) {
1209     FoldingSetNodeID ID;
1210     DIEString::Profile(ID, String);
1211     void *Where;
1212     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1213     if (!Value) {
1214       Value = new DIEString(String);
1215       ValuesSet.InsertNode(Value, Where);
1216       Values.push_back(Value);
1217     }
1218   
1219     Die->AddValue(Attribute, Form, Value);
1220   }
1221       
1222   /// AddLabel - Add a Dwarf label attribute data and value.
1223   ///
1224   void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1225                      const DWLabel &Label) {
1226     FoldingSetNodeID ID;
1227     DIEDwarfLabel::Profile(ID, Label);
1228     void *Where;
1229     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1230     if (!Value) {
1231       Value = new DIEDwarfLabel(Label);
1232       ValuesSet.InsertNode(Value, Where);
1233       Values.push_back(Value);
1234     }
1235   
1236     Die->AddValue(Attribute, Form, Value);
1237   }
1238       
1239   /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1240   ///
1241   void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1242                       const std::string &Label) {
1243     FoldingSetNodeID ID;
1244     DIEObjectLabel::Profile(ID, Label);
1245     void *Where;
1246     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1247     if (!Value) {
1248       Value = new DIEObjectLabel(Label);
1249       ValuesSet.InsertNode(Value, Where);
1250       Values.push_back(Value);
1251     }
1252   
1253     Die->AddValue(Attribute, Form, Value);
1254   }
1255       
1256   /// AddDelta - Add a label delta attribute data and value.
1257   ///
1258   void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1259                           const DWLabel &Hi, const DWLabel &Lo) {
1260     FoldingSetNodeID ID;
1261     DIEDelta::Profile(ID, Hi, Lo);
1262     void *Where;
1263     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1264     if (!Value) {
1265       Value = new DIEDelta(Hi, Lo);
1266       ValuesSet.InsertNode(Value, Where);
1267       Values.push_back(Value);
1268     }
1269   
1270     Die->AddValue(Attribute, Form, Value);
1271   }
1272       
1273   /// AddDIEntry - Add a DIE attribute data and value.
1274   ///
1275   void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1276     Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1277   }
1278
1279   /// AddBlock - Add block data.
1280   ///
1281   void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1282     Block->ComputeSize(*this);
1283     FoldingSetNodeID ID;
1284     Block->Profile(ID);
1285     void *Where;
1286     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1287     if (!Value) {
1288       Value = Block;
1289       ValuesSet.InsertNode(Value, Where);
1290       Values.push_back(Value);
1291     } else {
1292       delete Block;
1293     }
1294   
1295     Die->AddValue(Attribute, Block->BestForm(), Value);
1296   }
1297
1298 private:
1299
1300   /// AddSourceLine - Add location information to specified debug information
1301   /// entry.
1302   void AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line) {
1303     if (File && Line) {
1304       CompileUnit *FileUnit = FindCompileUnit(File);
1305       unsigned FileID = FileUnit->getID();
1306       AddUInt(Die, DW_AT_decl_file, 0, FileID);
1307       AddUInt(Die, DW_AT_decl_line, 0, Line);
1308     }
1309   }
1310
1311   /// AddAddress - Add an address attribute to a die based on the location
1312   /// provided.
1313   void AddAddress(DIE *Die, unsigned Attribute,
1314                             const MachineLocation &Location) {
1315     unsigned Reg = RI->getDwarfRegNum(Location.getRegister());
1316     DIEBlock *Block = new DIEBlock();
1317     
1318     if (Location.isRegister()) {
1319       if (Reg < 32) {
1320         AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1321       } else {
1322         AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1323         AddUInt(Block, 0, DW_FORM_udata, Reg);
1324       }
1325     } else {
1326       if (Reg < 32) {
1327         AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1328       } else {
1329         AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1330         AddUInt(Block, 0, DW_FORM_udata, Reg);
1331       }
1332       AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1333     }
1334     
1335     AddBlock(Die, Attribute, 0, Block);
1336   }
1337   
1338   /// AddBasicType - Add a new basic type attribute to the specified entity.
1339   ///
1340   void AddBasicType(DIE *Entity, CompileUnit *Unit,
1341                     const std::string &Name,
1342                     unsigned Encoding, unsigned Size) {
1343     DIE *Die = ConstructBasicType(Unit, Name, Encoding, Size);
1344     AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1345   }
1346   
1347   /// ConstructBasicType - Construct a new basic type.
1348   ///
1349   DIE *ConstructBasicType(CompileUnit *Unit,
1350                           const std::string &Name,
1351                           unsigned Encoding, unsigned Size) {
1352     DIE Buffer(DW_TAG_base_type);
1353     AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1354     AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, Encoding);
1355     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1356     return Unit->AddDie(Buffer);
1357   }
1358   
1359   /// AddPointerType - Add a new pointer type attribute to the specified entity.
1360   ///
1361   void AddPointerType(DIE *Entity, CompileUnit *Unit, const std::string &Name) {
1362     DIE *Die = ConstructPointerType(Unit, Name);
1363     AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1364   }
1365   
1366   /// ConstructPointerType - Construct a new pointer type.
1367   ///
1368   DIE *ConstructPointerType(CompileUnit *Unit, const std::string &Name) {
1369     DIE Buffer(DW_TAG_pointer_type);
1370     AddUInt(&Buffer, DW_AT_byte_size, 0, TAI->getAddressSize());
1371     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1372     return Unit->AddDie(Buffer);
1373   }
1374   
1375   /// AddType - Add a new type attribute to the specified entity.
1376   ///
1377   void AddType(DIE *Entity, TypeDesc *TyDesc, CompileUnit *Unit) {
1378     if (!TyDesc) {
1379       AddBasicType(Entity, Unit, "", DW_ATE_signed, sizeof(int32_t));
1380     } else {
1381       // Check for pre-existence.
1382       DIEntry *&Slot = Unit->getDIEntrySlotFor(TyDesc);
1383       
1384       // If it exists then use the existing value.
1385       if (Slot) {
1386         Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1387         return;
1388       }
1389       
1390       if (SubprogramDesc *SubprogramTy = dyn_cast<SubprogramDesc>(TyDesc)) {
1391         // FIXME - Not sure why programs and variables are coming through here.
1392         // Short cut for handling subprogram types (not really a TyDesc.)
1393         AddPointerType(Entity, Unit, SubprogramTy->getName());
1394       } else if (GlobalVariableDesc *GlobalTy =
1395                                          dyn_cast<GlobalVariableDesc>(TyDesc)) {
1396         // FIXME - Not sure why programs and variables are coming through here.
1397         // Short cut for handling global variable types (not really a TyDesc.)
1398         AddPointerType(Entity, Unit, GlobalTy->getName());
1399       } else {  
1400         // Set up proxy.
1401         Slot = NewDIEntry();
1402         
1403         // Construct type.
1404         DIE Buffer(DW_TAG_base_type);
1405         ConstructType(Buffer, TyDesc, Unit);
1406         
1407         // Add debug information entry to entity and unit.
1408         DIE *Die = Unit->AddDie(Buffer);
1409         SetDIEntry(Slot, Die);
1410         Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1411       }
1412     }
1413   }
1414   
1415   /// ConstructType - Adds all the required attributes to the type.
1416   ///
1417   void ConstructType(DIE &Buffer, TypeDesc *TyDesc, CompileUnit *Unit) {
1418     // Get core information.
1419     const std::string &Name = TyDesc->getName();
1420     uint64_t Size = TyDesc->getSize() >> 3;
1421     
1422     if (BasicTypeDesc *BasicTy = dyn_cast<BasicTypeDesc>(TyDesc)) {
1423       // Fundamental types like int, float, bool
1424       Buffer.setTag(DW_TAG_base_type);
1425       AddUInt(&Buffer, DW_AT_encoding,  DW_FORM_data1, BasicTy->getEncoding());
1426     } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
1427       // Fetch tag.
1428       unsigned Tag = DerivedTy->getTag();
1429       // FIXME - Workaround for templates.
1430       if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1431       // Pointers, typedefs et al. 
1432       Buffer.setTag(Tag);
1433       // Map to main type, void will not have a type.
1434       if (TypeDesc *FromTy = DerivedTy->getFromType())
1435         AddType(&Buffer, FromTy, Unit);
1436     } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)){
1437       // Fetch tag.
1438       unsigned Tag = CompTy->getTag();
1439       
1440       // Set tag accordingly.
1441       if (Tag == DW_TAG_vector_type)
1442         Buffer.setTag(DW_TAG_array_type);
1443       else 
1444         Buffer.setTag(Tag);
1445
1446       std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
1447       
1448       switch (Tag) {
1449       case DW_TAG_vector_type:
1450         AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1451         // Fall thru
1452       case DW_TAG_array_type: {
1453         // Add element type.
1454         if (TypeDesc *FromTy = CompTy->getFromType())
1455           AddType(&Buffer, FromTy, Unit);
1456         
1457         // Don't emit size attribute.
1458         Size = 0;
1459         
1460         // Construct an anonymous type for index type.
1461         DIE *IndexTy = ConstructBasicType(Unit, "", DW_ATE_signed,
1462                                           sizeof(int32_t));
1463       
1464         // Add subranges to array type.
1465         for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1466           SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
1467           int64_t Lo = SRD->getLo();
1468           int64_t Hi = SRD->getHi();
1469           DIE *Subrange = new DIE(DW_TAG_subrange_type);
1470           
1471           // If a range is available.
1472           if (Lo != Hi) {
1473             AddDIEntry(Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1474             // Only add low if non-zero.
1475             if (Lo) AddSInt(Subrange, DW_AT_lower_bound, 0, Lo);
1476             AddSInt(Subrange, DW_AT_upper_bound, 0, Hi);
1477           }
1478           
1479           Buffer.AddChild(Subrange);
1480         }
1481         break;
1482       }
1483       case DW_TAG_structure_type:
1484       case DW_TAG_union_type: {
1485         // Add elements to structure type.
1486         for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1487           DebugInfoDesc *Element = Elements[i];
1488           
1489           if (DerivedTypeDesc *MemberDesc = dyn_cast<DerivedTypeDesc>(Element)){
1490             // Add field or base class.
1491             
1492             unsigned Tag = MemberDesc->getTag();
1493           
1494             // Extract the basic information.
1495             const std::string &Name = MemberDesc->getName();
1496             uint64_t Size = MemberDesc->getSize();
1497             uint64_t Align = MemberDesc->getAlign();
1498             uint64_t Offset = MemberDesc->getOffset();
1499        
1500             // Construct member debug information entry.
1501             DIE *Member = new DIE(Tag);
1502             
1503             // Add name if not "".
1504             if (!Name.empty())
1505               AddString(Member, DW_AT_name, DW_FORM_string, Name);
1506             // Add location if available.
1507             AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
1508             
1509             // Most of the time the field info is the same as the members.
1510             uint64_t FieldSize = Size;
1511             uint64_t FieldAlign = Align;
1512             uint64_t FieldOffset = Offset;
1513             
1514             // Set the member type.
1515             TypeDesc *FromTy = MemberDesc->getFromType();
1516             AddType(Member, FromTy, Unit);
1517             
1518             // Walk up typedefs until a real size is found.
1519             while (FromTy) {
1520               if (FromTy->getTag() != DW_TAG_typedef) {
1521                 FieldSize = FromTy->getSize();
1522                 FieldAlign = FromTy->getSize();
1523                 break;
1524               }
1525               
1526               FromTy = dyn_cast<DerivedTypeDesc>(FromTy)->getFromType();
1527             }
1528             
1529             // Unless we have a bit field.
1530             if (Tag == DW_TAG_member && FieldSize != Size) {
1531               // Construct the alignment mask.
1532               uint64_t AlignMask = ~(FieldAlign - 1);
1533               // Determine the high bit + 1 of the declared size.
1534               uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1535               // Work backwards to determine the base offset of the field.
1536               FieldOffset = HiMark - FieldSize;
1537               // Now normalize offset to the field.
1538               Offset -= FieldOffset;
1539               
1540               // Maybe we need to work from the other end.
1541               if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1542               
1543               // Add size and offset.
1544               AddUInt(Member, DW_AT_byte_size, 0, FieldSize >> 3);
1545               AddUInt(Member, DW_AT_bit_size, 0, Size);
1546               AddUInt(Member, DW_AT_bit_offset, 0, Offset);
1547             }
1548             
1549             // Add computation for offset.
1550             DIEBlock *Block = new DIEBlock();
1551             AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1552             AddUInt(Block, 0, DW_FORM_udata, FieldOffset >> 3);
1553             AddBlock(Member, DW_AT_data_member_location, 0, Block);
1554
1555             // Add accessibility (public default unless is base class.
1556             if (MemberDesc->isProtected()) {
1557               AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_protected);
1558             } else if (MemberDesc->isPrivate()) {
1559               AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_private);
1560             } else if (Tag == DW_TAG_inheritance) {
1561               AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_public);
1562             }
1563             
1564             Buffer.AddChild(Member);
1565           } else if (GlobalVariableDesc *StaticDesc =
1566                                         dyn_cast<GlobalVariableDesc>(Element)) {
1567             // Add static member.
1568             
1569             // Construct member debug information entry.
1570             DIE *Static = new DIE(DW_TAG_variable);
1571             
1572             // Add name and mangled name.
1573             const std::string &Name = StaticDesc->getName();
1574             const std::string &LinkageName = StaticDesc->getLinkageName();
1575             AddString(Static, DW_AT_name, DW_FORM_string, Name);
1576             if (!LinkageName.empty()) {
1577               AddString(Static, DW_AT_MIPS_linkage_name, DW_FORM_string,
1578                                 LinkageName);
1579             }
1580             
1581             // Add location.
1582             AddSourceLine(Static, StaticDesc->getFile(), StaticDesc->getLine());
1583            
1584             // Add type.
1585             if (TypeDesc *StaticTy = StaticDesc->getType())
1586               AddType(Static, StaticTy, Unit);
1587             
1588             // Add flags.
1589             if (!StaticDesc->isStatic())
1590               AddUInt(Static, DW_AT_external, DW_FORM_flag, 1);
1591             AddUInt(Static, DW_AT_declaration, DW_FORM_flag, 1);
1592             
1593             Buffer.AddChild(Static);
1594           } else if (SubprogramDesc *MethodDesc =
1595                                             dyn_cast<SubprogramDesc>(Element)) {
1596             // Add member function.
1597             
1598             // Construct member debug information entry.
1599             DIE *Method = new DIE(DW_TAG_subprogram);
1600            
1601             // Add name and mangled name.
1602             const std::string &Name = MethodDesc->getName();
1603             const std::string &LinkageName = MethodDesc->getLinkageName();
1604             
1605             AddString(Method, DW_AT_name, DW_FORM_string, Name);            
1606             bool IsCTor = TyDesc->getName() == Name;
1607             
1608             if (!LinkageName.empty()) {
1609               AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string,
1610                                 LinkageName);
1611             }
1612             
1613             // Add location.
1614             AddSourceLine(Method, MethodDesc->getFile(), MethodDesc->getLine());
1615            
1616             // Add type.
1617             if (CompositeTypeDesc *MethodTy =
1618                    dyn_cast_or_null<CompositeTypeDesc>(MethodDesc->getType())) {
1619               // Get argument information.
1620               std::vector<DebugInfoDesc *> &Args = MethodTy->getElements();
1621              
1622               // If not a ctor.
1623               if (!IsCTor) {
1624                 // Add return type.
1625                 AddType(Method, dyn_cast<TypeDesc>(Args[0]), Unit);
1626               }
1627               
1628               // Add arguments.
1629               for(unsigned i = 1, N = Args.size(); i < N; ++i) {
1630                 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1631                 AddType(Arg, cast<TypeDesc>(Args[i]), Unit);
1632                 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1);
1633                 Method->AddChild(Arg);
1634               }
1635             }
1636
1637             // Add flags.
1638             if (!MethodDesc->isStatic())
1639               AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
1640             AddUInt(Method, DW_AT_declaration, DW_FORM_flag, 1);
1641               
1642             Buffer.AddChild(Method);
1643           }
1644         }
1645         break;
1646       }
1647       case DW_TAG_enumeration_type: {
1648         // Add enumerators to enumeration type.
1649         for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1650           EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
1651           const std::string &Name = ED->getName();
1652           int64_t Value = ED->getValue();
1653           DIE *Enumerator = new DIE(DW_TAG_enumerator);
1654           AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
1655           AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1656           Buffer.AddChild(Enumerator);
1657         }
1658
1659         break;
1660       }
1661       case DW_TAG_subroutine_type: {
1662         // Add prototype flag.
1663         AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1664         // Add return type.
1665         AddType(&Buffer, dyn_cast<TypeDesc>(Elements[0]), Unit);
1666         
1667         // Add arguments.
1668         for(unsigned i = 1, N = Elements.size(); i < N; ++i) {
1669           DIE *Arg = new DIE(DW_TAG_formal_parameter);
1670           AddType(Arg, cast<TypeDesc>(Elements[i]), Unit);
1671           Buffer.AddChild(Arg);
1672         }
1673         
1674         break;
1675       }
1676       default: break;
1677       }
1678     }
1679    
1680     // Add size if non-zero (derived types don't have a size.)
1681     if (Size) AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1682     // Add name if not anonymous or intermediate type.
1683     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1684     // Add source line info if available.
1685     AddSourceLine(&Buffer, TyDesc->getFile(), TyDesc->getLine());
1686   }
1687
1688   /// NewCompileUnit - Create new compile unit and it's debug information entry.
1689   ///
1690   CompileUnit *NewCompileUnit(CompileUnitDesc *UnitDesc, unsigned ID) {
1691     // Construct debug information entry.
1692     DIE *Die = new DIE(DW_TAG_compile_unit);
1693     if (TAI->isAbsoluteSectionOffsets())
1694       AddLabel(Die, DW_AT_stmt_list, DW_FORM_data4, DWLabel("section_line", 0));
1695     else
1696       AddDelta(Die, DW_AT_stmt_list, DW_FORM_data4, DWLabel("section_line", 0),
1697                DWLabel("section_line", 0));      
1698     AddString(Die, DW_AT_producer,  DW_FORM_string, UnitDesc->getProducer());
1699     AddUInt  (Die, DW_AT_language,  DW_FORM_data1,  UnitDesc->getLanguage());
1700     AddString(Die, DW_AT_name,      DW_FORM_string, UnitDesc->getFileName());
1701     AddString(Die, DW_AT_comp_dir,  DW_FORM_string, UnitDesc->getDirectory());
1702     
1703     // Construct compile unit.
1704     CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
1705     
1706     // Add Unit to compile unit map.
1707     DescToUnitMap[UnitDesc] = Unit;
1708     
1709     return Unit;
1710   }
1711
1712   /// GetBaseCompileUnit - Get the main compile unit.
1713   ///
1714   CompileUnit *GetBaseCompileUnit() const {
1715     CompileUnit *Unit = CompileUnits[0];
1716     assert(Unit && "Missing compile unit.");
1717     return Unit;
1718   }
1719
1720   /// FindCompileUnit - Get the compile unit for the given descriptor.
1721   ///
1722   CompileUnit *FindCompileUnit(CompileUnitDesc *UnitDesc) {
1723     CompileUnit *Unit = DescToUnitMap[UnitDesc];
1724     assert(Unit && "Missing compile unit.");
1725     return Unit;
1726   }
1727
1728   /// NewGlobalVariable - Add a new global variable DIE.
1729   ///
1730   DIE *NewGlobalVariable(GlobalVariableDesc *GVD) {
1731     // Get the compile unit context.
1732     CompileUnitDesc *UnitDesc =
1733       static_cast<CompileUnitDesc *>(GVD->getContext());
1734     CompileUnit *Unit = GetBaseCompileUnit();
1735
1736     // Check for pre-existence.
1737     DIE *&Slot = Unit->getDieMapSlotFor(GVD);
1738     if (Slot) return Slot;
1739     
1740     // Get the global variable itself.
1741     GlobalVariable *GV = GVD->getGlobalVariable();
1742
1743     const std::string &Name = GVD->getName();
1744     const std::string &FullName = GVD->getFullName();
1745     const std::string &LinkageName = GVD->getLinkageName();
1746     // Create the global's variable DIE.
1747     DIE *VariableDie = new DIE(DW_TAG_variable);
1748     AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
1749     if (!LinkageName.empty()) {
1750       AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1751                              LinkageName);
1752     }
1753     AddType(VariableDie, GVD->getType(), Unit);
1754     if (!GVD->isStatic())
1755       AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
1756     
1757     // Add source line info if available.
1758     AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
1759     
1760     // Add address.
1761     DIEBlock *Block = new DIEBlock();
1762     AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
1763     AddObjectLabel(Block, 0, DW_FORM_udata, Asm->getGlobalLinkName(GV));
1764     AddBlock(VariableDie, DW_AT_location, 0, Block);
1765     
1766     // Add to map.
1767     Slot = VariableDie;
1768    
1769     // Add to context owner.
1770     Unit->getDie()->AddChild(VariableDie);
1771     
1772     // Expose as global.
1773     // FIXME - need to check external flag.
1774     Unit->AddGlobal(FullName, VariableDie);
1775     
1776     return VariableDie;
1777   }
1778
1779   /// NewSubprogram - Add a new subprogram DIE.
1780   ///
1781   DIE *NewSubprogram(SubprogramDesc *SPD) {
1782     // Get the compile unit context.
1783     CompileUnitDesc *UnitDesc =
1784       static_cast<CompileUnitDesc *>(SPD->getContext());
1785     CompileUnit *Unit = GetBaseCompileUnit();
1786
1787     // Check for pre-existence.
1788     DIE *&Slot = Unit->getDieMapSlotFor(SPD);
1789     if (Slot) return Slot;
1790     
1791     // Gather the details (simplify add attribute code.)
1792     const std::string &Name = SPD->getName();
1793     const std::string &FullName = SPD->getFullName();
1794     const std::string &LinkageName = SPD->getLinkageName();
1795                                       
1796     DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
1797     AddString(SubprogramDie, DW_AT_name, DW_FORM_string, Name);
1798     if (!LinkageName.empty()) {
1799       AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1800                                LinkageName);
1801     }
1802     if (SPD->getType()) AddType(SubprogramDie, SPD->getType(), Unit);
1803     if (!SPD->isStatic())
1804       AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
1805     AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
1806     
1807     // Add source line info if available.
1808     AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
1809
1810     // Add to map.
1811     Slot = SubprogramDie;
1812    
1813     // Add to context owner.
1814     Unit->getDie()->AddChild(SubprogramDie);
1815     
1816     // Expose as global.
1817     Unit->AddGlobal(FullName, SubprogramDie);
1818     
1819     return SubprogramDie;
1820   }
1821
1822   /// NewScopeVariable - Create a new scope variable.
1823   ///
1824   DIE *NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
1825     // Get the descriptor.
1826     VariableDesc *VD = DV->getDesc();
1827
1828     // Translate tag to proper Dwarf tag.  The result variable is dropped for
1829     // now.
1830     unsigned Tag;
1831     switch (VD->getTag()) {
1832     case DW_TAG_return_variable:  return NULL;
1833     case DW_TAG_arg_variable:     Tag = DW_TAG_formal_parameter; break;
1834     case DW_TAG_auto_variable:    // fall thru
1835     default:                      Tag = DW_TAG_variable; break;
1836     }
1837
1838     // Define variable debug information entry.
1839     DIE *VariableDie = new DIE(Tag);
1840     AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
1841
1842     // Add source line info if available.
1843     AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
1844     
1845     // Add variable type.
1846     AddType(VariableDie, VD->getType(), Unit); 
1847     
1848     // Add variable address.
1849     MachineLocation Location;
1850     RI->getLocation(*MF, DV->getFrameIndex(), Location);
1851     AddAddress(VariableDie, DW_AT_location, Location);
1852
1853     return VariableDie;
1854   }
1855
1856   /// ConstructScope - Construct the components of a scope.
1857   ///
1858   void ConstructScope(DebugScope *ParentScope,
1859                       unsigned ParentStartID, unsigned ParentEndID,
1860                       DIE *ParentDie, CompileUnit *Unit) {
1861     // Add variables to scope.
1862     std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
1863     for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1864       DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
1865       if (VariableDie) ParentDie->AddChild(VariableDie);
1866     }
1867     
1868     // Add nested scopes.
1869     std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
1870     for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1871       // Define the Scope debug information entry.
1872       DebugScope *Scope = Scopes[j];
1873       // FIXME - Ignore inlined functions for the time being.
1874       if (!Scope->getParent()) continue;
1875       
1876       unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1877       unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1878
1879       // Ignore empty scopes.
1880       if (StartID == EndID && StartID != 0) continue;
1881       if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
1882       
1883       if (StartID == ParentStartID && EndID == ParentEndID) {
1884         // Just add stuff to the parent scope.
1885         ConstructScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1886       } else {
1887         DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
1888         
1889         // Add the scope bounds.
1890         if (StartID) {
1891           AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1892                              DWLabel("label", StartID));
1893         } else {
1894           AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1895                              DWLabel("func_begin", SubprogramCount));
1896         }
1897         if (EndID) {
1898           AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1899                              DWLabel("label", EndID));
1900         } else {
1901           AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1902                              DWLabel("func_end", SubprogramCount));
1903         }
1904                            
1905         // Add the scope contents.
1906         ConstructScope(Scope, StartID, EndID, ScopeDie, Unit);
1907         ParentDie->AddChild(ScopeDie);
1908       }
1909     }
1910   }
1911
1912   /// ConstructRootScope - Construct the scope for the subprogram.
1913   ///
1914   void ConstructRootScope(DebugScope *RootScope) {
1915     // Exit if there is no root scope.
1916     if (!RootScope) return;
1917     
1918     // Get the subprogram debug information entry. 
1919     SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
1920     
1921     // Get the compile unit context.
1922     CompileUnit *Unit = GetBaseCompileUnit();
1923     
1924     // Get the subprogram die.
1925     DIE *SPDie = Unit->getDieMapSlotFor(SPD);
1926     assert(SPDie && "Missing subprogram descriptor");
1927     
1928     // Add the function bounds.
1929     AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
1930                     DWLabel("func_begin", SubprogramCount));
1931     AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
1932                     DWLabel("func_end", SubprogramCount));
1933     MachineLocation Location(RI->getFrameRegister(*MF));
1934     AddAddress(SPDie, DW_AT_frame_base, Location);
1935
1936     ConstructScope(RootScope, 0, 0, SPDie, Unit);
1937   }
1938
1939   /// EmitInitial - Emit initial Dwarf declarations.  This is necessary for cc
1940   /// tools to recognize the object file contains Dwarf information.
1941   void EmitInitial() {
1942     // Check to see if we already emitted intial headers.
1943     if (didInitial) return;
1944     didInitial = true;
1945     
1946     // Dwarf sections base addresses.
1947     if (TAI->getDwarfRequiresFrameSection()) {
1948       Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1949       EmitLabel("section_frame", 0);
1950     }
1951     Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
1952     EmitLabel("section_info", 0);
1953     Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
1954     EmitLabel("section_abbrev", 0);
1955     Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
1956     EmitLabel("section_aranges", 0);
1957     Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
1958     EmitLabel("section_macinfo", 0);
1959     Asm->SwitchToDataSection(TAI->getDwarfLineSection());
1960     EmitLabel("section_line", 0);
1961     Asm->SwitchToDataSection(TAI->getDwarfLocSection());
1962     EmitLabel("section_loc", 0);
1963     Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
1964     EmitLabel("section_pubnames", 0);
1965     Asm->SwitchToDataSection(TAI->getDwarfStrSection());
1966     EmitLabel("section_str", 0);
1967     Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
1968     EmitLabel("section_ranges", 0);
1969
1970     Asm->SwitchToTextSection(TAI->getTextSection());
1971     EmitLabel("text_begin", 0);
1972     Asm->SwitchToDataSection(TAI->getDataSection());
1973     EmitLabel("data_begin", 0);
1974
1975     // Emit common frame information.
1976     EmitInitialDebugFrame();
1977   }
1978
1979   /// EmitDIE - Recusively Emits a debug information entry.
1980   ///
1981   void EmitDIE(DIE *Die) const {
1982     // Get the abbreviation for this DIE.
1983     unsigned AbbrevNumber = Die->getAbbrevNumber();
1984     const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1985     
1986     Asm->EOL();
1987
1988     // Emit the code (index) for the abbreviation.
1989     Asm->EmitULEB128Bytes(AbbrevNumber);
1990     Asm->EOL(std::string("Abbrev [" +
1991              utostr(AbbrevNumber) +
1992              "] 0x" + utohexstr(Die->getOffset()) +
1993              ":0x" + utohexstr(Die->getSize()) + " " +
1994              TagString(Abbrev->getTag())));
1995     
1996     const std::vector<DIEValue *> &Values = Die->getValues();
1997     const std::vector<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1998     
1999     // Emit the DIE attribute values.
2000     for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2001       unsigned Attr = AbbrevData[i].getAttribute();
2002       unsigned Form = AbbrevData[i].getForm();
2003       assert(Form && "Too many attributes for DIE (check abbreviation)");
2004       
2005       switch (Attr) {
2006       case DW_AT_sibling: {
2007         Asm->EmitInt32(Die->SiblingOffset());
2008         break;
2009       }
2010       default: {
2011         // Emit an attribute using the defined form.
2012         Values[i]->EmitValue(*this, Form);
2013         break;
2014       }
2015       }
2016       
2017       Asm->EOL(AttributeString(Attr));
2018     }
2019     
2020     // Emit the DIE children if any.
2021     if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2022       const std::vector<DIE *> &Children = Die->getChildren();
2023       
2024       for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2025         EmitDIE(Children[j]);
2026       }
2027       
2028       Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2029     }
2030   }
2031
2032   /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2033   ///
2034   unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2035     // Get the children.
2036     const std::vector<DIE *> &Children = Die->getChildren();
2037     
2038     // If not last sibling and has children then add sibling offset attribute.
2039     if (!Last && !Children.empty()) Die->AddSiblingOffset();
2040
2041     // Record the abbreviation.
2042     AssignAbbrevNumber(Die->getAbbrev());
2043    
2044     // Get the abbreviation for this DIE.
2045     unsigned AbbrevNumber = Die->getAbbrevNumber();
2046     const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2047
2048     // Set DIE offset
2049     Die->setOffset(Offset);
2050     
2051     // Start the size with the size of abbreviation code.
2052     Offset += Asm->SizeULEB128(AbbrevNumber);
2053     
2054     const std::vector<DIEValue *> &Values = Die->getValues();
2055     const std::vector<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2056
2057     // Size the DIE attribute values.
2058     for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2059       // Size attribute value.
2060       Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2061     }
2062     
2063     // Size the DIE children if any.
2064     if (!Children.empty()) {
2065       assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2066              "Children flag not set");
2067       
2068       for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2069         Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2070       }
2071       
2072       // End of children marker.
2073       Offset += sizeof(int8_t);
2074     }
2075
2076     Die->setSize(Offset - Die->getOffset());
2077     return Offset;
2078   }
2079
2080   /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2081   ///
2082   void SizeAndOffsets() {
2083     // Process base compile unit.
2084     CompileUnit *Unit = GetBaseCompileUnit();
2085     // Compute size of compile unit header
2086     unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2087                       sizeof(int16_t) + // DWARF version number
2088                       sizeof(int32_t) + // Offset Into Abbrev. Section
2089                       sizeof(int8_t);   // Pointer Size (in bytes)
2090     SizeAndOffsetDie(Unit->getDie(), Offset, true);
2091   }
2092
2093   /// EmitDebugInfo - Emit the debug info section.
2094   ///
2095   void EmitDebugInfo() const {
2096     // Start debug info section.
2097     Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2098     
2099     CompileUnit *Unit = GetBaseCompileUnit();
2100     DIE *Die = Unit->getDie();
2101     // Emit the compile units header.
2102     EmitLabel("info_begin", Unit->getID());
2103     // Emit size of content not including length itself
2104     unsigned ContentSize = Die->getSize() +
2105                            sizeof(int16_t) + // DWARF version number
2106                            sizeof(int32_t) + // Offset Into Abbrev. Section
2107                            sizeof(int8_t) +  // Pointer Size (in bytes)
2108                            sizeof(int32_t);  // FIXME - extra pad for gdb bug.
2109                            
2110     Asm->EmitInt32(ContentSize);  Asm->EOL("Length of Compilation Unit Info");
2111     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2112     EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true);
2113     Asm->EOL("Offset Into Abbrev. Section");
2114     Asm->EmitInt8(TAI->getAddressSize()); Asm->EOL("Address Size (in bytes)");
2115   
2116     EmitDIE(Die);
2117     // FIXME - extra padding for gdb bug.
2118     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2119     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2120     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2121     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2122     EmitLabel("info_end", Unit->getID());
2123     
2124     Asm->EOL();
2125   }
2126
2127   /// EmitAbbreviations - Emit the abbreviation section.
2128   ///
2129   void EmitAbbreviations() const {
2130     // Check to see if it is worth the effort.
2131     if (!Abbreviations.empty()) {
2132       // Start the debug abbrev section.
2133       Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2134       
2135       EmitLabel("abbrev_begin", 0);
2136       
2137       // For each abbrevation.
2138       for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2139         // Get abbreviation data
2140         const DIEAbbrev *Abbrev = Abbreviations[i];
2141         
2142         // Emit the abbrevations code (base 1 index.)
2143         Asm->EmitULEB128Bytes(Abbrev->getNumber());
2144         Asm->EOL("Abbreviation Code");
2145         
2146         // Emit the abbreviations data.
2147         Abbrev->Emit(*this);
2148     
2149         Asm->EOL();
2150       }
2151       
2152       // Mark end of abbreviations.
2153       Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2154
2155       EmitLabel("abbrev_end", 0);
2156     
2157       Asm->EOL();
2158     }
2159   }
2160
2161   /// EmitDebugLines - Emit source line information.
2162   ///
2163   void EmitDebugLines() const {
2164     // Minimum line delta, thus ranging from -10..(255-10).
2165     const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2166     // Maximum line delta, thus ranging from -10..(255-10).
2167     const int MaxLineDelta = 255 + MinLineDelta;
2168
2169     // Start the dwarf line section.
2170     Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2171     
2172     // Construct the section header.
2173     
2174     EmitDifference("line_end", 0, "line_begin", 0, true);
2175     Asm->EOL("Length of Source Line Info");
2176     EmitLabel("line_begin", 0);
2177     
2178     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2179     
2180     EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2181     Asm->EOL("Prolog Length");
2182     EmitLabel("line_prolog_begin", 0);
2183     
2184     Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2185
2186     Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2187
2188     Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2189     
2190     Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2191
2192     Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2193     
2194     // Line number standard opcode encodings argument count
2195     Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2196     Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2197     Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2198     Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2199     Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2200     Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2201     Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2202     Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2203     Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2204
2205     const UniqueVector<std::string> &Directories = MMI->getDirectories();
2206     const UniqueVector<SourceFileInfo>
2207       &SourceFiles = MMI->getSourceFiles();
2208
2209     // Emit directories.
2210     for (unsigned DirectoryID = 1, NDID = Directories.size();
2211                   DirectoryID <= NDID; ++DirectoryID) {
2212       Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
2213     }
2214     Asm->EmitInt8(0); Asm->EOL("End of directories");
2215     
2216     // Emit files.
2217     for (unsigned SourceID = 1, NSID = SourceFiles.size();
2218                  SourceID <= NSID; ++SourceID) {
2219       const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2220       Asm->EmitString(SourceFile.getName());
2221       Asm->EOL("Source");
2222       Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
2223       Asm->EOL("Directory #");
2224       Asm->EmitULEB128Bytes(0);
2225       Asm->EOL("Mod date");
2226       Asm->EmitULEB128Bytes(0);
2227       Asm->EOL("File size");
2228     }
2229     Asm->EmitInt8(0); Asm->EOL("End of files");
2230     
2231     EmitLabel("line_prolog_end", 0);
2232     
2233     // A sequence for each text section.
2234     for (unsigned j = 0, M = SectionSourceLines.size(); j < M; ++j) {
2235       // Isolate current sections line info.
2236       const std::vector<SourceLineInfo> &LineInfos = SectionSourceLines[j];
2237       
2238       Asm->EOL(std::string("Section ") + SectionMap[j + 1]);
2239
2240       // Dwarf assumes we start with first line of first source file.
2241       unsigned Source = 1;
2242       unsigned Line = 1;
2243       
2244       // Construct rows of the address, source, line, column matrix.
2245       for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2246         const SourceLineInfo &LineInfo = LineInfos[i];
2247         unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2248         if (!LabelID) continue;
2249         
2250         unsigned SourceID = LineInfo.getSourceID();
2251         const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2252         unsigned DirectoryID = SourceFile.getDirectoryID();
2253         Asm->EOL(Directories[DirectoryID]
2254           + SourceFile.getName()
2255           + ":"
2256           + utostr_32(LineInfo.getLine()));
2257
2258         // Define the line address.
2259         Asm->EmitInt8(0); Asm->EOL("Extended Op");
2260         Asm->EmitInt8(TAI->getAddressSize() + 1); Asm->EOL("Op size");
2261         Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2262         EmitReference("label",  LabelID); Asm->EOL("Location label");
2263         
2264         // If change of source, then switch to the new source.
2265         if (Source != LineInfo.getSourceID()) {
2266           Source = LineInfo.getSourceID();
2267           Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2268           Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2269         }
2270         
2271         // If change of line.
2272         if (Line != LineInfo.getLine()) {
2273           // Determine offset.
2274           int Offset = LineInfo.getLine() - Line;
2275           int Delta = Offset - MinLineDelta;
2276           
2277           // Update line.
2278           Line = LineInfo.getLine();
2279           
2280           // If delta is small enough and in range...
2281           if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2282             // ... then use fast opcode.
2283             Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2284           } else {
2285             // ... otherwise use long hand.
2286             Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2287             Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2288             Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2289           }
2290         } else {
2291           // Copy the previous row (different address or source)
2292           Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2293         }
2294       }
2295
2296       // Define last address of section.
2297       Asm->EmitInt8(0); Asm->EOL("Extended Op");
2298       Asm->EmitInt8(TAI->getAddressSize() + 1); Asm->EOL("Op size");
2299       Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2300       EmitReference("section_end", j + 1); Asm->EOL("Section end label");
2301
2302       // Mark end of matrix.
2303       Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2304       Asm->EmitULEB128Bytes(1); Asm->EOL();
2305       Asm->EmitInt8(1); Asm->EOL();
2306     }
2307     
2308     EmitLabel("line_end", 0);
2309     
2310     Asm->EOL();
2311   }
2312     
2313   /// EmitInitialDebugFrame - Emit common frame info into a debug frame section.
2314   ///
2315   void EmitInitialDebugFrame() {
2316     if (!TAI->getDwarfRequiresFrameSection())
2317       return;
2318
2319     int stackGrowth =
2320         Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2321           TargetFrameInfo::StackGrowsUp ?
2322         TAI->getAddressSize() : -TAI->getAddressSize();
2323
2324     // Start the dwarf frame section.
2325     Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2326
2327     EmitLabel("frame_common", 0);
2328     EmitDifference("frame_common_end", 0,
2329                    "frame_common_begin", 0, true);
2330     Asm->EOL("Length of Common Information Entry");
2331
2332     EmitLabel("frame_common_begin", 0);
2333     Asm->EmitInt32((int)DW_CIE_ID);
2334     Asm->EOL("CIE Identifier Tag");
2335     Asm->EmitInt8(DW_CIE_VERSION);
2336     Asm->EOL("CIE Version");
2337     Asm->EmitString("");
2338     Asm->EOL("CIE Augmentation");
2339     Asm->EmitULEB128Bytes(1);
2340     Asm->EOL("CIE Code Alignment Factor");
2341     Asm->EmitSLEB128Bytes(stackGrowth);
2342     Asm->EOL("CIE Data Alignment Factor");   
2343     Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister()));
2344     Asm->EOL("CIE RA Column");
2345     
2346     std::vector<MachineMove> Moves;
2347     RI->getInitialFrameState(Moves);
2348     EmitFrameMoves(NULL, 0, Moves);
2349
2350     Asm->EmitAlignment(2);
2351     EmitLabel("frame_common_end", 0);
2352     
2353     Asm->EOL();
2354   }
2355
2356   /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2357   /// section.
2358   void EmitFunctionDebugFrame() {
2359     if (!TAI->getDwarfRequiresFrameSection())
2360       return;
2361        
2362     // Start the dwarf frame section.
2363     Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2364     
2365     EmitDifference("frame_end", SubprogramCount,
2366                    "frame_begin", SubprogramCount, true);
2367     Asm->EOL("Length of Frame Information Entry");
2368     
2369     EmitLabel("frame_begin", SubprogramCount);
2370
2371     EmitSectionOffset("frame_common_begin", "section_frame", 0, 0, true);
2372     Asm->EOL("FDE CIE offset");
2373
2374     EmitReference("func_begin", SubprogramCount);
2375     Asm->EOL("FDE initial location");
2376     EmitDifference("func_end", SubprogramCount,
2377                    "func_begin", SubprogramCount);
2378     Asm->EOL("FDE address range");
2379     
2380     std::vector<MachineMove> &Moves = MMI->getFrameMoves();
2381     
2382     EmitFrameMoves("func_begin", SubprogramCount, Moves);
2383     
2384     Asm->EmitAlignment(2);
2385     EmitLabel("frame_end", SubprogramCount);
2386
2387     Asm->EOL();
2388   }
2389
2390   /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2391   ///
2392   void EmitDebugPubNames() {
2393     // Start the dwarf pubnames section.
2394     Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2395       
2396     CompileUnit *Unit = GetBaseCompileUnit(); 
2397  
2398     EmitDifference("pubnames_end", Unit->getID(),
2399                    "pubnames_begin", Unit->getID(), true);
2400     Asm->EOL("Length of Public Names Info");
2401     
2402     EmitLabel("pubnames_begin", Unit->getID());
2403     
2404     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2405
2406     EmitSectionOffset("info_begin", "section_info", Unit->getID(), 0, true);
2407     Asm->EOL("Offset of Compilation Unit Info");
2408
2409     EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),true);
2410     Asm->EOL("Compilation Unit Length");
2411     
2412     std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2413     
2414     for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2415                                                 GE = Globals.end();
2416          GI != GE; ++GI) {
2417       const std::string &Name = GI->first;
2418       DIE * Entity = GI->second;
2419       
2420       Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2421       Asm->EmitString(Name); Asm->EOL("External Name");
2422     }
2423   
2424     Asm->EmitInt32(0); Asm->EOL("End Mark");
2425     EmitLabel("pubnames_end", Unit->getID());
2426   
2427     Asm->EOL();
2428   }
2429
2430   /// EmitDebugStr - Emit visible names into a debug str section.
2431   ///
2432   void EmitDebugStr() {
2433     // Check to see if it is worth the effort.
2434     if (!StringPool.empty()) {
2435       // Start the dwarf str section.
2436       Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2437       
2438       // For each of strings in the string pool.
2439       for (unsigned StringID = 1, N = StringPool.size();
2440            StringID <= N; ++StringID) {
2441         // Emit a label for reference from debug information entries.
2442         EmitLabel("string", StringID);
2443         // Emit the string itself.
2444         const std::string &String = StringPool[StringID];
2445         Asm->EmitString(String); Asm->EOL();
2446       }
2447     
2448       Asm->EOL();
2449     }
2450   }
2451
2452   /// EmitDebugLoc - Emit visible names into a debug loc section.
2453   ///
2454   void EmitDebugLoc() {
2455     // Start the dwarf loc section.
2456     Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2457     
2458     Asm->EOL();
2459   }
2460
2461   /// EmitDebugARanges - Emit visible names into a debug aranges section.
2462   ///
2463   void EmitDebugARanges() {
2464     // Start the dwarf aranges section.
2465     Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2466     
2467     // FIXME - Mock up
2468   #if 0
2469     CompileUnit *Unit = GetBaseCompileUnit(); 
2470       
2471     // Don't include size of length
2472     Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2473     
2474     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2475     
2476     EmitReference("info_begin", Unit->getID());
2477     Asm->EOL("Offset of Compilation Unit Info");
2478
2479     Asm->EmitInt8(TAI->getAddressSize()); Asm->EOL("Size of Address");
2480
2481     Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2482
2483     Asm->EmitInt16(0);  Asm->EOL("Pad (1)");
2484     Asm->EmitInt16(0);  Asm->EOL("Pad (2)");
2485
2486     // Range 1
2487     EmitReference("text_begin", 0); Asm->EOL("Address");
2488     EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2489
2490     Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2491     Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2492     
2493     Asm->EOL();
2494   #endif
2495   }
2496
2497   /// EmitDebugRanges - Emit visible names into a debug ranges section.
2498   ///
2499   void EmitDebugRanges() {
2500     // Start the dwarf ranges section.
2501     Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2502     
2503     Asm->EOL();
2504   }
2505
2506   /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2507   ///
2508   void EmitDebugMacInfo() {
2509     // Start the dwarf macinfo section.
2510     Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2511     
2512     Asm->EOL();
2513   }
2514
2515   /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
2516   /// header file.
2517   void ConstructCompileUnitDIEs() {
2518     const UniqueVector<CompileUnitDesc *> CUW = MMI->getCompileUnits();
2519     
2520     for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
2521       unsigned ID = MMI->RecordSource(CUW[i]);
2522       CompileUnit *Unit = NewCompileUnit(CUW[i], ID);
2523       CompileUnits.push_back(Unit);
2524     }
2525   }
2526
2527   /// ConstructGlobalDIEs - Create DIEs for each of the externally visible
2528   /// global variables.
2529   void ConstructGlobalDIEs() {
2530     std::vector<GlobalVariableDesc *> GlobalVariables =
2531         MMI->getAnchoredDescriptors<GlobalVariableDesc>(*M);
2532     
2533     for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
2534       GlobalVariableDesc *GVD = GlobalVariables[i];
2535       NewGlobalVariable(GVD);
2536     }
2537   }
2538
2539   /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
2540   /// subprograms.
2541   void ConstructSubprogramDIEs() {
2542     std::vector<SubprogramDesc *> Subprograms =
2543         MMI->getAnchoredDescriptors<SubprogramDesc>(*M);
2544     
2545     for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2546       SubprogramDesc *SPD = Subprograms[i];
2547       NewSubprogram(SPD);
2548     }
2549   }
2550
2551 public:
2552   //===--------------------------------------------------------------------===//
2553   // Main entry points.
2554   //
2555   DwarfDebug(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
2556   : Dwarf(OS, A, T)
2557   , CompileUnits()
2558   , AbbreviationsSet(InitAbbreviationsSetSize)
2559   , Abbreviations()
2560   , ValuesSet(InitValuesSetSize)
2561   , Values()
2562   , StringPool()
2563   , DescToUnitMap()
2564   , SectionMap()
2565   , SectionSourceLines()
2566   , didInitial(false)
2567   , shouldEmit(false)
2568   {
2569   }
2570   virtual ~DwarfDebug() {
2571     for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i)
2572       delete CompileUnits[i];
2573     for (unsigned j = 0, M = Values.size(); j < M; ++j)
2574       delete Values[j];
2575   }
2576
2577   /// SetModuleInfo - Set machine module information when it's known that pass
2578   /// manager has created it.  Set by the target AsmPrinter.
2579   void SetModuleInfo(MachineModuleInfo *mmi) {
2580     // Make sure initial declarations are made.
2581     if (!MMI && mmi->hasDebugInfo()) {
2582       MMI = mmi;
2583       shouldEmit = true;
2584       
2585       // Emit initial sections
2586       EmitInitial();
2587     
2588       // Create all the compile unit DIEs.
2589       ConstructCompileUnitDIEs();
2590       
2591       // Create DIEs for each of the externally visible global variables.
2592       ConstructGlobalDIEs();
2593
2594       // Create DIEs for each of the externally visible subprograms.
2595       ConstructSubprogramDIEs();
2596       
2597       // Prime section data.
2598       SectionMap.insert(TAI->getTextSection());
2599     }
2600   }
2601
2602   /// BeginModule - Emit all Dwarf sections that should come prior to the
2603   /// content.
2604   void BeginModule(Module *M) {
2605     this->M = M;
2606     
2607     if (!ShouldEmitDwarf()) return;
2608   }
2609
2610   /// EndModule - Emit all Dwarf sections that should come after the content.
2611   ///
2612   void EndModule() {
2613     if (!ShouldEmitDwarf()) return;
2614     
2615     // Standard sections final addresses.
2616     Asm->SwitchToTextSection(TAI->getTextSection());
2617     EmitLabel("text_end", 0);
2618     Asm->SwitchToDataSection(TAI->getDataSection());
2619     EmitLabel("data_end", 0);
2620     
2621     // End text sections.
2622     for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2623       Asm->SwitchToTextSection(SectionMap[i].c_str());
2624       EmitLabel("section_end", i);
2625     }
2626     
2627     // Compute DIE offsets and sizes.
2628     SizeAndOffsets();
2629     
2630     // Emit all the DIEs into a debug info section
2631     EmitDebugInfo();
2632     
2633     // Corresponding abbreviations into a abbrev section.
2634     EmitAbbreviations();
2635     
2636     // Emit source line correspondence into a debug line section.
2637     EmitDebugLines();
2638     
2639     // Emit info into a debug pubnames section.
2640     EmitDebugPubNames();
2641     
2642     // Emit info into a debug str section.
2643     EmitDebugStr();
2644     
2645     // Emit info into a debug loc section.
2646     EmitDebugLoc();
2647     
2648     // Emit info into a debug aranges section.
2649     EmitDebugARanges();
2650     
2651     // Emit info into a debug ranges section.
2652     EmitDebugRanges();
2653     
2654     // Emit info into a debug macinfo section.
2655     EmitDebugMacInfo();
2656   }
2657
2658   /// BeginFunction - Gather pre-function debug information.  Assumes being 
2659   /// emitted immediately after the function entry point.
2660   void BeginFunction(MachineFunction *MF) {
2661     this->MF = MF;
2662     
2663     if (!ShouldEmitDwarf()) return;
2664
2665     // Begin accumulating function debug information.
2666     MMI->BeginFunction(MF);
2667     
2668     // Assumes in correct section after the entry point.
2669     EmitLabel("func_begin", ++SubprogramCount);
2670   }
2671   
2672   /// EndFunction - Gather and emit post-function debug information.
2673   ///
2674   void EndFunction() {
2675     if (!ShouldEmitDwarf()) return;
2676     
2677     // Define end label for subprogram.
2678     EmitLabel("func_end", SubprogramCount);
2679       
2680     // Get function line info.
2681     const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
2682
2683     if (!LineInfos.empty()) {
2684       // Get section line info.
2685       unsigned ID = SectionMap.insert(Asm->CurrentSection);
2686       if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2687       std::vector<SourceLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2688       // Append the function info to section info.
2689       SectionLineInfos.insert(SectionLineInfos.end(),
2690                               LineInfos.begin(), LineInfos.end());
2691     }
2692     
2693     // Construct scopes for subprogram.
2694     ConstructRootScope(MMI->getRootScope());
2695     
2696     // Emit function frame information.
2697     EmitFunctionDebugFrame();
2698   }
2699 };
2700
2701 //===----------------------------------------------------------------------===//
2702 /// DwarfException - Emits Dwarf exception handling directives. 
2703 ///
2704 class DwarfException : public Dwarf  {
2705
2706 private:
2707
2708   /// didInitial - Flag to indicate if initial emission has been done.
2709   ///
2710   bool didInitial;
2711   
2712   /// shouldEmit - Flag to indicate if debug information should be emitted.
2713   ///
2714   bool shouldEmit;
2715   
2716   /// FuncCPPPersonality - C++ persoanlity function.
2717   ///
2718   Function *FuncCPPPersonality;
2719
2720   /// EmitCommonEHFrame - Emit the common eh unwind frame.
2721   ///
2722   void EmitCommonEHFrame() {
2723     // Only do it once.
2724     if (didInitial) return;
2725     didInitial = true;
2726     
2727     // If there is a personality present then we need to indicate that
2728     // in the common eh frame.
2729     Function *Personality = FuncCPPPersonality;
2730
2731     // Size and sign of stack growth.
2732     int stackGrowth =
2733         Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2734           TargetFrameInfo::StackGrowsUp ?
2735         TAI->getAddressSize() : -TAI->getAddressSize();
2736
2737     // Begin eh frame section.
2738     Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2739     O << "EH_frame:\n";
2740     EmitLabel("section_eh_frame", 0);
2741
2742     // Define base labels.
2743     EmitLabel("eh_frame_common", 0);
2744     
2745     // Define the eh frame length.
2746     EmitDifference("eh_frame_common_end", 0,
2747                    "eh_frame_common_begin", 0, true);
2748     Asm->EOL("Length of Common Information Entry");
2749
2750     // EH frame header.
2751     EmitLabel("eh_frame_common_begin", 0);
2752     Asm->EmitInt32((int)0);
2753     Asm->EOL("CIE Identifier Tag");
2754     Asm->EmitInt8(DW_CIE_VERSION);
2755     Asm->EOL("CIE Version");
2756     
2757     // The personality presence indicates that language specific information
2758     // will show up in the eh frame.
2759     Asm->EmitString(Personality ? "zPLR" : "zR");
2760     Asm->EOL("CIE Augmentation");
2761     
2762     // Round out reader.
2763     Asm->EmitULEB128Bytes(1);
2764     Asm->EOL("CIE Code Alignment Factor");
2765     Asm->EmitSLEB128Bytes(stackGrowth);
2766     Asm->EOL("CIE Data Alignment Factor");   
2767     Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister()));
2768     Asm->EOL("CIE RA Column");
2769     
2770     // If there is a personality, we need to indicate the functions location.
2771     if (Personality) {
2772       Asm->EmitULEB128Bytes(7);
2773       Asm->EOL("Augmentation Size");
2774       Asm->EmitInt8(DW_EH_PE_indirect |
2775                             DW_EH_PE_pcrel |
2776                             DW_EH_PE_sdata4);
2777       Asm->EOL("Personality (indirect pcrel sdata4)");
2778       
2779       O << TAI->getData32bitsDirective();
2780       Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
2781       O << "-" << TAI->getPCSymbol();
2782       Asm->EOL("Personality");
2783       
2784       Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2785       Asm->EOL("LSDA Encoding (pcrel)");
2786       Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2787       Asm->EOL("FDE Encoding (pcrel)");
2788    } else {
2789       Asm->EmitULEB128Bytes(1);
2790       Asm->EOL("Augmentation Size");
2791       Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2792       Asm->EOL("FDE Encoding (pcrel)");
2793     }
2794
2795     // Indicate locations of general callee saved registers in frame.
2796     std::vector<MachineMove> Moves;
2797     RI->getInitialFrameState(Moves);
2798     EmitFrameMoves(NULL, 0, Moves);
2799
2800     Asm->EmitAlignment(2);
2801     EmitLabel("eh_frame_common_end", 0);
2802     
2803     Asm->EOL();
2804   }
2805   
2806   /// EmitEHFrame - Emit initial exception information.
2807   ///
2808   void EmitEHFrame() {
2809     // If there is a personality present then we need to indicate that
2810     // in the common eh frame.
2811     Function *Personality = FuncCPPPersonality;
2812 //    Function *Personality = MMI->getPersonality();
2813     MachineFrameInfo *MFI = MF->getFrameInfo();
2814
2815     Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2816
2817     // Externally visible entry into the functions eh frame info.
2818     if (const char *GlobalDirective = TAI->getGlobalDirective())
2819       O << GlobalDirective << getAsm()->CurrentFnName << ".eh\n";
2820     
2821     // If there are no calls then you can't unwind.
2822     if (!MFI->hasCalls()) { 
2823       O << getAsm()->CurrentFnName << ".eh = 0\n";
2824     } else {
2825       O << getAsm()->CurrentFnName << ".eh:\n";
2826       
2827       // EH frame header.
2828       EmitDifference("eh_frame_end", SubprogramCount,
2829                      "eh_frame_begin", SubprogramCount, true);
2830       Asm->EOL("Length of Frame Information Entry");
2831       
2832       EmitLabel("eh_frame_begin", SubprogramCount);
2833
2834       EmitSectionOffset("eh_frame_begin", "section_eh_frame",
2835                         SubprogramCount, 0, true);
2836       Asm->EOL("FDE CIE offset");
2837
2838       EmitReference("eh_func_begin", SubprogramCount, true);
2839       Asm->EOL("FDE initial location");
2840       EmitDifference("eh_func_end", SubprogramCount,
2841                      "eh_func_begin", SubprogramCount);
2842       Asm->EOL("FDE address range");
2843       
2844       // If there is a personality and landing pads then point to the language
2845       // specific data area in the exception table.
2846       if (Personality) {
2847         Asm->EmitULEB128Bytes(4);
2848         Asm->EOL("Augmentation size");
2849         
2850         if (!MMI->getLandingPads().empty()) {
2851           EmitReference("exception", SubprogramCount, true);
2852         } else if(TAI->getAddressSize() == 8) {
2853           Asm->EmitInt64((int)0);
2854         } else {
2855           Asm->EmitInt32((int)0);
2856         }
2857         Asm->EOL("Language Specific Data Area");
2858       } else {
2859         Asm->EmitULEB128Bytes(0);
2860         Asm->EOL("Augmentation size");
2861       }
2862       
2863       // Indicate locations of function specific  callee saved registers in
2864       // frame.
2865       std::vector<MachineMove> &Moves = MMI->getFrameMoves();
2866       EmitFrameMoves("eh_func_begin", SubprogramCount, Moves);
2867       
2868       Asm->EmitAlignment(2);
2869       EmitLabel("eh_frame_end", SubprogramCount);
2870     }
2871     
2872     if (const char *UsedDirective = TAI->getUsedDirective())
2873       O << UsedDirective << getAsm()->CurrentFnName << ".eh\n\n";
2874   }
2875   
2876   /// EmitExceptionTable - Emit landpads and actions.
2877   ///
2878   /// The general organization of the table is complex, but the basic concepts
2879   /// are easy.  First there is a header which describes the location and
2880   /// organization of the three components that follow.
2881   ///  1. The landing pad site information describes the range of code covered
2882   ///     by the try.  In our case it's an accumulation of the ranges covered
2883   ///     by the invokes in the try.  There is also a reference to the landing
2884   ///     pad that handles the exception once processed.  Finally an index into
2885   ///     the actions table.
2886   ///  2. The action table, in our case, is composed of pairs of type ids
2887   ///     and next action offset.  Starting with the action index from the
2888   ///     landing pad site, each type Id is checked for a match to the current
2889   ///     exception.  If it matches then the exception and type id are passed
2890   ///     on to the landing pad.  Otherwise the next action is looked up.  This
2891   ///     chain is terminated with a next action of zero.  If no type id is
2892   ///     found the the frame is unwound and handling continues.
2893   ///  3. Type id table contains references to all the C++ typeinfo for all
2894   ///     catches in the function.  This tables is reversed indexed base 1.
2895   void EmitExceptionTable() {
2896     // Map all labels and get rid of any dead landing pads.
2897     MMI->TidyLandingPads();
2898     
2899     const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
2900     const std::vector<LandingPadInfo> &LandingPads = MMI->getLandingPads();
2901     if (LandingPads.empty()) return;
2902     
2903     // FIXME - Should fold actions for multiple landing pads.
2904     
2905     // Gather first action index for each landing pad site.
2906     SmallVector<unsigned, 8> Actions;
2907     
2908     // FIXME - Assume there is only one filter typeinfo list per function
2909     // time being.  I.E., Each call to eh_filter will have the same list.
2910     // This can change if a function is inlined. 
2911     const LandingPadInfo *Filter = 0;
2912
2913     // Compute sizes for exception table.
2914     unsigned SizeHeader = sizeof(int8_t) + // LPStart format
2915                           sizeof(int8_t) + // TType format
2916                           sizeof(int8_t) + // TType base offset (NEED ULEB128)
2917                           sizeof(int8_t) + // Call site format
2918                           sizeof(int8_t);  // Call-site table length
2919     unsigned SizeSites = 0;
2920     unsigned SizeActions = 0;
2921
2922     // Look at each landing pad site to compute size.  We need the size of each
2923     // landing pad site info and the size of the landing pad's actions.
2924     for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
2925       const LandingPadInfo &LandingPad = LandingPads[i];
2926       bool IsFilter = LandingPad.IsFilter;
2927       unsigned SizeSiteActions = 0;
2928       const std::vector<unsigned> &TypeIds = LandingPad.TypeIds;
2929       unsigned SizeAction = 0;
2930       signed FirstAction;
2931       
2932       if (IsFilter) {
2933         // FIXME - Assume there is only one filter typeinfo list per function
2934         // time being.  I.E., Each call to eh_filter will have the same list.
2935         // This can change if a function is inlined. 
2936         Filter = &LandingPad;
2937         SizeAction =  Asm->SizeSLEB128(-1) + Asm->SizeSLEB128(0);
2938         SizeSiteActions += SizeAction;
2939         // Record the first action of the landing pad site.
2940         FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
2941       } else if (TypeIds.empty()) {
2942         FirstAction = 0;
2943       } else {
2944         // Gather the action sizes
2945         for (unsigned j = 0, M = TypeIds.size(); j != M; ++j) {
2946           unsigned TypeID = TypeIds[i];
2947           unsigned SizeTypeID = Asm->SizeSLEB128(TypeID);
2948           signed Action = j ? -(SizeAction + SizeTypeID) : 0;
2949           SizeAction = SizeTypeID + Asm->SizeSLEB128(Action);
2950           SizeSiteActions += SizeAction;
2951         }
2952         
2953         // Record the first action of the landing pad site.
2954         FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
2955       }
2956       
2957       Actions.push_back(FirstAction);
2958       
2959       // Compute this sites contribution to size.
2960       SizeActions += SizeSiteActions;
2961       SizeSites += sizeof(int32_t) + // Site start.
2962                    sizeof(int32_t) + // Site length.
2963                    sizeof(int32_t) + // Landing pad.
2964                    Asm->SizeSLEB128(FirstAction); // Action.
2965     }
2966     
2967     // Final tallies.
2968     unsigned SizeTypes = TypeInfos.size() * TAI->getAddressSize();
2969     unsigned SizePreType = SizeHeader + SizeSites + SizeActions;
2970     unsigned SizeAlign =  (4 - SizePreType) & 3;
2971     unsigned TypeOffset = SizePreType +
2972                           SizeTypes +
2973                           SizeAlign - 
2974                           sizeof(int8_t) - // LPStart format
2975                           sizeof(int8_t) - // TType format
2976                           sizeof(int8_t);  // TType base offset (NEED ULEB128)
2977     
2978     // Begin the exception table.
2979     Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
2980     O << "GCC_except_table" << SubprogramCount << ":\n";
2981     EmitLabel("exception", SubprogramCount);
2982     
2983     // Emit the header.
2984     Asm->EmitInt8(DW_EH_PE_omit);
2985     Asm->EOL("LPStart format (DW_EH_PE_omit)");
2986     Asm->EmitInt8(DW_EH_PE_absptr);
2987     Asm->EOL("TType format (DW_EH_PE_absptr)");
2988     Asm->EmitULEB128Bytes(TypeOffset);
2989     Asm->EOL("TType base offset");
2990     Asm->EmitInt8(DW_EH_PE_udata4);
2991     Asm->EOL("Call site format (DW_EH_PE_udata4)");
2992     Asm->EmitULEB128Bytes(SizeSites);
2993     Asm->EOL("Call-site table length");
2994     
2995     // Emit the landng pad site information.
2996     for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
2997       const LandingPadInfo &LandingPad = LandingPads[i];
2998       EmitSectionOffset("label", "eh_func_begin",
2999                         LandingPad.BeginLabel, SubprogramCount);
3000       Asm->EOL("Region start");
3001       
3002       EmitDifference("label", LandingPad.EndLabel,
3003                      "label", LandingPad.BeginLabel);
3004       Asm->EOL("Region length");
3005       
3006       if (LandingPad.TypeIds.empty()) {
3007         if (TAI->getAddressSize() == sizeof(int32_t))
3008           Asm->EmitInt32(0);
3009         else
3010           Asm->EmitInt64(0);
3011       } else {
3012         EmitSectionOffset("label", "eh_func_begin",
3013                           LandingPad.LandingPadLabel, SubprogramCount);
3014       }
3015       Asm->EOL("Landing pad");
3016
3017       Asm->EmitULEB128Bytes(Actions[i]);
3018       Asm->EOL("Action");
3019     }
3020     
3021     // Emit the actions.
3022     for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3023       const LandingPadInfo &LandingPad = LandingPads[i];
3024       const std::vector<unsigned> &TypeIds = LandingPad.TypeIds;
3025       unsigned SizeAction = 0;
3026       
3027       if (LandingPad.IsFilter) {
3028         Asm->EmitSLEB128Bytes(-1);
3029         Asm->EOL("TypeInfo index");
3030         Asm->EmitSLEB128Bytes(0);
3031         Asm->EOL("Next action");
3032       } else {
3033         for (unsigned j = 0, M = TypeIds.size(); j < M; ++j) {
3034           unsigned TypeID = TypeIds[j];
3035           unsigned SizeTypeID = Asm->SizeSLEB128(TypeID);
3036           Asm->EmitSLEB128Bytes(TypeID);
3037           Asm->EOL("TypeInfo index");
3038           signed Action = j ? -(SizeAction + SizeTypeID) : 0;
3039           SizeAction = SizeTypeID + Asm->SizeSLEB128(Action);
3040           Asm->EmitSLEB128Bytes(Action);
3041           Asm->EOL("Next action");
3042         }
3043       }
3044     }
3045
3046     // Emit the type ids.
3047     Asm->EmitAlignment(2);
3048     for (unsigned M = TypeInfos.size(); M; --M) {
3049       GlobalVariable *GV = TypeInfos[M - 1];
3050       
3051       if (TAI->getAddressSize() == sizeof(int32_t))
3052         O << TAI->getData32bitsDirective();
3053       else
3054         O << TAI->getData64bitsDirective();
3055
3056       if (GV)
3057         O << Asm->getGlobalLinkName(GV);
3058       else
3059         O << "0";
3060       
3061       Asm->EOL("TypeInfo");
3062     }
3063
3064     // Emit the filter typeinfo.
3065     if (Filter) {
3066       const std::vector<unsigned> &TypeIds = Filter->TypeIds;
3067       for (unsigned j = 0, M = TypeIds.size(); j < M; ++j) {
3068         unsigned TypeID = TypeIds[j];
3069         Asm->EmitSLEB128Bytes(TypeID);
3070         Asm->EOL("TypeInfo index");
3071       }
3072       Asm->EmitSLEB128Bytes(0);
3073       Asm->EOL("End of filter typeinfo");
3074     }
3075     
3076     Asm->EmitAlignment(2);
3077   }
3078
3079 public:
3080   //===--------------------------------------------------------------------===//
3081   // Main entry points.
3082   //
3083   DwarfException(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3084   : Dwarf(OS, A, T)
3085   , didInitial(false)
3086   , shouldEmit(false)
3087   , FuncCPPPersonality(NULL)
3088   {}
3089   
3090   virtual ~DwarfException() {}
3091
3092   /// SetModuleInfo - Set machine module information when it's known that pass
3093   /// manager has created it.  Set by the target AsmPrinter.
3094   void SetModuleInfo(MachineModuleInfo *mmi) {
3095     MMI = mmi;
3096   }
3097
3098   /// BeginModule - Emit all exception information that should come prior to the
3099   /// content.
3100   void BeginModule(Module *M) {
3101     this->M = M;
3102     FuncCPPPersonality = M->getFunction("__gxx_personality_v0");
3103   }
3104
3105   /// EndModule - Emit all exception information that should come after the
3106   /// content.
3107   void EndModule() {
3108   }
3109
3110   /// BeginFunction - Gather pre-function exception information.  Assumes being 
3111   /// emitted immediately after the function entry point.
3112   void BeginFunction(MachineFunction *MF) {
3113     this->MF = MF;
3114     
3115     if (MMI &&
3116         ExceptionHandling &&
3117         TAI->getSupportsExceptionHandling()) {
3118       shouldEmit = true;
3119       // Assumes in correct section after the entry point.
3120       EmitLabel("eh_func_begin", ++SubprogramCount);
3121     }
3122   }
3123
3124   /// EndFunction - Gather and emit post-function exception information.
3125   ///
3126   void EndFunction() {
3127     if (!shouldEmit) return;
3128
3129     EmitLabel("eh_func_end", SubprogramCount);
3130     EmitExceptionTable();
3131     EmitCommonEHFrame();
3132     EmitEHFrame();
3133   }
3134 };
3135
3136 } // End of namespace llvm
3137
3138 //===----------------------------------------------------------------------===//
3139
3140 /// Emit - Print the abbreviation using the specified Dwarf writer.
3141 ///
3142 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
3143   // Emit its Dwarf tag type.
3144   DD.getAsm()->EmitULEB128Bytes(Tag);
3145   DD.getAsm()->EOL(TagString(Tag));
3146   
3147   // Emit whether it has children DIEs.
3148   DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
3149   DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
3150   
3151   // For each attribute description.
3152   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3153     const DIEAbbrevData &AttrData = Data[i];
3154     
3155     // Emit attribute type.
3156     DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
3157     DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
3158     
3159     // Emit form type.
3160     DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
3161     DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
3162   }
3163
3164   // Mark end of abbreviation.
3165   DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
3166   DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
3167 }
3168
3169 #ifndef NDEBUG
3170 void DIEAbbrev::print(std::ostream &O) {
3171   O << "Abbreviation @"
3172     << std::hex << (intptr_t)this << std::dec
3173     << "  "
3174     << TagString(Tag)
3175     << " "
3176     << ChildrenString(ChildrenFlag)
3177     << "\n";
3178   
3179   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3180     O << "  "
3181       << AttributeString(Data[i].getAttribute())
3182       << "  "
3183       << FormEncodingString(Data[i].getForm())
3184       << "\n";
3185   }
3186 }
3187 void DIEAbbrev::dump() { print(cerr); }
3188 #endif
3189
3190 //===----------------------------------------------------------------------===//
3191
3192 #ifndef NDEBUG
3193 void DIEValue::dump() {
3194   print(cerr);
3195 }
3196 #endif
3197
3198 //===----------------------------------------------------------------------===//
3199
3200 /// EmitValue - Emit integer of appropriate size.
3201 ///
3202 void DIEInteger::EmitValue(const DwarfDebug &DD, unsigned Form) const {
3203   switch (Form) {
3204   case DW_FORM_flag:  // Fall thru
3205   case DW_FORM_ref1:  // Fall thru
3206   case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer);         break;
3207   case DW_FORM_ref2:  // Fall thru
3208   case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer);        break;
3209   case DW_FORM_ref4:  // Fall thru
3210   case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer);        break;
3211   case DW_FORM_ref8:  // Fall thru
3212   case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer);        break;
3213   case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
3214   case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
3215   default: assert(0 && "DIE Value form not supported yet");   break;
3216   }
3217 }
3218
3219 /// SizeOf - Determine size of integer value in bytes.
3220 ///
3221 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3222   switch (Form) {
3223   case DW_FORM_flag:  // Fall thru
3224   case DW_FORM_ref1:  // Fall thru
3225   case DW_FORM_data1: return sizeof(int8_t);
3226   case DW_FORM_ref2:  // Fall thru
3227   case DW_FORM_data2: return sizeof(int16_t);
3228   case DW_FORM_ref4:  // Fall thru
3229   case DW_FORM_data4: return sizeof(int32_t);
3230   case DW_FORM_ref8:  // Fall thru
3231   case DW_FORM_data8: return sizeof(int64_t);
3232   case DW_FORM_udata: return DD.getAsm()->SizeULEB128(Integer);
3233   case DW_FORM_sdata: return DD.getAsm()->SizeSLEB128(Integer);
3234   default: assert(0 && "DIE Value form not supported yet"); break;
3235   }
3236   return 0;
3237 }
3238
3239 //===----------------------------------------------------------------------===//
3240
3241 /// EmitValue - Emit string value.
3242 ///
3243 void DIEString::EmitValue(const DwarfDebug &DD, unsigned Form) const {
3244   DD.getAsm()->EmitString(String);
3245 }
3246
3247 //===----------------------------------------------------------------------===//
3248
3249 /// EmitValue - Emit label value.
3250 ///
3251 void DIEDwarfLabel::EmitValue(const DwarfDebug &DD, unsigned Form) const {
3252   DD.EmitReference(Label);
3253 }
3254
3255 /// SizeOf - Determine size of label value in bytes.
3256 ///
3257 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3258   return DD.getTargetAsmInfo()->getAddressSize();
3259 }
3260
3261 //===----------------------------------------------------------------------===//
3262
3263 /// EmitValue - Emit label value.
3264 ///
3265 void DIEObjectLabel::EmitValue(const DwarfDebug &DD, unsigned Form) const {
3266   DD.EmitReference(Label);
3267 }
3268
3269 /// SizeOf - Determine size of label value in bytes.
3270 ///
3271 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3272   return DD.getTargetAsmInfo()->getAddressSize();
3273 }
3274     
3275 //===----------------------------------------------------------------------===//
3276
3277 /// EmitValue - Emit delta value.
3278 ///
3279 void DIEDelta::EmitValue(const DwarfDebug &DD, unsigned Form) const {
3280   bool IsSmall = Form == DW_FORM_data4;
3281   DD.EmitDifference(LabelHi, LabelLo, IsSmall);
3282 }
3283
3284 /// SizeOf - Determine size of delta value in bytes.
3285 ///
3286 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3287   if (Form == DW_FORM_data4) return 4;
3288   return DD.getTargetAsmInfo()->getAddressSize();
3289 }
3290
3291 //===----------------------------------------------------------------------===//
3292
3293 /// EmitValue - Emit debug information entry offset.
3294 ///
3295 void DIEntry::EmitValue(const DwarfDebug &DD, unsigned Form) const {
3296   DD.getAsm()->EmitInt32(Entry->getOffset());
3297 }
3298     
3299 //===----------------------------------------------------------------------===//
3300
3301 /// ComputeSize - calculate the size of the block.
3302 ///
3303 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
3304   if (!Size) {
3305     const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
3306     
3307     for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3308       Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
3309     }
3310   }
3311   return Size;
3312 }
3313
3314 /// EmitValue - Emit block data.
3315 ///
3316 void DIEBlock::EmitValue(const DwarfDebug &DD, unsigned Form) const {
3317   switch (Form) {
3318   case DW_FORM_block1: DD.getAsm()->EmitInt8(Size);         break;
3319   case DW_FORM_block2: DD.getAsm()->EmitInt16(Size);        break;
3320   case DW_FORM_block4: DD.getAsm()->EmitInt32(Size);        break;
3321   case DW_FORM_block:  DD.getAsm()->EmitULEB128Bytes(Size); break;
3322   default: assert(0 && "Improper form for block");          break;
3323   }
3324   
3325   const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
3326
3327   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3328     DD.getAsm()->EOL();
3329     Values[i]->EmitValue(DD, AbbrevData[i].getForm());
3330   }
3331 }
3332
3333 /// SizeOf - Determine size of block data in bytes.
3334 ///
3335 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3336   switch (Form) {
3337   case DW_FORM_block1: return Size + sizeof(int8_t);
3338   case DW_FORM_block2: return Size + sizeof(int16_t);
3339   case DW_FORM_block4: return Size + sizeof(int32_t);
3340   case DW_FORM_block: return Size + DD.getAsm()->SizeULEB128(Size);
3341   default: assert(0 && "Improper form for block"); break;
3342   }
3343   return 0;
3344 }
3345
3346 //===----------------------------------------------------------------------===//
3347 /// DIE Implementation
3348
3349 DIE::~DIE() {
3350   for (unsigned i = 0, N = Children.size(); i < N; ++i)
3351     delete Children[i];
3352 }
3353   
3354 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
3355 ///
3356 void DIE::AddSiblingOffset() {
3357   DIEInteger *DI = new DIEInteger(0);
3358   Values.insert(Values.begin(), DI);
3359   Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
3360 }
3361
3362 /// Profile - Used to gather unique data for the value folding set.
3363 ///
3364 void DIE::Profile(FoldingSetNodeID &ID) {
3365   Abbrev.Profile(ID);
3366   
3367   for (unsigned i = 0, N = Children.size(); i < N; ++i)
3368     ID.AddPointer(Children[i]);
3369
3370   for (unsigned j = 0, M = Values.size(); j < M; ++j)
3371     ID.AddPointer(Values[j]);
3372 }
3373
3374 #ifndef NDEBUG
3375 void DIE::print(std::ostream &O, unsigned IncIndent) {
3376   static unsigned IndentCount = 0;
3377   IndentCount += IncIndent;
3378   const std::string Indent(IndentCount, ' ');
3379   bool isBlock = Abbrev.getTag() == 0;
3380   
3381   if (!isBlock) {
3382     O << Indent
3383       << "Die: "
3384       << "0x" << std::hex << (intptr_t)this << std::dec
3385       << ", Offset: " << Offset
3386       << ", Size: " << Size
3387       << "\n"; 
3388     
3389     O << Indent
3390       << TagString(Abbrev.getTag())
3391       << " "
3392       << ChildrenString(Abbrev.getChildrenFlag());
3393   } else {
3394     O << "Size: " << Size;
3395   }
3396   O << "\n";
3397
3398   const std::vector<DIEAbbrevData> &Data = Abbrev.getData();
3399   
3400   IndentCount += 2;
3401   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3402     O << Indent;
3403     if (!isBlock) {
3404       O << AttributeString(Data[i].getAttribute());
3405     } else {
3406       O << "Blk[" << i << "]";
3407     }
3408     O <<  "  "
3409       << FormEncodingString(Data[i].getForm())
3410       << " ";
3411     Values[i]->print(O);
3412     O << "\n";
3413   }
3414   IndentCount -= 2;
3415
3416   for (unsigned j = 0, M = Children.size(); j < M; ++j) {
3417     Children[j]->print(O, 4);
3418   }
3419   
3420   if (!isBlock) O << "\n";
3421   IndentCount -= IncIndent;
3422 }
3423
3424 void DIE::dump() {
3425   print(cerr);
3426 }
3427 #endif
3428
3429 //===----------------------------------------------------------------------===//
3430 /// DwarfWriter Implementation
3431 ///
3432
3433 DwarfWriter::DwarfWriter(std::ostream &OS, AsmPrinter *A,
3434                          const TargetAsmInfo *T) {
3435   DE = new DwarfException(OS, A, T);
3436   DD = new DwarfDebug(OS, A, T);
3437 }
3438
3439 DwarfWriter::~DwarfWriter() {
3440   delete DE;
3441   delete DD;
3442 }
3443
3444 /// SetModuleInfo - Set machine module info when it's known that pass manager
3445 /// has created it.  Set by the target AsmPrinter.
3446 void DwarfWriter::SetModuleInfo(MachineModuleInfo *MMI) {
3447   DD->SetModuleInfo(MMI);
3448   DE->SetModuleInfo(MMI);
3449 }
3450
3451 /// BeginModule - Emit all Dwarf sections that should come prior to the
3452 /// content.
3453 void DwarfWriter::BeginModule(Module *M) {
3454   DE->BeginModule(M);
3455   DD->BeginModule(M);
3456 }
3457
3458 /// EndModule - Emit all Dwarf sections that should come after the content.
3459 ///
3460 void DwarfWriter::EndModule() {
3461   DE->EndModule();
3462   DD->EndModule();
3463 }
3464
3465 /// BeginFunction - Gather pre-function debug information.  Assumes being 
3466 /// emitted immediately after the function entry point.
3467 void DwarfWriter::BeginFunction(MachineFunction *MF) {
3468   DE->BeginFunction(MF);
3469   DD->BeginFunction(MF);
3470 }
3471
3472 /// EndFunction - Gather and emit post-function debug information.
3473 ///
3474 void DwarfWriter::EndFunction() {
3475   DD->EndFunction();
3476   DE->EndFunction();
3477   
3478   if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI()) {
3479     // Clear function debug information.
3480     MMI->EndFunction();
3481   }
3482 }