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