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