Emit exception handling info for functions which are
[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 is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing dwarf 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/TargetRegisterInfo.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 TargetRegisterInfo *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 useSet = true) {
930     bool printAbsolute = false;
931     if (isEH)
932       printAbsolute = TAI->isAbsoluteEHSectionOffsets();
933     else
934       printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
935
936     if (TAI->needsSet() && useSet) {
937       O << "\t.set\t";
938       PrintLabelName("set", SetCounter, Flavor);
939       O << ",";
940       PrintLabelName(Label, LabelNumber);
941
942       if (!printAbsolute) {
943         O << "-";
944         PrintLabelName(Section, SectionNumber);
945       }      
946       O << "\n";
947
948       PrintRelDirective(IsSmall);
949         
950       PrintLabelName("set", SetCounter, Flavor);
951       ++SetCounter;
952     } else {
953       PrintRelDirective(IsSmall, true);
954         
955       PrintLabelName(Label, LabelNumber);
956
957       if (!printAbsolute) {
958         O << "-";
959         PrintLabelName(Section, SectionNumber);
960       }
961     }    
962   }
963   
964   /// EmitFrameMoves - Emit frame instructions to describe the layout of the
965   /// frame.
966   void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
967                       const std::vector<MachineMove> &Moves, bool isEH) {
968     int stackGrowth =
969         Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
970           TargetFrameInfo::StackGrowsUp ?
971             TD->getPointerSize() : -TD->getPointerSize();
972     bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
973
974     for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
975       const MachineMove &Move = Moves[i];
976       unsigned LabelID = Move.getLabelID();
977       
978       if (LabelID) {
979         LabelID = MMI->MappedLabel(LabelID);
980       
981         // Throw out move if the label is invalid.
982         if (!LabelID) continue;
983       }
984       
985       const MachineLocation &Dst = Move.getDestination();
986       const MachineLocation &Src = Move.getSource();
987       
988       // Advance row if new location.
989       if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
990         Asm->EmitInt8(DW_CFA_advance_loc4);
991         Asm->EOL("DW_CFA_advance_loc4");
992         EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
993         Asm->EOL();
994         
995         BaseLabelID = LabelID;
996         BaseLabel = "label";
997         IsLocal = true;
998       }
999       
1000       // If advancing cfa.
1001       if (Dst.isRegister() && Dst.getRegister() == MachineLocation::VirtualFP) {
1002         if (!Src.isRegister()) {
1003           if (Src.getRegister() == MachineLocation::VirtualFP) {
1004             Asm->EmitInt8(DW_CFA_def_cfa_offset);
1005             Asm->EOL("DW_CFA_def_cfa_offset");
1006           } else {
1007             Asm->EmitInt8(DW_CFA_def_cfa);
1008             Asm->EOL("DW_CFA_def_cfa");
1009             Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getRegister(), isEH));
1010             Asm->EOL("Register");
1011           }
1012           
1013           int Offset = -Src.getOffset();
1014           
1015           Asm->EmitULEB128Bytes(Offset);
1016           Asm->EOL("Offset");
1017         } else {
1018           assert(0 && "Machine move no supported yet.");
1019         }
1020       } else if (Src.isRegister() &&
1021         Src.getRegister() == MachineLocation::VirtualFP) {
1022         if (Dst.isRegister()) {
1023           Asm->EmitInt8(DW_CFA_def_cfa_register);
1024           Asm->EOL("DW_CFA_def_cfa_register");
1025           Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getRegister(), isEH));
1026           Asm->EOL("Register");
1027         } else {
1028           assert(0 && "Machine move no supported yet.");
1029         }
1030       } else {
1031         unsigned Reg = RI->getDwarfRegNum(Src.getRegister(), isEH);
1032         int Offset = Dst.getOffset() / stackGrowth;
1033         
1034         if (Offset < 0) {
1035           Asm->EmitInt8(DW_CFA_offset_extended_sf);
1036           Asm->EOL("DW_CFA_offset_extended_sf");
1037           Asm->EmitULEB128Bytes(Reg);
1038           Asm->EOL("Reg");
1039           Asm->EmitSLEB128Bytes(Offset);
1040           Asm->EOL("Offset");
1041         } else if (Reg < 64) {
1042           Asm->EmitInt8(DW_CFA_offset + Reg);
1043           Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
1044           Asm->EmitULEB128Bytes(Offset);
1045           Asm->EOL("Offset");
1046         } else {
1047           Asm->EmitInt8(DW_CFA_offset_extended);
1048           Asm->EOL("DW_CFA_offset_extended");
1049           Asm->EmitULEB128Bytes(Reg);
1050           Asm->EOL("Reg");
1051           Asm->EmitULEB128Bytes(Offset);
1052           Asm->EOL("Offset");
1053         }
1054       }
1055     }
1056   }
1057
1058 };
1059
1060 //===----------------------------------------------------------------------===//
1061 /// DwarfDebug - Emits Dwarf debug directives. 
1062 ///
1063 class DwarfDebug : public Dwarf {
1064
1065 private:
1066   //===--------------------------------------------------------------------===//
1067   // Attributes used to construct specific Dwarf sections.
1068   //
1069   
1070   /// CompileUnits - All the compile units involved in this build.  The index
1071   /// of each entry in this vector corresponds to the sources in MMI.
1072   std::vector<CompileUnit *> CompileUnits;
1073   
1074   /// AbbreviationsSet - Used to uniquely define abbreviations.
1075   ///
1076   FoldingSet<DIEAbbrev> AbbreviationsSet;
1077
1078   /// Abbreviations - A list of all the unique abbreviations in use.
1079   ///
1080   std::vector<DIEAbbrev *> Abbreviations;
1081   
1082   /// ValuesSet - Used to uniquely define values.
1083   ///
1084   FoldingSet<DIEValue> ValuesSet;
1085   
1086   /// Values - A list of all the unique values in use.
1087   ///
1088   std::vector<DIEValue *> Values;
1089   
1090   /// StringPool - A UniqueVector of strings used by indirect references.
1091   ///
1092   UniqueVector<std::string> StringPool;
1093
1094   /// UnitMap - Map debug information descriptor to compile unit.
1095   ///
1096   std::map<DebugInfoDesc *, CompileUnit *> DescToUnitMap;
1097   
1098   /// SectionMap - Provides a unique id per text section.
1099   ///
1100   UniqueVector<std::string> SectionMap;
1101   
1102   /// SectionSourceLines - Tracks line numbers per text section.
1103   ///
1104   std::vector<std::vector<SourceLineInfo> > SectionSourceLines;
1105
1106   /// didInitial - Flag to indicate if initial emission has been done.
1107   ///
1108   bool didInitial;
1109   
1110   /// shouldEmit - Flag to indicate if debug information should be emitted.
1111   ///
1112   bool shouldEmit;
1113
1114   struct FunctionDebugFrameInfo {
1115     unsigned Number;
1116     std::vector<MachineMove> Moves;
1117
1118     FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1119       Number(Num), Moves(M) { }
1120   };
1121
1122   std::vector<FunctionDebugFrameInfo> DebugFrames;
1123   
1124 public:
1125   
1126   /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
1127   ///
1128   bool ShouldEmitDwarf() const { return shouldEmit; }
1129
1130   /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1131   ///  
1132   void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1133     // Profile the node so that we can make it unique.
1134     FoldingSetNodeID ID;
1135     Abbrev.Profile(ID);
1136     
1137     // Check the set for priors.
1138     DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1139     
1140     // If it's newly added.
1141     if (InSet == &Abbrev) {
1142       // Add to abbreviation list. 
1143       Abbreviations.push_back(&Abbrev);
1144       // Assign the vector position + 1 as its number.
1145       Abbrev.setNumber(Abbreviations.size());
1146     } else {
1147       // Assign existing abbreviation number.
1148       Abbrev.setNumber(InSet->getNumber());
1149     }
1150   }
1151
1152   /// NewString - Add a string to the constant pool and returns a label.
1153   ///
1154   DWLabel NewString(const std::string &String) {
1155     unsigned StringID = StringPool.insert(String);
1156     return DWLabel("string", StringID);
1157   }
1158   
1159   /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1160   /// entry.
1161   DIEntry *NewDIEntry(DIE *Entry = NULL) {
1162     DIEntry *Value;
1163     
1164     if (Entry) {
1165       FoldingSetNodeID ID;
1166       DIEntry::Profile(ID, Entry);
1167       void *Where;
1168       Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1169       
1170       if (Value) return Value;
1171       
1172       Value = new DIEntry(Entry);
1173       ValuesSet.InsertNode(Value, Where);
1174     } else {
1175       Value = new DIEntry(Entry);
1176     }
1177     
1178     Values.push_back(Value);
1179     return Value;
1180   }
1181   
1182   /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1183   ///
1184   void SetDIEntry(DIEntry *Value, DIE *Entry) {
1185     Value->Entry = Entry;
1186     // Add to values set if not already there.  If it is, we merely have a
1187     // duplicate in the values list (no harm.)
1188     ValuesSet.GetOrInsertNode(Value);
1189   }
1190
1191   /// AddUInt - Add an unsigned integer attribute data and value.
1192   ///
1193   void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1194     if (!Form) Form = DIEInteger::BestForm(false, Integer);
1195
1196     FoldingSetNodeID ID;
1197     DIEInteger::Profile(ID, Integer);
1198     void *Where;
1199     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1200     if (!Value) {
1201       Value = new DIEInteger(Integer);
1202       ValuesSet.InsertNode(Value, Where);
1203       Values.push_back(Value);
1204     }
1205   
1206     Die->AddValue(Attribute, Form, Value);
1207   }
1208       
1209   /// AddSInt - Add an signed integer attribute data and value.
1210   ///
1211   void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1212     if (!Form) Form = DIEInteger::BestForm(true, Integer);
1213
1214     FoldingSetNodeID ID;
1215     DIEInteger::Profile(ID, (uint64_t)Integer);
1216     void *Where;
1217     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1218     if (!Value) {
1219       Value = new DIEInteger(Integer);
1220       ValuesSet.InsertNode(Value, Where);
1221       Values.push_back(Value);
1222     }
1223   
1224     Die->AddValue(Attribute, Form, Value);
1225   }
1226       
1227   /// AddString - Add a std::string attribute data and value.
1228   ///
1229   void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1230                  const std::string &String) {
1231     FoldingSetNodeID ID;
1232     DIEString::Profile(ID, String);
1233     void *Where;
1234     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1235     if (!Value) {
1236       Value = new DIEString(String);
1237       ValuesSet.InsertNode(Value, Where);
1238       Values.push_back(Value);
1239     }
1240   
1241     Die->AddValue(Attribute, Form, Value);
1242   }
1243       
1244   /// AddLabel - Add a Dwarf label attribute data and value.
1245   ///
1246   void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1247                      const DWLabel &Label) {
1248     FoldingSetNodeID ID;
1249     DIEDwarfLabel::Profile(ID, Label);
1250     void *Where;
1251     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1252     if (!Value) {
1253       Value = new DIEDwarfLabel(Label);
1254       ValuesSet.InsertNode(Value, Where);
1255       Values.push_back(Value);
1256     }
1257   
1258     Die->AddValue(Attribute, Form, Value);
1259   }
1260       
1261   /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1262   ///
1263   void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1264                       const std::string &Label) {
1265     FoldingSetNodeID ID;
1266     DIEObjectLabel::Profile(ID, Label);
1267     void *Where;
1268     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1269     if (!Value) {
1270       Value = new DIEObjectLabel(Label);
1271       ValuesSet.InsertNode(Value, Where);
1272       Values.push_back(Value);
1273     }
1274   
1275     Die->AddValue(Attribute, Form, Value);
1276   }
1277       
1278   /// AddDelta - Add a label delta attribute data and value.
1279   ///
1280   void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1281                           const DWLabel &Hi, const DWLabel &Lo) {
1282     FoldingSetNodeID ID;
1283     DIEDelta::Profile(ID, Hi, Lo);
1284     void *Where;
1285     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1286     if (!Value) {
1287       Value = new DIEDelta(Hi, Lo);
1288       ValuesSet.InsertNode(Value, Where);
1289       Values.push_back(Value);
1290     }
1291   
1292     Die->AddValue(Attribute, Form, Value);
1293   }
1294       
1295   /// AddDIEntry - Add a DIE attribute data and value.
1296   ///
1297   void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1298     Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1299   }
1300
1301   /// AddBlock - Add block data.
1302   ///
1303   void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1304     Block->ComputeSize(*this);
1305     FoldingSetNodeID ID;
1306     Block->Profile(ID);
1307     void *Where;
1308     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1309     if (!Value) {
1310       Value = Block;
1311       ValuesSet.InsertNode(Value, Where);
1312       Values.push_back(Value);
1313     } else {
1314       // Already exists, reuse the previous one.
1315       delete Block;
1316       Block = cast<DIEBlock>(Value);
1317     }
1318   
1319     Die->AddValue(Attribute, Block->BestForm(), Value);
1320   }
1321
1322 private:
1323
1324   /// AddSourceLine - Add location information to specified debug information
1325   /// entry.
1326   void AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line) {
1327     if (File && Line) {
1328       CompileUnit *FileUnit = FindCompileUnit(File);
1329       unsigned FileID = FileUnit->getID();
1330       AddUInt(Die, DW_AT_decl_file, 0, FileID);
1331       AddUInt(Die, DW_AT_decl_line, 0, Line);
1332     }
1333   }
1334
1335   /// AddAddress - Add an address attribute to a die based on the location
1336   /// provided.
1337   void AddAddress(DIE *Die, unsigned Attribute,
1338                             const MachineLocation &Location) {
1339     unsigned Reg = RI->getDwarfRegNum(Location.getRegister(), false);
1340     DIEBlock *Block = new DIEBlock();
1341     
1342     if (Location.isRegister()) {
1343       if (Reg < 32) {
1344         AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1345       } else {
1346         AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1347         AddUInt(Block, 0, DW_FORM_udata, Reg);
1348       }
1349     } else {
1350       if (Reg < 32) {
1351         AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1352       } else {
1353         AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1354         AddUInt(Block, 0, DW_FORM_udata, Reg);
1355       }
1356       AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1357     }
1358     
1359     AddBlock(Die, Attribute, 0, Block);
1360   }
1361   
1362   /// AddBasicType - Add a new basic type attribute to the specified entity.
1363   ///
1364   void AddBasicType(DIE *Entity, CompileUnit *Unit,
1365                     const std::string &Name,
1366                     unsigned Encoding, unsigned Size) {
1367     DIE *Die = ConstructBasicType(Unit, Name, Encoding, Size);
1368     AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1369   }
1370   
1371   /// ConstructBasicType - Construct a new basic type.
1372   ///
1373   DIE *ConstructBasicType(CompileUnit *Unit,
1374                           const std::string &Name,
1375                           unsigned Encoding, unsigned Size) {
1376     DIE Buffer(DW_TAG_base_type);
1377     AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1378     AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, Encoding);
1379     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1380     return Unit->AddDie(Buffer);
1381   }
1382   
1383   /// AddPointerType - Add a new pointer type attribute to the specified entity.
1384   ///
1385   void AddPointerType(DIE *Entity, CompileUnit *Unit, const std::string &Name) {
1386     DIE *Die = ConstructPointerType(Unit, Name);
1387     AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
1388   }
1389   
1390   /// ConstructPointerType - Construct a new pointer type.
1391   ///
1392   DIE *ConstructPointerType(CompileUnit *Unit, const std::string &Name) {
1393     DIE Buffer(DW_TAG_pointer_type);
1394     AddUInt(&Buffer, DW_AT_byte_size, 0, TD->getPointerSize());
1395     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1396     return Unit->AddDie(Buffer);
1397   }
1398   
1399   /// AddType - Add a new type attribute to the specified entity.
1400   ///
1401   void AddType(DIE *Entity, TypeDesc *TyDesc, CompileUnit *Unit) {
1402     if (!TyDesc) {
1403       AddBasicType(Entity, Unit, "", DW_ATE_signed, sizeof(int32_t));
1404     } else {
1405       // Check for pre-existence.
1406       DIEntry *&Slot = Unit->getDIEntrySlotFor(TyDesc);
1407       
1408       // If it exists then use the existing value.
1409       if (Slot) {
1410         Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1411         return;
1412       }
1413       
1414       if (SubprogramDesc *SubprogramTy = dyn_cast<SubprogramDesc>(TyDesc)) {
1415         // FIXME - Not sure why programs and variables are coming through here.
1416         // Short cut for handling subprogram types (not really a TyDesc.)
1417         AddPointerType(Entity, Unit, SubprogramTy->getName());
1418       } else if (GlobalVariableDesc *GlobalTy =
1419                                          dyn_cast<GlobalVariableDesc>(TyDesc)) {
1420         // FIXME - Not sure why programs and variables are coming through here.
1421         // Short cut for handling global variable types (not really a TyDesc.)
1422         AddPointerType(Entity, Unit, GlobalTy->getName());
1423       } else {  
1424         // Set up proxy.
1425         Slot = NewDIEntry();
1426         
1427         // Construct type.
1428         DIE Buffer(DW_TAG_base_type);
1429         ConstructType(Buffer, TyDesc, Unit);
1430         
1431         // Add debug information entry to entity and unit.
1432         DIE *Die = Unit->AddDie(Buffer);
1433         SetDIEntry(Slot, Die);
1434         Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1435       }
1436     }
1437   }
1438   
1439   /// ConstructType - Adds all the required attributes to the type.
1440   ///
1441   void ConstructType(DIE &Buffer, TypeDesc *TyDesc, CompileUnit *Unit) {
1442     // Get core information.
1443     const std::string &Name = TyDesc->getName();
1444     uint64_t Size = TyDesc->getSize() >> 3;
1445     
1446     if (BasicTypeDesc *BasicTy = dyn_cast<BasicTypeDesc>(TyDesc)) {
1447       // Fundamental types like int, float, bool
1448       Buffer.setTag(DW_TAG_base_type);
1449       AddUInt(&Buffer, DW_AT_encoding,  DW_FORM_data1, BasicTy->getEncoding());
1450     } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
1451       // Fetch tag.
1452       unsigned Tag = DerivedTy->getTag();
1453       // FIXME - Workaround for templates.
1454       if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1455       // Pointers, typedefs et al. 
1456       Buffer.setTag(Tag);
1457       // Map to main type, void will not have a type.
1458       if (TypeDesc *FromTy = DerivedTy->getFromType())
1459         AddType(&Buffer, FromTy, Unit);
1460     } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)){
1461       // Fetch tag.
1462       unsigned Tag = CompTy->getTag();
1463       
1464       // Set tag accordingly.
1465       if (Tag == DW_TAG_vector_type)
1466         Buffer.setTag(DW_TAG_array_type);
1467       else 
1468         Buffer.setTag(Tag);
1469
1470       std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
1471       
1472       switch (Tag) {
1473       case DW_TAG_vector_type:
1474         AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1475         // Fall thru
1476       case DW_TAG_array_type: {
1477         // Add element type.
1478         if (TypeDesc *FromTy = CompTy->getFromType())
1479           AddType(&Buffer, FromTy, Unit);
1480         
1481         // Don't emit size attribute.
1482         Size = 0;
1483         
1484         // Construct an anonymous type for index type.
1485         DIE *IndexTy = ConstructBasicType(Unit, "", DW_ATE_signed,
1486                                           sizeof(int32_t));
1487       
1488         // Add subranges to array type.
1489         for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1490           SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
1491           int64_t Lo = SRD->getLo();
1492           int64_t Hi = SRD->getHi();
1493           DIE *Subrange = new DIE(DW_TAG_subrange_type);
1494           
1495           // If a range is available.
1496           if (Lo != Hi) {
1497             AddDIEntry(Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1498             // Only add low if non-zero.
1499             if (Lo) AddSInt(Subrange, DW_AT_lower_bound, 0, Lo);
1500             AddSInt(Subrange, DW_AT_upper_bound, 0, Hi);
1501           }
1502           
1503           Buffer.AddChild(Subrange);
1504         }
1505         break;
1506       }
1507       case DW_TAG_structure_type:
1508       case DW_TAG_union_type: {
1509         // Add elements to structure type.
1510         for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1511           DebugInfoDesc *Element = Elements[i];
1512           
1513           if (DerivedTypeDesc *MemberDesc = dyn_cast<DerivedTypeDesc>(Element)){
1514             // Add field or base class.
1515             
1516             unsigned Tag = MemberDesc->getTag();
1517           
1518             // Extract the basic information.
1519             const std::string &Name = MemberDesc->getName();
1520             uint64_t Size = MemberDesc->getSize();
1521             uint64_t Align = MemberDesc->getAlign();
1522             uint64_t Offset = MemberDesc->getOffset();
1523        
1524             // Construct member debug information entry.
1525             DIE *Member = new DIE(Tag);
1526             
1527             // Add name if not "".
1528             if (!Name.empty())
1529               AddString(Member, DW_AT_name, DW_FORM_string, Name);
1530             // Add location if available.
1531             AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
1532             
1533             // Most of the time the field info is the same as the members.
1534             uint64_t FieldSize = Size;
1535             uint64_t FieldAlign = Align;
1536             uint64_t FieldOffset = Offset;
1537             
1538             // Set the member type.
1539             TypeDesc *FromTy = MemberDesc->getFromType();
1540             AddType(Member, FromTy, Unit);
1541             
1542             // Walk up typedefs until a real size is found.
1543             while (FromTy) {
1544               if (FromTy->getTag() != DW_TAG_typedef) {
1545                 FieldSize = FromTy->getSize();
1546                 FieldAlign = FromTy->getSize();
1547                 break;
1548               }
1549               
1550               FromTy = cast<DerivedTypeDesc>(FromTy)->getFromType();
1551             }
1552             
1553             // Unless we have a bit field.
1554             if (Tag == DW_TAG_member && FieldSize != Size) {
1555               // Construct the alignment mask.
1556               uint64_t AlignMask = ~(FieldAlign - 1);
1557               // Determine the high bit + 1 of the declared size.
1558               uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1559               // Work backwards to determine the base offset of the field.
1560               FieldOffset = HiMark - FieldSize;
1561               // Now normalize offset to the field.
1562               Offset -= FieldOffset;
1563               
1564               // Maybe we need to work from the other end.
1565               if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1566               
1567               // Add size and offset.
1568               AddUInt(Member, DW_AT_byte_size, 0, FieldSize >> 3);
1569               AddUInt(Member, DW_AT_bit_size, 0, Size);
1570               AddUInt(Member, DW_AT_bit_offset, 0, Offset);
1571             }
1572             
1573             // Add computation for offset.
1574             DIEBlock *Block = new DIEBlock();
1575             AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1576             AddUInt(Block, 0, DW_FORM_udata, FieldOffset >> 3);
1577             AddBlock(Member, DW_AT_data_member_location, 0, Block);
1578
1579             // Add accessibility (public default unless is base class.
1580             if (MemberDesc->isProtected()) {
1581               AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_protected);
1582             } else if (MemberDesc->isPrivate()) {
1583               AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_private);
1584             } else if (Tag == DW_TAG_inheritance) {
1585               AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_public);
1586             }
1587             
1588             Buffer.AddChild(Member);
1589           } else if (GlobalVariableDesc *StaticDesc =
1590                                         dyn_cast<GlobalVariableDesc>(Element)) {
1591             // Add static member.
1592             
1593             // Construct member debug information entry.
1594             DIE *Static = new DIE(DW_TAG_variable);
1595             
1596             // Add name and mangled name.
1597             const std::string &Name = StaticDesc->getName();
1598             const std::string &LinkageName = StaticDesc->getLinkageName();
1599             AddString(Static, DW_AT_name, DW_FORM_string, Name);
1600             if (!LinkageName.empty()) {
1601               AddString(Static, DW_AT_MIPS_linkage_name, DW_FORM_string,
1602                                 LinkageName);
1603             }
1604             
1605             // Add location.
1606             AddSourceLine(Static, StaticDesc->getFile(), StaticDesc->getLine());
1607            
1608             // Add type.
1609             if (TypeDesc *StaticTy = StaticDesc->getType())
1610               AddType(Static, StaticTy, Unit);
1611             
1612             // Add flags.
1613             if (!StaticDesc->isStatic())
1614               AddUInt(Static, DW_AT_external, DW_FORM_flag, 1);
1615             AddUInt(Static, DW_AT_declaration, DW_FORM_flag, 1);
1616             
1617             Buffer.AddChild(Static);
1618           } else if (SubprogramDesc *MethodDesc =
1619                                             dyn_cast<SubprogramDesc>(Element)) {
1620             // Add member function.
1621             
1622             // Construct member debug information entry.
1623             DIE *Method = new DIE(DW_TAG_subprogram);
1624            
1625             // Add name and mangled name.
1626             const std::string &Name = MethodDesc->getName();
1627             const std::string &LinkageName = MethodDesc->getLinkageName();
1628             
1629             AddString(Method, DW_AT_name, DW_FORM_string, Name);            
1630             bool IsCTor = TyDesc->getName() == Name;
1631             
1632             if (!LinkageName.empty()) {
1633               AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string,
1634                                 LinkageName);
1635             }
1636             
1637             // Add location.
1638             AddSourceLine(Method, MethodDesc->getFile(), MethodDesc->getLine());
1639            
1640             // Add type.
1641             if (CompositeTypeDesc *MethodTy =
1642                    dyn_cast_or_null<CompositeTypeDesc>(MethodDesc->getType())) {
1643               // Get argument information.
1644               std::vector<DebugInfoDesc *> &Args = MethodTy->getElements();
1645              
1646               // If not a ctor.
1647               if (!IsCTor) {
1648                 // Add return type.
1649                 AddType(Method, dyn_cast<TypeDesc>(Args[0]), Unit);
1650               }
1651               
1652               // Add arguments.
1653               for(unsigned i = 1, N = Args.size(); i < N; ++i) {
1654                 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1655                 AddType(Arg, cast<TypeDesc>(Args[i]), Unit);
1656                 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1);
1657                 Method->AddChild(Arg);
1658               }
1659             }
1660
1661             // Add flags.
1662             if (!MethodDesc->isStatic())
1663               AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
1664             AddUInt(Method, DW_AT_declaration, DW_FORM_flag, 1);
1665               
1666             Buffer.AddChild(Method);
1667           }
1668         }
1669         break;
1670       }
1671       case DW_TAG_enumeration_type: {
1672         // Add enumerators to enumeration type.
1673         for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
1674           EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
1675           const std::string &Name = ED->getName();
1676           int64_t Value = ED->getValue();
1677           DIE *Enumerator = new DIE(DW_TAG_enumerator);
1678           AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
1679           AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1680           Buffer.AddChild(Enumerator);
1681         }
1682
1683         break;
1684       }
1685       case DW_TAG_subroutine_type: {
1686         // Add prototype flag.
1687         AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1688         // Add return type.
1689         AddType(&Buffer, dyn_cast<TypeDesc>(Elements[0]), Unit);
1690         
1691         // Add arguments.
1692         for(unsigned i = 1, N = Elements.size(); i < N; ++i) {
1693           DIE *Arg = new DIE(DW_TAG_formal_parameter);
1694           AddType(Arg, cast<TypeDesc>(Elements[i]), Unit);
1695           Buffer.AddChild(Arg);
1696         }
1697         
1698         break;
1699       }
1700       default: break;
1701       }
1702     }
1703    
1704     // Add size if non-zero (derived types don't have a size.)
1705     if (Size) AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1706     // Add name if not anonymous or intermediate type.
1707     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1708     // Add source line info if available.
1709     AddSourceLine(&Buffer, TyDesc->getFile(), TyDesc->getLine());
1710   }
1711
1712   /// NewCompileUnit - Create new compile unit and it's debug information entry.
1713   ///
1714   CompileUnit *NewCompileUnit(CompileUnitDesc *UnitDesc, unsigned ID) {
1715     // Construct debug information entry.
1716     DIE *Die = new DIE(DW_TAG_compile_unit);
1717     if (TAI->isAbsoluteDebugSectionOffsets())
1718       AddLabel(Die, DW_AT_stmt_list, DW_FORM_data4, DWLabel("section_line", 0));
1719     else
1720       AddDelta(Die, DW_AT_stmt_list, DW_FORM_data4, DWLabel("section_line", 0),
1721                DWLabel("section_line", 0));      
1722     AddString(Die, DW_AT_producer,  DW_FORM_string, UnitDesc->getProducer());
1723     AddUInt  (Die, DW_AT_language,  DW_FORM_data1,  UnitDesc->getLanguage());
1724     AddString(Die, DW_AT_name,      DW_FORM_string, UnitDesc->getFileName());
1725     AddString(Die, DW_AT_comp_dir,  DW_FORM_string, UnitDesc->getDirectory());
1726     
1727     // Construct compile unit.
1728     CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
1729     
1730     // Add Unit to compile unit map.
1731     DescToUnitMap[UnitDesc] = Unit;
1732     
1733     return Unit;
1734   }
1735
1736   /// GetBaseCompileUnit - Get the main compile unit.
1737   ///
1738   CompileUnit *GetBaseCompileUnit() const {
1739     CompileUnit *Unit = CompileUnits[0];
1740     assert(Unit && "Missing compile unit.");
1741     return Unit;
1742   }
1743
1744   /// FindCompileUnit - Get the compile unit for the given descriptor.
1745   ///
1746   CompileUnit *FindCompileUnit(CompileUnitDesc *UnitDesc) {
1747     CompileUnit *Unit = DescToUnitMap[UnitDesc];
1748     assert(Unit && "Missing compile unit.");
1749     return Unit;
1750   }
1751
1752   /// NewGlobalVariable - Add a new global variable DIE.
1753   ///
1754   DIE *NewGlobalVariable(GlobalVariableDesc *GVD) {
1755     // Get the compile unit context.
1756     CompileUnitDesc *UnitDesc =
1757       static_cast<CompileUnitDesc *>(GVD->getContext());
1758     CompileUnit *Unit = GetBaseCompileUnit();
1759
1760     // Check for pre-existence.
1761     DIE *&Slot = Unit->getDieMapSlotFor(GVD);
1762     if (Slot) return Slot;
1763     
1764     // Get the global variable itself.
1765     GlobalVariable *GV = GVD->getGlobalVariable();
1766
1767     const std::string &Name = GVD->getName();
1768     const std::string &FullName = GVD->getFullName();
1769     const std::string &LinkageName = GVD->getLinkageName();
1770     // Create the global's variable DIE.
1771     DIE *VariableDie = new DIE(DW_TAG_variable);
1772     AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
1773     if (!LinkageName.empty()) {
1774       AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1775                              LinkageName);
1776     }
1777     AddType(VariableDie, GVD->getType(), Unit);
1778     if (!GVD->isStatic())
1779       AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
1780     
1781     // Add source line info if available.
1782     AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
1783     
1784     // Add address.
1785     DIEBlock *Block = new DIEBlock();
1786     AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
1787     AddObjectLabel(Block, 0, DW_FORM_udata, Asm->getGlobalLinkName(GV));
1788     AddBlock(VariableDie, DW_AT_location, 0, Block);
1789     
1790     // Add to map.
1791     Slot = VariableDie;
1792    
1793     // Add to context owner.
1794     Unit->getDie()->AddChild(VariableDie);
1795     
1796     // Expose as global.
1797     // FIXME - need to check external flag.
1798     Unit->AddGlobal(FullName, VariableDie);
1799     
1800     return VariableDie;
1801   }
1802
1803   /// NewSubprogram - Add a new subprogram DIE.
1804   ///
1805   DIE *NewSubprogram(SubprogramDesc *SPD) {
1806     // Get the compile unit context.
1807     CompileUnitDesc *UnitDesc =
1808       static_cast<CompileUnitDesc *>(SPD->getContext());
1809     CompileUnit *Unit = GetBaseCompileUnit();
1810
1811     // Check for pre-existence.
1812     DIE *&Slot = Unit->getDieMapSlotFor(SPD);
1813     if (Slot) return Slot;
1814     
1815     // Gather the details (simplify add attribute code.)
1816     const std::string &Name = SPD->getName();
1817     const std::string &FullName = SPD->getFullName();
1818     const std::string &LinkageName = SPD->getLinkageName();
1819                                       
1820     DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
1821     AddString(SubprogramDie, DW_AT_name, DW_FORM_string, Name);
1822     if (!LinkageName.empty()) {
1823       AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1824                                LinkageName);
1825     }
1826     if (SPD->getType()) AddType(SubprogramDie, SPD->getType(), Unit);
1827     if (!SPD->isStatic())
1828       AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
1829     AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
1830     
1831     // Add source line info if available.
1832     AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
1833
1834     // Add to map.
1835     Slot = SubprogramDie;
1836    
1837     // Add to context owner.
1838     Unit->getDie()->AddChild(SubprogramDie);
1839     
1840     // Expose as global.
1841     Unit->AddGlobal(FullName, SubprogramDie);
1842     
1843     return SubprogramDie;
1844   }
1845
1846   /// NewScopeVariable - Create a new scope variable.
1847   ///
1848   DIE *NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
1849     // Get the descriptor.
1850     VariableDesc *VD = DV->getDesc();
1851
1852     // Translate tag to proper Dwarf tag.  The result variable is dropped for
1853     // now.
1854     unsigned Tag;
1855     switch (VD->getTag()) {
1856     case DW_TAG_return_variable:  return NULL;
1857     case DW_TAG_arg_variable:     Tag = DW_TAG_formal_parameter; break;
1858     case DW_TAG_auto_variable:    // fall thru
1859     default:                      Tag = DW_TAG_variable; break;
1860     }
1861
1862     // Define variable debug information entry.
1863     DIE *VariableDie = new DIE(Tag);
1864     AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
1865
1866     // Add source line info if available.
1867     AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
1868     
1869     // Add variable type.
1870     AddType(VariableDie, VD->getType(), Unit); 
1871     
1872     // Add variable address.
1873     MachineLocation Location;
1874     Location.set(RI->getFrameRegister(*MF),
1875                  RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
1876     AddAddress(VariableDie, DW_AT_location, Location);
1877
1878     return VariableDie;
1879   }
1880
1881   /// ConstructScope - Construct the components of a scope.
1882   ///
1883   void ConstructScope(DebugScope *ParentScope,
1884                       unsigned ParentStartID, unsigned ParentEndID,
1885                       DIE *ParentDie, CompileUnit *Unit) {
1886     // Add variables to scope.
1887     std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
1888     for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
1889       DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
1890       if (VariableDie) ParentDie->AddChild(VariableDie);
1891     }
1892     
1893     // Add nested scopes.
1894     std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
1895     for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
1896       // Define the Scope debug information entry.
1897       DebugScope *Scope = Scopes[j];
1898       // FIXME - Ignore inlined functions for the time being.
1899       if (!Scope->getParent()) continue;
1900       
1901       unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
1902       unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
1903
1904       // Ignore empty scopes.
1905       if (StartID == EndID && StartID != 0) continue;
1906       if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
1907       
1908       if (StartID == ParentStartID && EndID == ParentEndID) {
1909         // Just add stuff to the parent scope.
1910         ConstructScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
1911       } else {
1912         DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
1913         
1914         // Add the scope bounds.
1915         if (StartID) {
1916           AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1917                              DWLabel("label", StartID));
1918         } else {
1919           AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
1920                              DWLabel("func_begin", SubprogramCount));
1921         }
1922         if (EndID) {
1923           AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1924                              DWLabel("label", EndID));
1925         } else {
1926           AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
1927                              DWLabel("func_end", SubprogramCount));
1928         }
1929                            
1930         // Add the scope contents.
1931         ConstructScope(Scope, StartID, EndID, ScopeDie, Unit);
1932         ParentDie->AddChild(ScopeDie);
1933       }
1934     }
1935   }
1936
1937   /// ConstructRootScope - Construct the scope for the subprogram.
1938   ///
1939   void ConstructRootScope(DebugScope *RootScope) {
1940     // Exit if there is no root scope.
1941     if (!RootScope) return;
1942     
1943     // Get the subprogram debug information entry. 
1944     SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
1945     
1946     // Get the compile unit context.
1947     CompileUnit *Unit = GetBaseCompileUnit();
1948     
1949     // Get the subprogram die.
1950     DIE *SPDie = Unit->getDieMapSlotFor(SPD);
1951     assert(SPDie && "Missing subprogram descriptor");
1952     
1953     // Add the function bounds.
1954     AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
1955                     DWLabel("func_begin", SubprogramCount));
1956     AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
1957                     DWLabel("func_end", SubprogramCount));
1958     MachineLocation Location(RI->getFrameRegister(*MF));
1959     AddAddress(SPDie, DW_AT_frame_base, Location);
1960
1961     ConstructScope(RootScope, 0, 0, SPDie, Unit);
1962   }
1963
1964   /// EmitInitial - Emit initial Dwarf declarations.  This is necessary for cc
1965   /// tools to recognize the object file contains Dwarf information.
1966   void EmitInitial() {
1967     // Check to see if we already emitted intial headers.
1968     if (didInitial) return;
1969     didInitial = true;
1970     
1971     // Dwarf sections base addresses.
1972     if (TAI->doesDwarfRequireFrameSection()) {
1973       Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
1974       EmitLabel("section_debug_frame", 0);
1975     }
1976     Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
1977     EmitLabel("section_info", 0);
1978     Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
1979     EmitLabel("section_abbrev", 0);
1980     Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
1981     EmitLabel("section_aranges", 0);
1982     Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
1983     EmitLabel("section_macinfo", 0);
1984     Asm->SwitchToDataSection(TAI->getDwarfLineSection());
1985     EmitLabel("section_line", 0);
1986     Asm->SwitchToDataSection(TAI->getDwarfLocSection());
1987     EmitLabel("section_loc", 0);
1988     Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
1989     EmitLabel("section_pubnames", 0);
1990     Asm->SwitchToDataSection(TAI->getDwarfStrSection());
1991     EmitLabel("section_str", 0);
1992     Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
1993     EmitLabel("section_ranges", 0);
1994
1995     Asm->SwitchToTextSection(TAI->getTextSection());
1996     EmitLabel("text_begin", 0);
1997     Asm->SwitchToDataSection(TAI->getDataSection());
1998     EmitLabel("data_begin", 0);
1999   }
2000
2001   /// EmitDIE - Recusively Emits a debug information entry.
2002   ///
2003   void EmitDIE(DIE *Die) {
2004     // Get the abbreviation for this DIE.
2005     unsigned AbbrevNumber = Die->getAbbrevNumber();
2006     const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2007     
2008     Asm->EOL();
2009
2010     // Emit the code (index) for the abbreviation.
2011     Asm->EmitULEB128Bytes(AbbrevNumber);
2012     Asm->EOL(std::string("Abbrev [" +
2013              utostr(AbbrevNumber) +
2014              "] 0x" + utohexstr(Die->getOffset()) +
2015              ":0x" + utohexstr(Die->getSize()) + " " +
2016              TagString(Abbrev->getTag())));
2017     
2018     std::vector<DIEValue *> &Values = Die->getValues();
2019     const std::vector<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2020     
2021     // Emit the DIE attribute values.
2022     for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2023       unsigned Attr = AbbrevData[i].getAttribute();
2024       unsigned Form = AbbrevData[i].getForm();
2025       assert(Form && "Too many attributes for DIE (check abbreviation)");
2026       
2027       switch (Attr) {
2028       case DW_AT_sibling: {
2029         Asm->EmitInt32(Die->SiblingOffset());
2030         break;
2031       }
2032       default: {
2033         // Emit an attribute using the defined form.
2034         Values[i]->EmitValue(*this, Form);
2035         break;
2036       }
2037       }
2038       
2039       Asm->EOL(AttributeString(Attr));
2040     }
2041     
2042     // Emit the DIE children if any.
2043     if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2044       const std::vector<DIE *> &Children = Die->getChildren();
2045       
2046       for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2047         EmitDIE(Children[j]);
2048       }
2049       
2050       Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2051     }
2052   }
2053
2054   /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2055   ///
2056   unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2057     // Get the children.
2058     const std::vector<DIE *> &Children = Die->getChildren();
2059     
2060     // If not last sibling and has children then add sibling offset attribute.
2061     if (!Last && !Children.empty()) Die->AddSiblingOffset();
2062
2063     // Record the abbreviation.
2064     AssignAbbrevNumber(Die->getAbbrev());
2065    
2066     // Get the abbreviation for this DIE.
2067     unsigned AbbrevNumber = Die->getAbbrevNumber();
2068     const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2069
2070     // Set DIE offset
2071     Die->setOffset(Offset);
2072     
2073     // Start the size with the size of abbreviation code.
2074     Offset += Asm->SizeULEB128(AbbrevNumber);
2075     
2076     const std::vector<DIEValue *> &Values = Die->getValues();
2077     const std::vector<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2078
2079     // Size the DIE attribute values.
2080     for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2081       // Size attribute value.
2082       Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2083     }
2084     
2085     // Size the DIE children if any.
2086     if (!Children.empty()) {
2087       assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2088              "Children flag not set");
2089       
2090       for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2091         Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2092       }
2093       
2094       // End of children marker.
2095       Offset += sizeof(int8_t);
2096     }
2097
2098     Die->setSize(Offset - Die->getOffset());
2099     return Offset;
2100   }
2101
2102   /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2103   ///
2104   void SizeAndOffsets() {
2105     // Process base compile unit.
2106     CompileUnit *Unit = GetBaseCompileUnit();
2107     // Compute size of compile unit header
2108     unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2109                       sizeof(int16_t) + // DWARF version number
2110                       sizeof(int32_t) + // Offset Into Abbrev. Section
2111                       sizeof(int8_t);   // Pointer Size (in bytes)
2112     SizeAndOffsetDie(Unit->getDie(), Offset, true);
2113   }
2114
2115   /// EmitDebugInfo - Emit the debug info section.
2116   ///
2117   void EmitDebugInfo() {
2118     // Start debug info section.
2119     Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2120     
2121     CompileUnit *Unit = GetBaseCompileUnit();
2122     DIE *Die = Unit->getDie();
2123     // Emit the compile units header.
2124     EmitLabel("info_begin", Unit->getID());
2125     // Emit size of content not including length itself
2126     unsigned ContentSize = Die->getSize() +
2127                            sizeof(int16_t) + // DWARF version number
2128                            sizeof(int32_t) + // Offset Into Abbrev. Section
2129                            sizeof(int8_t) +  // Pointer Size (in bytes)
2130                            sizeof(int32_t);  // FIXME - extra pad for gdb bug.
2131                            
2132     Asm->EmitInt32(ContentSize);  Asm->EOL("Length of Compilation Unit Info");
2133     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2134     EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2135     Asm->EOL("Offset Into Abbrev. Section");
2136     Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2137   
2138     EmitDIE(Die);
2139     // FIXME - extra padding for gdb bug.
2140     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2141     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2142     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2143     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2144     EmitLabel("info_end", Unit->getID());
2145     
2146     Asm->EOL();
2147   }
2148
2149   /// EmitAbbreviations - Emit the abbreviation section.
2150   ///
2151   void EmitAbbreviations() const {
2152     // Check to see if it is worth the effort.
2153     if (!Abbreviations.empty()) {
2154       // Start the debug abbrev section.
2155       Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2156       
2157       EmitLabel("abbrev_begin", 0);
2158       
2159       // For each abbrevation.
2160       for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2161         // Get abbreviation data
2162         const DIEAbbrev *Abbrev = Abbreviations[i];
2163         
2164         // Emit the abbrevations code (base 1 index.)
2165         Asm->EmitULEB128Bytes(Abbrev->getNumber());
2166         Asm->EOL("Abbreviation Code");
2167         
2168         // Emit the abbreviations data.
2169         Abbrev->Emit(*this);
2170     
2171         Asm->EOL();
2172       }
2173       
2174       // Mark end of abbreviations.
2175       Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2176
2177       EmitLabel("abbrev_end", 0);
2178     
2179       Asm->EOL();
2180     }
2181   }
2182
2183   /// EmitDebugLines - Emit source line information.
2184   ///
2185   void EmitDebugLines() {
2186     // If there are no lines to emit (such as when we're using .loc directives
2187     // to emit .debug_line information) don't emit a .debug_line header.
2188     if (SectionSourceLines.empty())
2189       return;
2190
2191     // Minimum line delta, thus ranging from -10..(255-10).
2192     const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2193     // Maximum line delta, thus ranging from -10..(255-10).
2194     const int MaxLineDelta = 255 + MinLineDelta;
2195
2196     // Start the dwarf line section.
2197     Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2198     
2199     // Construct the section header.
2200     
2201     EmitDifference("line_end", 0, "line_begin", 0, true);
2202     Asm->EOL("Length of Source Line Info");
2203     EmitLabel("line_begin", 0);
2204     
2205     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2206     
2207     EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2208     Asm->EOL("Prolog Length");
2209     EmitLabel("line_prolog_begin", 0);
2210     
2211     Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2212
2213     Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2214
2215     Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2216     
2217     Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2218
2219     Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2220     
2221     // Line number standard opcode encodings argument count
2222     Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2223     Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2224     Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2225     Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2226     Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2227     Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2228     Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2229     Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2230     Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2231
2232     const UniqueVector<std::string> &Directories = MMI->getDirectories();
2233     const UniqueVector<SourceFileInfo>
2234       &SourceFiles = MMI->getSourceFiles();
2235
2236     // Emit directories.
2237     for (unsigned DirectoryID = 1, NDID = Directories.size();
2238                   DirectoryID <= NDID; ++DirectoryID) {
2239       Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
2240     }
2241     Asm->EmitInt8(0); Asm->EOL("End of directories");
2242     
2243     // Emit files.
2244     for (unsigned SourceID = 1, NSID = SourceFiles.size();
2245                  SourceID <= NSID; ++SourceID) {
2246       const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2247       Asm->EmitString(SourceFile.getName());
2248       Asm->EOL("Source");
2249       Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
2250       Asm->EOL("Directory #");
2251       Asm->EmitULEB128Bytes(0);
2252       Asm->EOL("Mod date");
2253       Asm->EmitULEB128Bytes(0);
2254       Asm->EOL("File size");
2255     }
2256     Asm->EmitInt8(0); Asm->EOL("End of files");
2257     
2258     EmitLabel("line_prolog_end", 0);
2259     
2260     // A sequence for each text section.
2261     for (unsigned j = 0, M = SectionSourceLines.size(); j < M; ++j) {
2262       // Isolate current sections line info.
2263       const std::vector<SourceLineInfo> &LineInfos = SectionSourceLines[j];
2264       
2265       Asm->EOL(std::string("Section ") + SectionMap[j + 1]);
2266
2267       // Dwarf assumes we start with first line of first source file.
2268       unsigned Source = 1;
2269       unsigned Line = 1;
2270       
2271       // Construct rows of the address, source, line, column matrix.
2272       for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2273         const SourceLineInfo &LineInfo = LineInfos[i];
2274         unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2275         if (!LabelID) continue;
2276         
2277         unsigned SourceID = LineInfo.getSourceID();
2278         const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2279         unsigned DirectoryID = SourceFile.getDirectoryID();
2280         Asm->EOL(Directories[DirectoryID]
2281           + SourceFile.getName()
2282           + ":"
2283           + utostr_32(LineInfo.getLine()));
2284
2285         // Define the line address.
2286         Asm->EmitInt8(0); Asm->EOL("Extended Op");
2287         Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2288         Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2289         EmitReference("label",  LabelID); Asm->EOL("Location label");
2290         
2291         // If change of source, then switch to the new source.
2292         if (Source != LineInfo.getSourceID()) {
2293           Source = LineInfo.getSourceID();
2294           Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2295           Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2296         }
2297         
2298         // If change of line.
2299         if (Line != LineInfo.getLine()) {
2300           // Determine offset.
2301           int Offset = LineInfo.getLine() - Line;
2302           int Delta = Offset - MinLineDelta;
2303           
2304           // Update line.
2305           Line = LineInfo.getLine();
2306           
2307           // If delta is small enough and in range...
2308           if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2309             // ... then use fast opcode.
2310             Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2311           } else {
2312             // ... otherwise use long hand.
2313             Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2314             Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2315             Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2316           }
2317         } else {
2318           // Copy the previous row (different address or source)
2319           Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2320         }
2321       }
2322
2323       // Define last address of section.
2324       Asm->EmitInt8(0); Asm->EOL("Extended Op");
2325       Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2326       Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2327       EmitReference("section_end", j + 1); Asm->EOL("Section end label");
2328
2329       // Mark end of matrix.
2330       Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2331       Asm->EmitULEB128Bytes(1); Asm->EOL();
2332       Asm->EmitInt8(1); Asm->EOL();
2333     }
2334     
2335     EmitLabel("line_end", 0);
2336     
2337     Asm->EOL();
2338   }
2339     
2340   /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2341   ///
2342   void EmitCommonDebugFrame() {
2343     if (!TAI->doesDwarfRequireFrameSection())
2344       return;
2345
2346     int stackGrowth =
2347         Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2348           TargetFrameInfo::StackGrowsUp ?
2349         TD->getPointerSize() : -TD->getPointerSize();
2350
2351     // Start the dwarf frame section.
2352     Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2353
2354     EmitLabel("debug_frame_common", 0);
2355     EmitDifference("debug_frame_common_end", 0,
2356                    "debug_frame_common_begin", 0, true);
2357     Asm->EOL("Length of Common Information Entry");
2358
2359     EmitLabel("debug_frame_common_begin", 0);
2360     Asm->EmitInt32((int)DW_CIE_ID);
2361     Asm->EOL("CIE Identifier Tag");
2362     Asm->EmitInt8(DW_CIE_VERSION);
2363     Asm->EOL("CIE Version");
2364     Asm->EmitString("");
2365     Asm->EOL("CIE Augmentation");
2366     Asm->EmitULEB128Bytes(1);
2367     Asm->EOL("CIE Code Alignment Factor");
2368     Asm->EmitSLEB128Bytes(stackGrowth);
2369     Asm->EOL("CIE Data Alignment Factor");   
2370     Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2371     Asm->EOL("CIE RA Column");
2372     
2373     std::vector<MachineMove> Moves;
2374     RI->getInitialFrameState(Moves);
2375
2376     EmitFrameMoves(NULL, 0, Moves, false);
2377
2378     Asm->EmitAlignment(2, 0, 0, false);
2379     EmitLabel("debug_frame_common_end", 0);
2380     
2381     Asm->EOL();
2382   }
2383
2384   /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2385   /// section.
2386   void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2387     if (!TAI->doesDwarfRequireFrameSection())
2388       return;
2389        
2390     // Start the dwarf frame section.
2391     Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2392     
2393     EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2394                    "debug_frame_begin", DebugFrameInfo.Number, true);
2395     Asm->EOL("Length of Frame Information Entry");
2396     
2397     EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2398
2399     EmitSectionOffset("debug_frame_common", "section_debug_frame",
2400                       0, 0, true, false);
2401     Asm->EOL("FDE CIE offset");
2402
2403     EmitReference("func_begin", DebugFrameInfo.Number);
2404     Asm->EOL("FDE initial location");
2405     EmitDifference("func_end", DebugFrameInfo.Number,
2406                    "func_begin", DebugFrameInfo.Number);
2407     Asm->EOL("FDE address range");
2408     
2409     EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves, false);
2410     
2411     Asm->EmitAlignment(2, 0, 0, false);
2412     EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2413
2414     Asm->EOL();
2415   }
2416
2417   /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2418   ///
2419   void EmitDebugPubNames() {
2420     // Start the dwarf pubnames section.
2421     Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2422       
2423     CompileUnit *Unit = GetBaseCompileUnit(); 
2424  
2425     EmitDifference("pubnames_end", Unit->getID(),
2426                    "pubnames_begin", Unit->getID(), true);
2427     Asm->EOL("Length of Public Names Info");
2428     
2429     EmitLabel("pubnames_begin", Unit->getID());
2430     
2431     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2432
2433     EmitSectionOffset("info_begin", "section_info",
2434                       Unit->getID(), 0, true, false);
2435     Asm->EOL("Offset of Compilation Unit Info");
2436
2437     EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),true);
2438     Asm->EOL("Compilation Unit Length");
2439     
2440     std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2441     
2442     for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2443                                                 GE = Globals.end();
2444          GI != GE; ++GI) {
2445       const std::string &Name = GI->first;
2446       DIE * Entity = GI->second;
2447       
2448       Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2449       Asm->EmitString(Name); Asm->EOL("External Name");
2450     }
2451   
2452     Asm->EmitInt32(0); Asm->EOL("End Mark");
2453     EmitLabel("pubnames_end", Unit->getID());
2454   
2455     Asm->EOL();
2456   }
2457
2458   /// EmitDebugStr - Emit visible names into a debug str section.
2459   ///
2460   void EmitDebugStr() {
2461     // Check to see if it is worth the effort.
2462     if (!StringPool.empty()) {
2463       // Start the dwarf str section.
2464       Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2465       
2466       // For each of strings in the string pool.
2467       for (unsigned StringID = 1, N = StringPool.size();
2468            StringID <= N; ++StringID) {
2469         // Emit a label for reference from debug information entries.
2470         EmitLabel("string", StringID);
2471         // Emit the string itself.
2472         const std::string &String = StringPool[StringID];
2473         Asm->EmitString(String); Asm->EOL();
2474       }
2475     
2476       Asm->EOL();
2477     }
2478   }
2479
2480   /// EmitDebugLoc - Emit visible names into a debug loc section.
2481   ///
2482   void EmitDebugLoc() {
2483     // Start the dwarf loc section.
2484     Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2485     
2486     Asm->EOL();
2487   }
2488
2489   /// EmitDebugARanges - Emit visible names into a debug aranges section.
2490   ///
2491   void EmitDebugARanges() {
2492     // Start the dwarf aranges section.
2493     Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2494     
2495     // FIXME - Mock up
2496   #if 0
2497     CompileUnit *Unit = GetBaseCompileUnit(); 
2498       
2499     // Don't include size of length
2500     Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2501     
2502     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2503     
2504     EmitReference("info_begin", Unit->getID());
2505     Asm->EOL("Offset of Compilation Unit Info");
2506
2507     Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2508
2509     Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2510
2511     Asm->EmitInt16(0);  Asm->EOL("Pad (1)");
2512     Asm->EmitInt16(0);  Asm->EOL("Pad (2)");
2513
2514     // Range 1
2515     EmitReference("text_begin", 0); Asm->EOL("Address");
2516     EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2517
2518     Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2519     Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2520   #endif
2521     
2522     Asm->EOL();
2523   }
2524
2525   /// EmitDebugRanges - Emit visible names into a debug ranges section.
2526   ///
2527   void EmitDebugRanges() {
2528     // Start the dwarf ranges section.
2529     Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2530     
2531     Asm->EOL();
2532   }
2533
2534   /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2535   ///
2536   void EmitDebugMacInfo() {
2537     // Start the dwarf macinfo section.
2538     Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2539     
2540     Asm->EOL();
2541   }
2542
2543   /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
2544   /// header file.
2545   void ConstructCompileUnitDIEs() {
2546     const UniqueVector<CompileUnitDesc *> CUW = MMI->getCompileUnits();
2547     
2548     for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
2549       unsigned ID = MMI->RecordSource(CUW[i]);
2550       CompileUnit *Unit = NewCompileUnit(CUW[i], ID);
2551       CompileUnits.push_back(Unit);
2552     }
2553   }
2554
2555   /// ConstructGlobalDIEs - Create DIEs for each of the externally visible
2556   /// global variables.
2557   void ConstructGlobalDIEs() {
2558     std::vector<GlobalVariableDesc *> GlobalVariables =
2559         MMI->getAnchoredDescriptors<GlobalVariableDesc>(*M);
2560     
2561     for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
2562       GlobalVariableDesc *GVD = GlobalVariables[i];
2563       NewGlobalVariable(GVD);
2564     }
2565   }
2566
2567   /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
2568   /// subprograms.
2569   void ConstructSubprogramDIEs() {
2570     std::vector<SubprogramDesc *> Subprograms =
2571         MMI->getAnchoredDescriptors<SubprogramDesc>(*M);
2572     
2573     for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2574       SubprogramDesc *SPD = Subprograms[i];
2575       NewSubprogram(SPD);
2576     }
2577   }
2578
2579 public:
2580   //===--------------------------------------------------------------------===//
2581   // Main entry points.
2582   //
2583   DwarfDebug(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
2584   : Dwarf(OS, A, T, "dbg")
2585   , CompileUnits()
2586   , AbbreviationsSet(InitAbbreviationsSetSize)
2587   , Abbreviations()
2588   , ValuesSet(InitValuesSetSize)
2589   , Values()
2590   , StringPool()
2591   , DescToUnitMap()
2592   , SectionMap()
2593   , SectionSourceLines()
2594   , didInitial(false)
2595   , shouldEmit(false)
2596   {
2597   }
2598   virtual ~DwarfDebug() {
2599     for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i)
2600       delete CompileUnits[i];
2601     for (unsigned j = 0, M = Values.size(); j < M; ++j)
2602       delete Values[j];
2603   }
2604
2605   /// SetModuleInfo - Set machine module information when it's known that pass
2606   /// manager has created it.  Set by the target AsmPrinter.
2607   void SetModuleInfo(MachineModuleInfo *mmi) {
2608     // Make sure initial declarations are made.
2609     if (!MMI && mmi->hasDebugInfo()) {
2610       MMI = mmi;
2611       shouldEmit = true;
2612       
2613       // Create all the compile unit DIEs.
2614       ConstructCompileUnitDIEs();
2615       
2616       // Create DIEs for each of the externally visible global variables.
2617       ConstructGlobalDIEs();
2618
2619       // Create DIEs for each of the externally visible subprograms.
2620       ConstructSubprogramDIEs();
2621       
2622       // Prime section data.
2623       SectionMap.insert(TAI->getTextSection());
2624
2625       // Print out .file directives to specify files for .loc directives. These
2626       // are printed out early so that they precede any .loc directives.
2627       if (TAI->hasDotLocAndDotFile()) {
2628         const UniqueVector<SourceFileInfo> &SourceFiles = MMI->getSourceFiles();
2629         const UniqueVector<std::string> &Directories = MMI->getDirectories();
2630         for (unsigned i = 1, e = SourceFiles.size(); i <= e; ++i) {
2631           sys::Path FullPath(Directories[SourceFiles[i].getDirectoryID()]);
2632           bool AppendOk = FullPath.appendComponent(SourceFiles[i].getName());
2633           assert(AppendOk && "Could not append filename to directory!");
2634           Asm->EmitFile(i, FullPath.toString());
2635           Asm->EOL();
2636         }
2637       }
2638
2639       // Emit initial sections
2640       EmitInitial();
2641     }
2642   }
2643
2644   /// BeginModule - Emit all Dwarf sections that should come prior to the
2645   /// content.
2646   void BeginModule(Module *M) {
2647     this->M = M;
2648     
2649     if (!ShouldEmitDwarf()) return;
2650   }
2651
2652   /// EndModule - Emit all Dwarf sections that should come after the content.
2653   ///
2654   void EndModule() {
2655     if (!ShouldEmitDwarf()) return;
2656     
2657     // Standard sections final addresses.
2658     Asm->SwitchToTextSection(TAI->getTextSection());
2659     EmitLabel("text_end", 0);
2660     Asm->SwitchToDataSection(TAI->getDataSection());
2661     EmitLabel("data_end", 0);
2662     
2663     // End text sections.
2664     for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2665       Asm->SwitchToTextSection(SectionMap[i].c_str());
2666       EmitLabel("section_end", i);
2667     }
2668
2669     // Emit common frame information.
2670     EmitCommonDebugFrame();
2671
2672     // Emit function debug frame information
2673     for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2674            E = DebugFrames.end(); I != E; ++I)
2675       EmitFunctionDebugFrame(*I);
2676
2677     // Compute DIE offsets and sizes.
2678     SizeAndOffsets();
2679     
2680     // Emit all the DIEs into a debug info section
2681     EmitDebugInfo();
2682     
2683     // Corresponding abbreviations into a abbrev section.
2684     EmitAbbreviations();
2685     
2686     // Emit source line correspondence into a debug line section.
2687     EmitDebugLines();
2688     
2689     // Emit info into a debug pubnames section.
2690     EmitDebugPubNames();
2691     
2692     // Emit info into a debug str section.
2693     EmitDebugStr();
2694     
2695     // Emit info into a debug loc section.
2696     EmitDebugLoc();
2697     
2698     // Emit info into a debug aranges section.
2699     EmitDebugARanges();
2700     
2701     // Emit info into a debug ranges section.
2702     EmitDebugRanges();
2703     
2704     // Emit info into a debug macinfo section.
2705     EmitDebugMacInfo();
2706   }
2707
2708   /// BeginFunction - Gather pre-function debug information.  Assumes being 
2709   /// emitted immediately after the function entry point.
2710   void BeginFunction(MachineFunction *MF) {
2711     this->MF = MF;
2712     
2713     if (!ShouldEmitDwarf()) return;
2714
2715     // Begin accumulating function debug information.
2716     MMI->BeginFunction(MF);
2717     
2718     // Assumes in correct section after the entry point.
2719     EmitLabel("func_begin", ++SubprogramCount);
2720
2721     // Emit label for the implicitly defined dbg.stoppoint at the start of
2722     // the function.
2723     const SourceLineInfo &LineInfo = MMI->getSourceLines()[0];
2724     Asm->printLabel(LineInfo.getLabelID());
2725   }
2726   
2727   /// EndFunction - Gather and emit post-function debug information.
2728   ///
2729   void EndFunction() {
2730     if (!ShouldEmitDwarf()) return;
2731     
2732     // Define end label for subprogram.
2733     EmitLabel("func_end", SubprogramCount);
2734       
2735     // Get function line info.
2736     const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
2737
2738     if (!LineInfos.empty()) {
2739       // Get section line info.
2740       unsigned ID = SectionMap.insert(Asm->CurrentSection);
2741       if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2742       std::vector<SourceLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2743       // Append the function info to section info.
2744       SectionLineInfos.insert(SectionLineInfos.end(),
2745                               LineInfos.begin(), LineInfos.end());
2746     }
2747     
2748     // Construct scopes for subprogram.
2749     ConstructRootScope(MMI->getRootScope());
2750
2751     DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2752                                                  MMI->getFrameMoves()));
2753   }
2754 };
2755
2756 //===----------------------------------------------------------------------===//
2757 /// DwarfException - Emits Dwarf exception handling directives. 
2758 ///
2759 class DwarfException : public Dwarf  {
2760
2761 private:
2762   struct FunctionEHFrameInfo {
2763     std::string FnName;
2764     unsigned Number;
2765     unsigned PersonalityIndex;
2766     bool hasCalls;
2767     bool hasLandingPads;
2768     std::vector<MachineMove> Moves;
2769     const Function * function;
2770
2771     FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
2772                         bool hC, bool hL,
2773                         const std::vector<MachineMove> &M,
2774                         const Function *f):
2775       FnName(FN), Number(Num), PersonalityIndex(P),
2776       hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
2777   };
2778
2779   std::vector<FunctionEHFrameInfo> EHFrames;
2780     
2781   /// shouldEmit - Per-function flag to indicate if EH information should
2782   /// be emitted.
2783   bool shouldEmit;
2784
2785   /// shouldEmitModule - Per-module flag to indicate if EH information should
2786   /// be emitted.
2787   bool shouldEmitModule;
2788   
2789   /// EmitCommonEHFrame - Emit the common eh unwind frame.
2790   ///
2791   void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
2792     // Size and sign of stack growth.
2793     int stackGrowth =
2794         Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2795           TargetFrameInfo::StackGrowsUp ?
2796         TD->getPointerSize() : -TD->getPointerSize();
2797
2798     // Begin eh frame section.
2799     Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2800     O << "EH_frame" << Index << ":\n";
2801     EmitLabel("section_eh_frame", Index);
2802
2803     // Define base labels.
2804     EmitLabel("eh_frame_common", Index);
2805     
2806     // Define the eh frame length.
2807     EmitDifference("eh_frame_common_end", Index,
2808                    "eh_frame_common_begin", Index, true);
2809     Asm->EOL("Length of Common Information Entry");
2810
2811     // EH frame header.
2812     EmitLabel("eh_frame_common_begin", Index);
2813     Asm->EmitInt32((int)0);
2814     Asm->EOL("CIE Identifier Tag");
2815     Asm->EmitInt8(DW_CIE_VERSION);
2816     Asm->EOL("CIE Version");
2817     
2818     // The personality presence indicates that language specific information
2819     // will show up in the eh frame.
2820     Asm->EmitString(Personality ? "zPLR" : "zR");
2821     Asm->EOL("CIE Augmentation");
2822     
2823     // Round out reader.
2824     Asm->EmitULEB128Bytes(1);
2825     Asm->EOL("CIE Code Alignment Factor");
2826     Asm->EmitSLEB128Bytes(stackGrowth);
2827     Asm->EOL("CIE Data Alignment Factor");   
2828     Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
2829     Asm->EOL("CIE RA Column");
2830     
2831     // If there is a personality, we need to indicate the functions location.
2832     if (Personality) {
2833       Asm->EmitULEB128Bytes(7);
2834       Asm->EOL("Augmentation Size");
2835
2836       if (TAI->getNeedsIndirectEncoding())
2837         Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
2838       else
2839         Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
2840
2841       Asm->EOL("Personality (pcrel sdata4 indirect)");
2842       
2843       PrintRelDirective(TAI->getShortenEHDataOn64Bit());
2844       O << TAI->getPersonalityPrefix();
2845       Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
2846       O << TAI->getPersonalitySuffix();
2847       if (!TAI->getShortenEHDataOn64Bit()) {
2848         O << "-" << TAI->getPCSymbol();
2849       }
2850       Asm->EOL("Personality");
2851
2852       Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2853       Asm->EOL("LSDA Encoding (pcrel)");
2854       Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2855       Asm->EOL("FDE Encoding (pcrel)");
2856    } else {
2857       Asm->EmitULEB128Bytes(1);
2858       Asm->EOL("Augmentation Size");
2859       Asm->EmitULEB128Bytes(DW_EH_PE_pcrel);
2860       Asm->EOL("FDE Encoding (pcrel)");
2861     }
2862
2863     // Indicate locations of general callee saved registers in frame.
2864     std::vector<MachineMove> Moves;
2865     RI->getInitialFrameState(Moves);
2866     EmitFrameMoves(NULL, 0, Moves, true);
2867
2868     Asm->EmitAlignment(2, 0, 0, false);
2869     EmitLabel("eh_frame_common_end", Index);
2870     
2871     Asm->EOL();
2872   }
2873   
2874   /// EmitEHFrame - Emit function exception frame information.
2875   ///
2876   void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
2877     Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
2878
2879     Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
2880
2881     // Externally visible entry into the functions eh frame info.
2882     // If the corresponding function is static, this should not be
2883     // externally visible.
2884     if (linkage != Function::InternalLinkage) {
2885       if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
2886         O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
2887     }
2888
2889     // If corresponding function is weak definition, this should be too.
2890     if ((linkage == Function::WeakLinkage || 
2891          linkage == Function::LinkOnceLinkage) &&
2892         TAI->getWeakDefDirective())
2893       O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
2894
2895     // If there are no calls then you can't unwind.  This may mean we can
2896     // omit the EH Frame, but some environments do not handle weak absolute
2897     // symbols.
2898     if (!EHFrameInfo.hasCalls &&
2899         ((linkage != Function::WeakLinkage && 
2900           linkage != Function::LinkOnceLinkage) ||
2901          !TAI->getWeakDefDirective() ||
2902          TAI->getSupportsWeakOmittedEHFrame()))
2903     { 
2904       O << EHFrameInfo.FnName << " = 0\n";
2905       // This name has no connection to the function, so it might get 
2906       // dead-stripped when the function is not, erroneously.  Prohibit 
2907       // dead-stripping unconditionally.
2908       if (const char *UsedDirective = TAI->getUsedDirective())
2909         O << UsedDirective << EHFrameInfo.FnName << "\n\n";
2910     } else {
2911       O << EHFrameInfo.FnName << ":\n";
2912
2913       // EH frame header.
2914       EmitDifference("eh_frame_end", EHFrameInfo.Number,
2915                      "eh_frame_begin", EHFrameInfo.Number, true);
2916       Asm->EOL("Length of Frame Information Entry");
2917       
2918       EmitLabel("eh_frame_begin", EHFrameInfo.Number);
2919
2920       EmitSectionOffset("eh_frame_begin", "eh_frame_common",
2921                         EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
2922                         true, true, false);
2923       Asm->EOL("FDE CIE offset");
2924
2925       EmitReference("eh_func_begin", EHFrameInfo.Number, true);
2926       Asm->EOL("FDE initial location");
2927       EmitDifference("eh_func_end", EHFrameInfo.Number,
2928                      "eh_func_begin", EHFrameInfo.Number);
2929       Asm->EOL("FDE address range");
2930       
2931       // If there is a personality and landing pads then point to the language
2932       // specific data area in the exception table.
2933       if (EHFrameInfo.PersonalityIndex) {
2934         Asm->EmitULEB128Bytes(TAI->getShortenEHDataOn64Bit() ? 8 : 4);
2935         Asm->EOL("Augmentation size");
2936         
2937         if (EHFrameInfo.hasLandingPads) {
2938           EmitReference("exception", EHFrameInfo.Number, true);
2939         } else if (TD->getPointerSize() == 8) {
2940           Asm->EmitInt64((int)0);
2941         } else {
2942           Asm->EmitInt32((int)0);
2943         }
2944         Asm->EOL("Language Specific Data Area");
2945       } else {
2946         Asm->EmitULEB128Bytes(0);
2947         Asm->EOL("Augmentation size");
2948       }
2949       
2950       // Indicate locations of function specific  callee saved registers in
2951       // frame.
2952       EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves, true);
2953       
2954       Asm->EmitAlignment(2, 0, 0, false);
2955       EmitLabel("eh_frame_end", EHFrameInfo.Number);
2956     
2957       // If the function is marked used, this table should be also.  We cannot 
2958       // make the mark unconditional in this case, since retaining the table
2959       // also retains the function in this case, and there is code around 
2960       // that depends on unused functions (calling undefined externals) being
2961       // dead-stripped to link correctly.  Yes, there really is.
2962       if (MMI->getUsedFunctions().count(EHFrameInfo.function))
2963         if (const char *UsedDirective = TAI->getUsedDirective())
2964           O << UsedDirective << EHFrameInfo.FnName << "\n\n";
2965     }
2966   }
2967
2968   /// EmitExceptionTable - Emit landing pads and actions.
2969   ///
2970   /// The general organization of the table is complex, but the basic concepts
2971   /// are easy.  First there is a header which describes the location and
2972   /// organization of the three components that follow.
2973   ///  1. The landing pad site information describes the range of code covered
2974   ///     by the try.  In our case it's an accumulation of the ranges covered
2975   ///     by the invokes in the try.  There is also a reference to the landing
2976   ///     pad that handles the exception once processed.  Finally an index into
2977   ///     the actions table.
2978   ///  2. The action table, in our case, is composed of pairs of type ids
2979   ///     and next action offset.  Starting with the action index from the
2980   ///     landing pad site, each type Id is checked for a match to the current
2981   ///     exception.  If it matches then the exception and type id are passed
2982   ///     on to the landing pad.  Otherwise the next action is looked up.  This
2983   ///     chain is terminated with a next action of zero.  If no type id is
2984   ///     found the the frame is unwound and handling continues.
2985   ///  3. Type id table contains references to all the C++ typeinfo for all
2986   ///     catches in the function.  This tables is reversed indexed base 1.
2987
2988   /// SharedTypeIds - How many leading type ids two landing pads have in common.
2989   static unsigned SharedTypeIds(const LandingPadInfo *L,
2990                                 const LandingPadInfo *R) {
2991     const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
2992     unsigned LSize = LIds.size(), RSize = RIds.size();
2993     unsigned MinSize = LSize < RSize ? LSize : RSize;
2994     unsigned Count = 0;
2995
2996     for (; Count != MinSize; ++Count)
2997       if (LIds[Count] != RIds[Count])
2998         return Count;
2999
3000     return Count;
3001   }
3002
3003   /// PadLT - Order landing pads lexicographically by type id.
3004   static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
3005     const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3006     unsigned LSize = LIds.size(), RSize = RIds.size();
3007     unsigned MinSize = LSize < RSize ? LSize : RSize;
3008
3009     for (unsigned i = 0; i != MinSize; ++i)
3010       if (LIds[i] != RIds[i])
3011         return LIds[i] < RIds[i];
3012
3013     return LSize < RSize;
3014   }
3015
3016   struct KeyInfo {
3017     static inline unsigned getEmptyKey() { return -1U; }
3018     static inline unsigned getTombstoneKey() { return -2U; }
3019     static unsigned getHashValue(const unsigned &Key) { return Key; }
3020     static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
3021     static bool isPod() { return true; }
3022   };
3023
3024   /// ActionEntry - Structure describing an entry in the actions table.
3025   struct ActionEntry {
3026     int ValueForTypeID; // The value to write - may not be equal to the type id.
3027     int NextAction;
3028     struct ActionEntry *Previous;
3029   };
3030
3031   /// PadRange - Structure holding a try-range and the associated landing pad.
3032   struct PadRange {
3033     // The index of the landing pad.
3034     unsigned PadIndex;
3035     // The index of the begin and end labels in the landing pad's label lists.
3036     unsigned RangeIndex;
3037   };
3038
3039   typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
3040
3041   /// CallSiteEntry - Structure describing an entry in the call-site table.
3042   struct CallSiteEntry {
3043     // The 'try-range' is BeginLabel .. EndLabel.
3044     unsigned BeginLabel; // zero indicates the start of the function.
3045     unsigned EndLabel;   // zero indicates the end of the function.
3046     // The landing pad starts at PadLabel.
3047     unsigned PadLabel;   // zero indicates that there is no landing pad.
3048     unsigned Action;
3049   };
3050
3051   void EmitExceptionTable() {
3052     // Map all labels and get rid of any dead landing pads.
3053     MMI->TidyLandingPads();
3054
3055     const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
3056     const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
3057     const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
3058     if (PadInfos.empty()) return;
3059
3060     // Sort the landing pads in order of their type ids.  This is used to fold
3061     // duplicate actions.
3062     SmallVector<const LandingPadInfo *, 64> LandingPads;
3063     LandingPads.reserve(PadInfos.size());
3064     for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
3065       LandingPads.push_back(&PadInfos[i]);
3066     std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
3067
3068     // Negative type ids index into FilterIds, positive type ids index into
3069     // TypeInfos.  The value written for a positive type id is just the type
3070     // id itself.  For a negative type id, however, the value written is the
3071     // (negative) byte offset of the corresponding FilterIds entry.  The byte
3072     // offset is usually equal to the type id, because the FilterIds entries
3073     // are written using a variable width encoding which outputs one byte per
3074     // entry as long as the value written is not too large, but can differ.
3075     // This kind of complication does not occur for positive type ids because
3076     // type infos are output using a fixed width encoding.
3077     // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
3078     SmallVector<int, 16> FilterOffsets;
3079     FilterOffsets.reserve(FilterIds.size());
3080     int Offset = -1;
3081     for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3082         E = FilterIds.end(); I != E; ++I) {
3083       FilterOffsets.push_back(Offset);
3084       Offset -= Asm->SizeULEB128(*I);
3085     }
3086
3087     // Compute the actions table and gather the first action index for each
3088     // landing pad site.
3089     SmallVector<ActionEntry, 32> Actions;
3090     SmallVector<unsigned, 64> FirstActions;
3091     FirstActions.reserve(LandingPads.size());
3092
3093     int FirstAction = 0;
3094     unsigned SizeActions = 0;
3095     for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3096       const LandingPadInfo *LP = LandingPads[i];
3097       const std::vector<int> &TypeIds = LP->TypeIds;
3098       const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3099       unsigned SizeSiteActions = 0;
3100
3101       if (NumShared < TypeIds.size()) {
3102         unsigned SizeAction = 0;
3103         ActionEntry *PrevAction = 0;
3104
3105         if (NumShared) {
3106           const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3107           assert(Actions.size());
3108           PrevAction = &Actions.back();
3109           SizeAction = Asm->SizeSLEB128(PrevAction->NextAction) +
3110             Asm->SizeSLEB128(PrevAction->ValueForTypeID);
3111           for (unsigned j = NumShared; j != SizePrevIds; ++j) {
3112             SizeAction -= Asm->SizeSLEB128(PrevAction->ValueForTypeID);
3113             SizeAction += -PrevAction->NextAction;
3114             PrevAction = PrevAction->Previous;
3115           }
3116         }
3117
3118         // Compute the actions.
3119         for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
3120           int TypeID = TypeIds[I];
3121           assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
3122           int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
3123           unsigned SizeTypeID = Asm->SizeSLEB128(ValueForTypeID);
3124
3125           int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
3126           SizeAction = SizeTypeID + Asm->SizeSLEB128(NextAction);
3127           SizeSiteActions += SizeAction;
3128
3129           ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
3130           Actions.push_back(Action);
3131
3132           PrevAction = &Actions.back();
3133         }
3134
3135         // Record the first action of the landing pad site.
3136         FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
3137       } // else identical - re-use previous FirstAction
3138
3139       FirstActions.push_back(FirstAction);
3140
3141       // Compute this sites contribution to size.
3142       SizeActions += SizeSiteActions;
3143     }
3144
3145     // Compute the call-site table.  The entry for an invoke has a try-range
3146     // containing the call, a non-zero landing pad and an appropriate action.
3147     // The entry for an ordinary call has a try-range containing the call and
3148     // zero for the landing pad and the action.  Calls marked 'nounwind' have
3149     // no entry and must not be contained in the try-range of any entry - they
3150     // form gaps in the table.  Entries must be ordered by try-range address.
3151     SmallVector<CallSiteEntry, 64> CallSites;
3152
3153     RangeMapType PadMap;
3154     // Invokes and nounwind calls have entries in PadMap (due to being bracketed
3155     // by try-range labels when lowered).  Ordinary calls do not, so appropriate
3156     // try-ranges for them need be deduced.
3157     for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3158       const LandingPadInfo *LandingPad = LandingPads[i];
3159       for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
3160         unsigned BeginLabel = LandingPad->BeginLabels[j];
3161         assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
3162         PadRange P = { i, j };
3163         PadMap[BeginLabel] = P;
3164       }
3165     }
3166
3167     // The end label of the previous invoke or nounwind try-range.
3168     unsigned LastLabel = 0;
3169
3170     // Whether there is a potentially throwing instruction (currently this means
3171     // an ordinary call) between the end of the previous try-range and now.
3172     bool SawPotentiallyThrowing = false;
3173
3174     // Whether the last callsite entry was for an invoke.
3175     bool PreviousIsInvoke = false;
3176
3177     // Visit all instructions in order of address.
3178     for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
3179          I != E; ++I) {
3180       for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
3181            MI != E; ++MI) {
3182         if (MI->getOpcode() != TargetInstrInfo::LABEL) {
3183           SawPotentiallyThrowing |= MI->getDesc().isCall();
3184           continue;
3185         }
3186
3187         unsigned BeginLabel = MI->getOperand(0).getImm();
3188         assert(BeginLabel && "Invalid label!");
3189
3190         // End of the previous try-range?
3191         if (BeginLabel == LastLabel)
3192           SawPotentiallyThrowing = false;
3193
3194         // Beginning of a new try-range?
3195         RangeMapType::iterator L = PadMap.find(BeginLabel);
3196         if (L == PadMap.end())
3197           // Nope, it was just some random label.
3198           continue;
3199
3200         PadRange P = L->second;
3201         const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
3202
3203         assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
3204                "Inconsistent landing pad map!");
3205
3206         // If some instruction between the previous try-range and this one may
3207         // throw, create a call-site entry with no landing pad for the region
3208         // between the try-ranges.
3209         if (SawPotentiallyThrowing) {
3210           CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
3211           CallSites.push_back(Site);
3212           PreviousIsInvoke = false;
3213         }
3214
3215         LastLabel = LandingPad->EndLabels[P.RangeIndex];
3216         assert(BeginLabel && LastLabel && "Invalid landing pad!");
3217
3218         if (LandingPad->LandingPadLabel) {
3219           // This try-range is for an invoke.
3220           CallSiteEntry Site = {BeginLabel, LastLabel,
3221             LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
3222
3223           // Try to merge with the previous call-site.
3224           if (PreviousIsInvoke) {
3225             CallSiteEntry &Prev = CallSites[CallSites.size()-1];
3226             if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
3227               // Extend the range of the previous entry.
3228               Prev.EndLabel = Site.EndLabel;
3229               continue;
3230             }
3231           }
3232
3233           // Otherwise, create a new call-site.
3234           CallSites.push_back(Site);
3235           PreviousIsInvoke = true;
3236         } else {
3237           // Create a gap.
3238           PreviousIsInvoke = false;
3239         }
3240       }
3241     }
3242     // If some instruction between the previous try-range and the end of the
3243     // function may throw, create a call-site entry with no landing pad for the
3244     // region following the try-range.
3245     if (SawPotentiallyThrowing) {
3246       CallSiteEntry Site = {LastLabel, 0, 0, 0};
3247       CallSites.push_back(Site);
3248     }
3249
3250     // Final tallies.
3251     unsigned SizeSites = CallSites.size() * (sizeof(int32_t) + // Site start.
3252                                              sizeof(int32_t) + // Site length.
3253                                              sizeof(int32_t)); // Landing pad.
3254     for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
3255       SizeSites += Asm->SizeULEB128(CallSites[i].Action);
3256
3257     unsigned SizeTypes = TypeInfos.size() * TD->getPointerSize();
3258
3259     unsigned TypeOffset = sizeof(int8_t) + // Call site format
3260                           Asm->SizeULEB128(SizeSites) + // Call-site table length
3261                           SizeSites + SizeActions + SizeTypes;
3262
3263     unsigned TotalSize = sizeof(int8_t) + // LPStart format
3264                          sizeof(int8_t) + // TType format
3265                          Asm->SizeULEB128(TypeOffset) + // TType base offset
3266                          TypeOffset;
3267
3268     unsigned SizeAlign = (4 - TotalSize) & 3;
3269
3270     // Begin the exception table.
3271     Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
3272     O << "GCC_except_table" << SubprogramCount << ":\n";
3273     Asm->EmitAlignment(2, 0, 0, false);
3274     for (unsigned i = 0; i != SizeAlign; ++i) {
3275       Asm->EmitInt8(0);
3276       Asm->EOL("Padding");
3277     }
3278     EmitLabel("exception", SubprogramCount);
3279
3280     // Emit the header.
3281     Asm->EmitInt8(DW_EH_PE_omit);
3282     Asm->EOL("LPStart format (DW_EH_PE_omit)");
3283     Asm->EmitInt8(DW_EH_PE_absptr);
3284     Asm->EOL("TType format (DW_EH_PE_absptr)");
3285     Asm->EmitULEB128Bytes(TypeOffset);
3286     Asm->EOL("TType base offset");
3287     Asm->EmitInt8(DW_EH_PE_udata4);
3288     Asm->EOL("Call site format (DW_EH_PE_udata4)");
3289     Asm->EmitULEB128Bytes(SizeSites);
3290     Asm->EOL("Call-site table length");
3291
3292     // Emit the landing pad site information.
3293     for (unsigned i = 0; i < CallSites.size(); ++i) {
3294       CallSiteEntry &S = CallSites[i];
3295       const char *BeginTag;
3296       unsigned BeginNumber;
3297
3298       if (!S.BeginLabel) {
3299         BeginTag = "eh_func_begin";
3300         BeginNumber = SubprogramCount;
3301       } else {
3302         BeginTag = "label";
3303         BeginNumber = S.BeginLabel;
3304       }
3305
3306       EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
3307                         TAI->getShortenEHDataOn64Bit(), true);
3308       Asm->EOL("Region start");
3309
3310       if (!S.EndLabel) {
3311         EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
3312                        TAI->getShortenEHDataOn64Bit());
3313       } else {
3314         EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, 
3315                        TAI->getShortenEHDataOn64Bit());
3316       }
3317       Asm->EOL("Region length");
3318
3319       if (!S.PadLabel) {
3320         if (TD->getPointerSize() == sizeof(int32_t) || TAI->getShortenEHDataOn64Bit())
3321           Asm->EmitInt32(0);
3322         else
3323           Asm->EmitInt64(0);
3324       } else {
3325         EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
3326                           TAI->getShortenEHDataOn64Bit(), true);
3327       }
3328       Asm->EOL("Landing pad");
3329
3330       Asm->EmitULEB128Bytes(S.Action);
3331       Asm->EOL("Action");
3332     }
3333
3334     // Emit the actions.
3335     for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
3336       ActionEntry &Action = Actions[I];
3337
3338       Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
3339       Asm->EOL("TypeInfo index");
3340       Asm->EmitSLEB128Bytes(Action.NextAction);
3341       Asm->EOL("Next action");
3342     }
3343
3344     // Emit the type ids.
3345     for (unsigned M = TypeInfos.size(); M; --M) {
3346       GlobalVariable *GV = TypeInfos[M - 1];
3347
3348       PrintRelDirective();
3349
3350       if (GV)
3351         O << Asm->getGlobalLinkName(GV);
3352       else
3353         O << "0";
3354
3355       Asm->EOL("TypeInfo");
3356     }
3357
3358     // Emit the filter typeids.
3359     for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
3360       unsigned TypeID = FilterIds[j];
3361       Asm->EmitULEB128Bytes(TypeID);
3362       Asm->EOL("Filter TypeInfo index");
3363     }
3364
3365     Asm->EmitAlignment(2, 0, 0, false);
3366   }
3367
3368 public:
3369   //===--------------------------------------------------------------------===//
3370   // Main entry points.
3371   //
3372   DwarfException(std::ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3373   : Dwarf(OS, A, T, "eh")
3374   , shouldEmit(false)
3375   , shouldEmitModule(false)
3376   {}
3377   
3378   virtual ~DwarfException() {}
3379
3380   /// SetModuleInfo - Set machine module information when it's known that pass
3381   /// manager has created it.  Set by the target AsmPrinter.
3382   void SetModuleInfo(MachineModuleInfo *mmi) {
3383     MMI = mmi;
3384   }
3385
3386   /// BeginModule - Emit all exception information that should come prior to the
3387   /// content.
3388   void BeginModule(Module *M) {
3389     this->M = M;
3390   }
3391
3392   /// EndModule - Emit all exception information that should come after the
3393   /// content.
3394   void EndModule() {
3395     if (!shouldEmitModule) return;
3396
3397     const std::vector<Function *> Personalities = MMI->getPersonalities();
3398     for (unsigned i =0; i < Personalities.size(); ++i)
3399       EmitCommonEHFrame(Personalities[i], i);
3400
3401     for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
3402            E = EHFrames.end(); I != E; ++I)
3403       EmitEHFrame(*I);
3404   }
3405
3406   /// BeginFunction - Gather pre-function exception information.  Assumes being 
3407   /// emitted immediately after the function entry point.
3408   void BeginFunction(MachineFunction *MF) {
3409     this->MF = MF;
3410     
3411     shouldEmit = false;
3412     if ((ExceptionHandling || !MF->getFunction()->doesNotThrow()) &&
3413         TAI->doesSupportExceptionHandling()) {
3414       shouldEmit = true;
3415       // Assumes in correct section after the entry point.
3416       EmitLabel("eh_func_begin", ++SubprogramCount);
3417     }
3418     shouldEmitModule |= shouldEmit;
3419   }
3420
3421   /// EndFunction - Gather and emit post-function exception information.
3422   ///
3423   void EndFunction() {
3424     if (!shouldEmit) return;
3425
3426     EmitLabel("eh_func_end", SubprogramCount);
3427     EmitExceptionTable();
3428
3429     // Save EH frame information
3430     EHFrames.
3431       push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
3432                                     SubprogramCount,
3433                                     MMI->getPersonalityIndex(),
3434                                     MF->getFrameInfo()->hasCalls(),
3435                                     !MMI->getLandingPads().empty(),
3436                                     MMI->getFrameMoves(),
3437                                     MF->getFunction()));
3438   }
3439 };
3440
3441 } // End of namespace llvm
3442
3443 //===----------------------------------------------------------------------===//
3444
3445 /// Emit - Print the abbreviation using the specified Dwarf writer.
3446 ///
3447 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
3448   // Emit its Dwarf tag type.
3449   DD.getAsm()->EmitULEB128Bytes(Tag);
3450   DD.getAsm()->EOL(TagString(Tag));
3451   
3452   // Emit whether it has children DIEs.
3453   DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
3454   DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
3455   
3456   // For each attribute description.
3457   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3458     const DIEAbbrevData &AttrData = Data[i];
3459     
3460     // Emit attribute type.
3461     DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
3462     DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
3463     
3464     // Emit form type.
3465     DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
3466     DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
3467   }
3468
3469   // Mark end of abbreviation.
3470   DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
3471   DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
3472 }
3473
3474 #ifndef NDEBUG
3475 void DIEAbbrev::print(std::ostream &O) {
3476   O << "Abbreviation @"
3477     << std::hex << (intptr_t)this << std::dec
3478     << "  "
3479     << TagString(Tag)
3480     << " "
3481     << ChildrenString(ChildrenFlag)
3482     << "\n";
3483   
3484   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3485     O << "  "
3486       << AttributeString(Data[i].getAttribute())
3487       << "  "
3488       << FormEncodingString(Data[i].getForm())
3489       << "\n";
3490   }
3491 }
3492 void DIEAbbrev::dump() { print(cerr); }
3493 #endif
3494
3495 //===----------------------------------------------------------------------===//
3496
3497 #ifndef NDEBUG
3498 void DIEValue::dump() {
3499   print(cerr);
3500 }
3501 #endif
3502
3503 //===----------------------------------------------------------------------===//
3504
3505 /// EmitValue - Emit integer of appropriate size.
3506 ///
3507 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
3508   switch (Form) {
3509   case DW_FORM_flag:  // Fall thru
3510   case DW_FORM_ref1:  // Fall thru
3511   case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer);         break;
3512   case DW_FORM_ref2:  // Fall thru
3513   case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer);        break;
3514   case DW_FORM_ref4:  // Fall thru
3515   case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer);        break;
3516   case DW_FORM_ref8:  // Fall thru
3517   case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer);        break;
3518   case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
3519   case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
3520   default: assert(0 && "DIE Value form not supported yet");   break;
3521   }
3522 }
3523
3524 /// SizeOf - Determine size of integer value in bytes.
3525 ///
3526 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3527   switch (Form) {
3528   case DW_FORM_flag:  // Fall thru
3529   case DW_FORM_ref1:  // Fall thru
3530   case DW_FORM_data1: return sizeof(int8_t);
3531   case DW_FORM_ref2:  // Fall thru
3532   case DW_FORM_data2: return sizeof(int16_t);
3533   case DW_FORM_ref4:  // Fall thru
3534   case DW_FORM_data4: return sizeof(int32_t);
3535   case DW_FORM_ref8:  // Fall thru
3536   case DW_FORM_data8: return sizeof(int64_t);
3537   case DW_FORM_udata: return DD.getAsm()->SizeULEB128(Integer);
3538   case DW_FORM_sdata: return DD.getAsm()->SizeSLEB128(Integer);
3539   default: assert(0 && "DIE Value form not supported yet"); break;
3540   }
3541   return 0;
3542 }
3543
3544 //===----------------------------------------------------------------------===//
3545
3546 /// EmitValue - Emit string value.
3547 ///
3548 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
3549   DD.getAsm()->EmitString(String);
3550 }
3551
3552 //===----------------------------------------------------------------------===//
3553
3554 /// EmitValue - Emit label value.
3555 ///
3556 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
3557   bool IsSmall = Form == DW_FORM_data4;
3558   DD.EmitReference(Label, false, IsSmall);
3559 }
3560
3561 /// SizeOf - Determine size of label value in bytes.
3562 ///
3563 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3564   if (Form == DW_FORM_data4) return 4;
3565   return DD.getTargetData()->getPointerSize();
3566 }
3567
3568 //===----------------------------------------------------------------------===//
3569
3570 /// EmitValue - Emit label value.
3571 ///
3572 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
3573   bool IsSmall = Form == DW_FORM_data4;
3574   DD.EmitReference(Label, false, IsSmall);
3575 }
3576
3577 /// SizeOf - Determine size of label value in bytes.
3578 ///
3579 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3580   if (Form == DW_FORM_data4) return 4;
3581   return DD.getTargetData()->getPointerSize();
3582 }
3583     
3584 //===----------------------------------------------------------------------===//
3585
3586 /// EmitValue - Emit delta value.
3587 ///
3588 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
3589   bool IsSmall = Form == DW_FORM_data4;
3590   DD.EmitDifference(LabelHi, LabelLo, IsSmall);
3591 }
3592
3593 /// SizeOf - Determine size of delta value in bytes.
3594 ///
3595 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3596   if (Form == DW_FORM_data4) return 4;
3597   return DD.getTargetData()->getPointerSize();
3598 }
3599
3600 //===----------------------------------------------------------------------===//
3601
3602 /// EmitValue - Emit debug information entry offset.
3603 ///
3604 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
3605   DD.getAsm()->EmitInt32(Entry->getOffset());
3606 }
3607     
3608 //===----------------------------------------------------------------------===//
3609
3610 /// ComputeSize - calculate the size of the block.
3611 ///
3612 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
3613   if (!Size) {
3614     const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
3615     
3616     for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3617       Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
3618     }
3619   }
3620   return Size;
3621 }
3622
3623 /// EmitValue - Emit block data.
3624 ///
3625 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
3626   switch (Form) {
3627   case DW_FORM_block1: DD.getAsm()->EmitInt8(Size);         break;
3628   case DW_FORM_block2: DD.getAsm()->EmitInt16(Size);        break;
3629   case DW_FORM_block4: DD.getAsm()->EmitInt32(Size);        break;
3630   case DW_FORM_block:  DD.getAsm()->EmitULEB128Bytes(Size); break;
3631   default: assert(0 && "Improper form for block");          break;
3632   }
3633   
3634   const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
3635
3636   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3637     DD.getAsm()->EOL();
3638     Values[i]->EmitValue(DD, AbbrevData[i].getForm());
3639   }
3640 }
3641
3642 /// SizeOf - Determine size of block data in bytes.
3643 ///
3644 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3645   switch (Form) {
3646   case DW_FORM_block1: return Size + sizeof(int8_t);
3647   case DW_FORM_block2: return Size + sizeof(int16_t);
3648   case DW_FORM_block4: return Size + sizeof(int32_t);
3649   case DW_FORM_block: return Size + DD.getAsm()->SizeULEB128(Size);
3650   default: assert(0 && "Improper form for block"); break;
3651   }
3652   return 0;
3653 }
3654
3655 //===----------------------------------------------------------------------===//
3656 /// DIE Implementation
3657
3658 DIE::~DIE() {
3659   for (unsigned i = 0, N = Children.size(); i < N; ++i)
3660     delete Children[i];
3661 }
3662   
3663 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
3664 ///
3665 void DIE::AddSiblingOffset() {
3666   DIEInteger *DI = new DIEInteger(0);
3667   Values.insert(Values.begin(), DI);
3668   Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
3669 }
3670
3671 /// Profile - Used to gather unique data for the value folding set.
3672 ///
3673 void DIE::Profile(FoldingSetNodeID &ID) {
3674   Abbrev.Profile(ID);
3675   
3676   for (unsigned i = 0, N = Children.size(); i < N; ++i)
3677     ID.AddPointer(Children[i]);
3678
3679   for (unsigned j = 0, M = Values.size(); j < M; ++j)
3680     ID.AddPointer(Values[j]);
3681 }
3682
3683 #ifndef NDEBUG
3684 void DIE::print(std::ostream &O, unsigned IncIndent) {
3685   static unsigned IndentCount = 0;
3686   IndentCount += IncIndent;
3687   const std::string Indent(IndentCount, ' ');
3688   bool isBlock = Abbrev.getTag() == 0;
3689   
3690   if (!isBlock) {
3691     O << Indent
3692       << "Die: "
3693       << "0x" << std::hex << (intptr_t)this << std::dec
3694       << ", Offset: " << Offset
3695       << ", Size: " << Size
3696       << "\n"; 
3697     
3698     O << Indent
3699       << TagString(Abbrev.getTag())
3700       << " "
3701       << ChildrenString(Abbrev.getChildrenFlag());
3702   } else {
3703     O << "Size: " << Size;
3704   }
3705   O << "\n";
3706
3707   const std::vector<DIEAbbrevData> &Data = Abbrev.getData();
3708   
3709   IndentCount += 2;
3710   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3711     O << Indent;
3712     if (!isBlock) {
3713       O << AttributeString(Data[i].getAttribute());
3714     } else {
3715       O << "Blk[" << i << "]";
3716     }
3717     O <<  "  "
3718       << FormEncodingString(Data[i].getForm())
3719       << " ";
3720     Values[i]->print(O);
3721     O << "\n";
3722   }
3723   IndentCount -= 2;
3724
3725   for (unsigned j = 0, M = Children.size(); j < M; ++j) {
3726     Children[j]->print(O, 4);
3727   }
3728   
3729   if (!isBlock) O << "\n";
3730   IndentCount -= IncIndent;
3731 }
3732
3733 void DIE::dump() {
3734   print(cerr);
3735 }
3736 #endif
3737
3738 //===----------------------------------------------------------------------===//
3739 /// DwarfWriter Implementation
3740 ///
3741
3742 DwarfWriter::DwarfWriter(std::ostream &OS, AsmPrinter *A,
3743                          const TargetAsmInfo *T) {
3744   DE = new DwarfException(OS, A, T);
3745   DD = new DwarfDebug(OS, A, T);
3746 }
3747
3748 DwarfWriter::~DwarfWriter() {
3749   delete DE;
3750   delete DD;
3751 }
3752
3753 /// SetModuleInfo - Set machine module info when it's known that pass manager
3754 /// has created it.  Set by the target AsmPrinter.
3755 void DwarfWriter::SetModuleInfo(MachineModuleInfo *MMI) {
3756   DD->SetModuleInfo(MMI);
3757   DE->SetModuleInfo(MMI);
3758 }
3759
3760 /// BeginModule - Emit all Dwarf sections that should come prior to the
3761 /// content.
3762 void DwarfWriter::BeginModule(Module *M) {
3763   DE->BeginModule(M);
3764   DD->BeginModule(M);
3765 }
3766
3767 /// EndModule - Emit all Dwarf sections that should come after the content.
3768 ///
3769 void DwarfWriter::EndModule() {
3770   DE->EndModule();
3771   DD->EndModule();
3772 }
3773
3774 /// BeginFunction - Gather pre-function debug information.  Assumes being 
3775 /// emitted immediately after the function entry point.
3776 void DwarfWriter::BeginFunction(MachineFunction *MF) {
3777   DE->BeginFunction(MF);
3778   DD->BeginFunction(MF);
3779 }
3780
3781 /// EndFunction - Gather and emit post-function debug information.
3782 ///
3783 void DwarfWriter::EndFunction() {
3784   DD->EndFunction();
3785   DE->EndFunction();
3786   
3787   if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI()) {
3788     // Clear function debug information.
3789     MMI->EndFunction();
3790   }
3791 }