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