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