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