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