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