LinearScanner hotspot.
[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     unsigned StartID = Scope->getStartLabelID();
1759     unsigned EndID = Scope->getEndLabelID();
1760     
1761     // Throw out scope if block is discarded.
1762     if (StartID && !DebugInfo->isLabelValid(StartID)) continue;
1763     if (EndID && !DebugInfo->isLabelValid(EndID)) continue;
1764     
1765     DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
1766     
1767     // Add the scope bounds.
1768     if (StartID) {
1769       ScopeDie->AddLabel(DW_AT_low_pc, DW_FORM_addr,
1770                          DWLabel("loc", StartID));
1771     } else {
1772       ScopeDie->AddLabel(DW_AT_low_pc, DW_FORM_addr,
1773                          DWLabel("func_begin", SubprogramCount));
1774     }
1775     if (EndID) {
1776       ScopeDie->AddLabel(DW_AT_high_pc, DW_FORM_addr,
1777                          DWLabel("loc", EndID));
1778     } else {
1779       ScopeDie->AddLabel(DW_AT_high_pc, DW_FORM_addr,
1780                          DWLabel("func_end", SubprogramCount));
1781     }
1782                        
1783     // Add the scope contents.
1784     ConstructScope(Scope, ScopeDie, Unit);
1785     ParentDie->AddChild(ScopeDie);
1786   }
1787 }
1788
1789 /// ConstructRootScope - Construct the scope for the subprogram.
1790 ///
1791 void DwarfWriter::ConstructRootScope(DebugScope *RootScope) {
1792   // Exit if there is no root scope.
1793   if (!RootScope) return;
1794   
1795   // Get the subprogram debug information entry. 
1796   SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
1797   
1798   // Get the compile unit context.
1799   CompileUnitDesc *UnitDesc = static_cast<CompileUnitDesc *>(SPD->getContext());
1800   CompileUnit *Unit = FindCompileUnit(UnitDesc);
1801   
1802   // Get the subprogram die.
1803   DIE *SPDie = Unit->getDieMapSlotFor(SPD);
1804   assert(SPDie && "Missing subprogram descriptor");
1805   
1806   // Add the function bounds.
1807   SPDie->AddLabel(DW_AT_low_pc, DW_FORM_addr,
1808                   DWLabel("func_begin", SubprogramCount));
1809   SPDie->AddLabel(DW_AT_high_pc, DW_FORM_addr,
1810                   DWLabel("func_end", SubprogramCount));
1811   MachineLocation Location(RI->getFrameRegister(*MF));
1812   AddAddress(SPDie, DW_AT_frame_base, Location);
1813                   
1814   ConstructScope(RootScope, SPDie, Unit);
1815 }
1816
1817 /// EmitInitial - Emit initial Dwarf declarations.  This is necessary for cc
1818 /// tools to recognize the object file contains Dwarf information.
1819 ///
1820 void DwarfWriter::EmitInitial() {
1821   // Check to see if we already emitted intial headers.
1822   if (didInitial) return;
1823   didInitial = true;
1824   
1825   // Dwarf sections base addresses.
1826   Asm->SwitchToDataSection(TAI->getDwarfFrameSection(), 0);
1827   EmitLabel("section_frame", 0);
1828   Asm->SwitchToDataSection(TAI->getDwarfInfoSection(), 0);
1829   EmitLabel("section_info", 0);
1830   EmitLabel("info", 0);
1831   Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection(), 0);
1832   EmitLabel("section_abbrev", 0);
1833   EmitLabel("abbrev", 0);
1834   Asm->SwitchToDataSection(TAI->getDwarfARangesSection(), 0);
1835   EmitLabel("section_aranges", 0);
1836   Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection(), 0);
1837   EmitLabel("section_macinfo", 0);
1838   Asm->SwitchToDataSection(TAI->getDwarfLineSection(), 0);
1839   EmitLabel("section_line", 0);
1840   EmitLabel("line", 0);
1841   Asm->SwitchToDataSection(TAI->getDwarfLocSection(), 0);
1842   EmitLabel("section_loc", 0);
1843   Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection(), 0);
1844   EmitLabel("section_pubnames", 0);
1845   Asm->SwitchToDataSection(TAI->getDwarfStrSection(), 0);
1846   EmitLabel("section_str", 0);
1847   Asm->SwitchToDataSection(TAI->getDwarfRangesSection(), 0);
1848   EmitLabel("section_ranges", 0);
1849
1850   Asm->SwitchToTextSection(TAI->getTextSection(), 0);
1851   EmitLabel("text_begin", 0);
1852   Asm->SwitchToDataSection(TAI->getDataSection(), 0);
1853   EmitLabel("data_begin", 0);
1854
1855   // Emit common frame information.
1856   EmitInitialDebugFrame();
1857 }
1858
1859 /// EmitDIE - Recusively Emits a debug information entry.
1860 ///
1861 void DwarfWriter::EmitDIE(DIE *Die) const {
1862   // Get the abbreviation for this DIE.
1863   unsigned AbbrevID = Die->getAbbrevID();
1864   const DIEAbbrev &Abbrev = Abbreviations[AbbrevID];
1865   
1866   O << "\n";
1867
1868   // Emit the code (index) for the abbreviation.
1869   EmitULEB128Bytes(AbbrevID);
1870   EOL(std::string("Abbrev [" +
1871       utostr(AbbrevID) +
1872       "] 0x" + utohexstr(Die->getOffset()) +
1873       ":0x" + utohexstr(Die->getSize()) + " " +
1874       TagString(Abbrev.getTag())));
1875   
1876   const std::vector<DIEValue *> &Values = Die->getValues();
1877   const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1878   
1879   // Emit the DIE attribute values.
1880   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1881     unsigned Attr = AbbrevData[i].getAttribute();
1882     unsigned Form = AbbrevData[i].getForm();
1883     assert(Form && "Too many attributes for DIE (check abbreviation)");
1884     
1885     switch (Attr) {
1886     case DW_AT_sibling: {
1887       EmitInt32(Die->SiblingOffset());
1888       break;
1889     }
1890     default: {
1891       // Emit an attribute using the defined form.
1892       Values[i]->EmitValue(*this, Form);
1893       break;
1894     }
1895     }
1896     
1897     EOL(AttributeString(Attr));
1898   }
1899   
1900   // Emit the DIE children if any.
1901   if (Abbrev.getChildrenFlag() == DW_CHILDREN_yes) {
1902     const std::vector<DIE *> &Children = Die->getChildren();
1903     
1904     for (unsigned j = 0, M = Children.size(); j < M; ++j) {
1905       EmitDIE(Children[j]);
1906     }
1907     
1908     EmitInt8(0); EOL("End Of Children Mark");
1909   }
1910 }
1911
1912 /// SizeAndOffsetDie - Compute the size and offset of a DIE.
1913 ///
1914 unsigned DwarfWriter::SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
1915   // Get the children.
1916   const std::vector<DIE *> &Children = Die->getChildren();
1917   
1918   // If not last sibling and has children then add sibling offset attribute.
1919   if (!Last && !Children.empty()) Die->AddSiblingOffset();
1920
1921   // Record the abbreviation.
1922   Die->Complete(*this);
1923   
1924   // Get the abbreviation for this DIE.
1925   unsigned AbbrevID = Die->getAbbrevID();
1926   const DIEAbbrev &Abbrev = Abbreviations[AbbrevID];
1927
1928   // Set DIE offset
1929   Die->setOffset(Offset);
1930   
1931   // Start the size with the size of abbreviation code.
1932   Offset += SizeULEB128(AbbrevID);
1933   
1934   const std::vector<DIEValue *> &Values = Die->getValues();
1935   const std::vector<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1936
1937   // Emit the DIE attribute values.
1938   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1939     // Size attribute value.
1940     Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
1941   }
1942   
1943   // Emit the DIE children if any.
1944   if (!Children.empty()) {
1945     assert(Abbrev.getChildrenFlag() == DW_CHILDREN_yes &&
1946            "Children flag not set");
1947     
1948     for (unsigned j = 0, M = Children.size(); j < M; ++j) {
1949       Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
1950     }
1951     
1952     // End of children marker.
1953     Offset += sizeof(int8_t);
1954   }
1955
1956   Die->setSize(Offset - Die->getOffset());
1957   return Offset;
1958 }
1959
1960 /// SizeAndOffsets - Compute the size and offset of all the DIEs.
1961 ///
1962 void DwarfWriter::SizeAndOffsets() {
1963   
1964   // Process each compile unit.
1965   for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
1966     CompileUnit *Unit = CompileUnits[i];
1967     if (Unit->hasContent()) {
1968       // Compute size of compile unit header
1969       unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
1970                         sizeof(int16_t) + // DWARF version number
1971                         sizeof(int32_t) + // Offset Into Abbrev. Section
1972                         sizeof(int8_t);   // Pointer Size (in bytes)
1973       SizeAndOffsetDie(Unit->getDie(), Offset, (i + 1) == N);
1974     }
1975   }
1976 }
1977
1978 /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1979 /// frame.
1980 void DwarfWriter::EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
1981                                  std::vector<MachineMove *> &Moves) {
1982   for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
1983     MachineMove *Move = Moves[i];
1984     unsigned LabelID = Move->getLabelID();
1985     
1986     // Throw out move if the label is invalid.
1987     if (LabelID && !DebugInfo->isLabelValid(LabelID)) continue;
1988     
1989     const MachineLocation &Dst = Move->getDestination();
1990     const MachineLocation &Src = Move->getSource();
1991     
1992     // Advance row if new location.
1993     if (BaseLabel && LabelID && BaseLabelID != LabelID) {
1994       EmitInt8(DW_CFA_advance_loc4);
1995       EOL("DW_CFA_advance_loc4");
1996       EmitDifference("loc", LabelID, BaseLabel, BaseLabelID);
1997       EOL("");
1998       
1999       BaseLabelID = LabelID;
2000       BaseLabel = "loc";
2001     }
2002     
2003     int stackGrowth =
2004         Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2005           TargetFrameInfo::StackGrowsUp ?
2006             TAI->getAddressSize() : -TAI->getAddressSize();
2007
2008     // If advancing cfa.
2009     if (Dst.isRegister() && Dst.getRegister() == MachineLocation::VirtualFP) {
2010       if (!Src.isRegister()) {
2011         if (Src.getRegister() == MachineLocation::VirtualFP) {
2012           EmitInt8(DW_CFA_def_cfa_offset);
2013           EOL("DW_CFA_def_cfa_offset");
2014         } else {
2015           EmitInt8(DW_CFA_def_cfa);
2016           EOL("DW_CFA_def_cfa");
2017           
2018           EmitULEB128Bytes(RI->getDwarfRegNum(Src.getRegister()));
2019           EOL("Register");
2020         }
2021         
2022         int Offset = Src.getOffset() / stackGrowth;
2023         
2024         EmitULEB128Bytes(Offset);
2025         EOL("Offset");
2026       } else {
2027         assert(0 && "Machine move no supported yet.");
2028       }
2029     } else {
2030       unsigned Reg = RI->getDwarfRegNum(Src.getRegister());
2031       int Offset = Dst.getOffset() / stackGrowth;
2032       
2033       if (Offset < 0) {
2034         EmitInt8(DW_CFA_offset_extended_sf);
2035         EOL("DW_CFA_offset_extended_sf");
2036         EmitULEB128Bytes(Reg);
2037         EOL("Reg");
2038         EmitSLEB128Bytes(Offset);
2039         EOL("Offset");
2040       } else if (Reg < 64) {
2041         EmitInt8(DW_CFA_offset + Reg);
2042         EOL("DW_CFA_offset + Reg");
2043         EmitULEB128Bytes(Offset);
2044         EOL("Offset");
2045       } else {
2046         EmitInt8(DW_CFA_offset_extended);
2047         EOL("DW_CFA_offset_extended");
2048         EmitULEB128Bytes(Reg);
2049         EOL("Reg");
2050         EmitULEB128Bytes(Offset);
2051         EOL("Offset");
2052       }
2053     }
2054   }
2055 }
2056
2057 /// EmitDebugInfo - Emit the debug info section.
2058 ///
2059 void DwarfWriter::EmitDebugInfo() const {
2060   // Start debug info section.
2061   Asm->SwitchToDataSection(TAI->getDwarfInfoSection(), 0);
2062   
2063   // Process each compile unit.
2064   for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
2065     CompileUnit *Unit = CompileUnits[i];
2066     
2067     if (Unit->hasContent()) {
2068       DIE *Die = Unit->getDie();
2069       // Emit the compile units header.
2070       EmitLabel("info_begin", Unit->getID());
2071       // Emit size of content not including length itself
2072       unsigned ContentSize = Die->getSize() +
2073                              sizeof(int16_t) + // DWARF version number
2074                              sizeof(int32_t) + // Offset Into Abbrev. Section
2075                              sizeof(int8_t);   // Pointer Size (in bytes)
2076                              
2077       EmitInt32(ContentSize);  EOL("Length of Compilation Unit Info");
2078       EmitInt16(DWARF_VERSION); EOL("DWARF version number");
2079       EmitDifference("abbrev_begin", 0, "section_abbrev", 0);
2080       EOL("Offset Into Abbrev. Section");
2081       EmitInt8(TAI->getAddressSize()); EOL("Address Size (in bytes)");
2082     
2083       EmitDIE(Die);
2084       EmitLabel("info_end", Unit->getID());
2085     }
2086     
2087     O << "\n";
2088   }
2089 }
2090
2091 /// EmitAbbreviations - Emit the abbreviation section.
2092 ///
2093 void DwarfWriter::EmitAbbreviations() const {
2094   // Check to see if it is worth the effort.
2095   if (!Abbreviations.empty()) {
2096     // Start the debug abbrev section.
2097     Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection(), 0);
2098     
2099     EmitLabel("abbrev_begin", 0);
2100     
2101     // For each abbrevation.
2102     for (unsigned AbbrevID = 1, NAID = Abbreviations.size();
2103                   AbbrevID <= NAID; ++AbbrevID) {
2104       // Get abbreviation data
2105       const DIEAbbrev &Abbrev = Abbreviations[AbbrevID];
2106       
2107       // Emit the abbrevations code (base 1 index.)
2108       EmitULEB128Bytes(AbbrevID); EOL("Abbreviation Code");
2109       
2110       // Emit the abbreviations data.
2111       Abbrev.Emit(*this);
2112   
2113       O << "\n";
2114     }
2115     
2116     EmitLabel("abbrev_end", 0);
2117   
2118     O << "\n";
2119   }
2120 }
2121
2122 /// EmitDebugLines - Emit source line information.
2123 ///
2124 void DwarfWriter::EmitDebugLines() const {
2125   // Minimum line delta, thus ranging from -10..(255-10).
2126   const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2127   // Maximum line delta, thus ranging from -10..(255-10).
2128   const int MaxLineDelta = 255 + MinLineDelta;
2129
2130   // Start the dwarf line section.
2131   Asm->SwitchToDataSection(TAI->getDwarfLineSection(), 0);
2132   
2133   // Construct the section header.
2134   
2135   EmitDifference("line_end", 0, "line_begin", 0);
2136   EOL("Length of Source Line Info");
2137   EmitLabel("line_begin", 0);
2138   
2139   EmitInt16(DWARF_VERSION); EOL("DWARF version number");
2140   
2141   EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0);
2142   EOL("Prolog Length");
2143   EmitLabel("line_prolog_begin", 0);
2144   
2145   EmitInt8(1); EOL("Minimum Instruction Length");
2146
2147   EmitInt8(1); EOL("Default is_stmt_start flag");
2148
2149   EmitInt8(MinLineDelta);  EOL("Line Base Value (Special Opcodes)");
2150   
2151   EmitInt8(MaxLineDelta); EOL("Line Range Value (Special Opcodes)");
2152
2153   EmitInt8(-MinLineDelta); EOL("Special Opcode Base");
2154   
2155   // Line number standard opcode encodings argument count
2156   EmitInt8(0); EOL("DW_LNS_copy arg count");
2157   EmitInt8(1); EOL("DW_LNS_advance_pc arg count");
2158   EmitInt8(1); EOL("DW_LNS_advance_line arg count");
2159   EmitInt8(1); EOL("DW_LNS_set_file arg count");
2160   EmitInt8(1); EOL("DW_LNS_set_column arg count");
2161   EmitInt8(0); EOL("DW_LNS_negate_stmt arg count");
2162   EmitInt8(0); EOL("DW_LNS_set_basic_block arg count");
2163   EmitInt8(0); EOL("DW_LNS_const_add_pc arg count");
2164   EmitInt8(1); EOL("DW_LNS_fixed_advance_pc arg count");
2165
2166   const UniqueVector<std::string> &Directories = DebugInfo->getDirectories();
2167   const UniqueVector<SourceFileInfo> &SourceFiles = DebugInfo->getSourceFiles();
2168
2169   // Emit directories.
2170   for (unsigned DirectoryID = 1, NDID = Directories.size();
2171                 DirectoryID <= NDID; ++DirectoryID) {
2172     EmitString(Directories[DirectoryID]); EOL("Directory");
2173   }
2174   EmitInt8(0); EOL("End of directories");
2175   
2176   // Emit files.
2177   for (unsigned SourceID = 1, NSID = SourceFiles.size();
2178                SourceID <= NSID; ++SourceID) {
2179     const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2180     EmitString(SourceFile.getName()); EOL("Source");
2181     EmitULEB128Bytes(SourceFile.getDirectoryID());  EOL("Directory #");
2182     EmitULEB128Bytes(0);  EOL("Mod date");
2183     EmitULEB128Bytes(0);  EOL("File size");
2184   }
2185   EmitInt8(0); EOL("End of files");
2186   
2187   EmitLabel("line_prolog_end", 0);
2188   
2189   // A sequence for each text section.
2190   for (unsigned j = 0, M = SectionSourceLines.size(); j < M; ++j) {
2191     // Isolate current sections line info.
2192     const std::vector<SourceLineInfo> &LineInfos = SectionSourceLines[j];
2193     
2194     if (DwarfVerbose) {
2195       O << "\t"
2196         << TAI->getCommentString() << " "
2197         << "Section "
2198         << SectionMap[j + 1].c_str() << "\n";
2199     }
2200
2201     // Dwarf assumes we start with first line of first source file.
2202     unsigned Source = 1;
2203     unsigned Line = 1;
2204     
2205     // Construct rows of the address, source, line, column matrix.
2206     for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2207       const SourceLineInfo &LineInfo = LineInfos[i];
2208       unsigned LabelID = LineInfo.getLabelID();
2209       
2210       // Source line labels are validated at the MachineDebugInfo level.
2211       
2212       if (DwarfVerbose) {
2213         unsigned SourceID = LineInfo.getSourceID();
2214         const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2215         unsigned DirectoryID = SourceFile.getDirectoryID();
2216         O << "\t"
2217           << TAI->getCommentString() << " "
2218           << Directories[DirectoryID]
2219           << SourceFile.getName() << ":"
2220           << LineInfo.getLine() << "\n"; 
2221       }
2222
2223       // Define the line address.
2224       EmitInt8(0); EOL("Extended Op");
2225       EmitInt8(4 + 1); EOL("Op size");
2226       EmitInt8(DW_LNE_set_address); EOL("DW_LNE_set_address");
2227       EmitReference("loc",  LabelID); EOL("Location label");
2228       
2229       // If change of source, then switch to the new source.
2230       if (Source != LineInfo.getSourceID()) {
2231         Source = LineInfo.getSourceID();
2232         EmitInt8(DW_LNS_set_file); EOL("DW_LNS_set_file");
2233         EmitULEB128Bytes(Source); EOL("New Source");
2234       }
2235       
2236       // If change of line.
2237       if (Line != LineInfo.getLine()) {
2238         // Determine offset.
2239         int Offset = LineInfo.getLine() - Line;
2240         int Delta = Offset - MinLineDelta;
2241         
2242         // Update line.
2243         Line = LineInfo.getLine();
2244         
2245         // If delta is small enough and in range...
2246         if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2247           // ... then use fast opcode.
2248           EmitInt8(Delta - MinLineDelta); EOL("Line Delta");
2249         } else {
2250           // ... otherwise use long hand.
2251           EmitInt8(DW_LNS_advance_line); EOL("DW_LNS_advance_line");
2252           EmitSLEB128Bytes(Offset); EOL("Line Offset");
2253           EmitInt8(DW_LNS_copy); EOL("DW_LNS_copy");
2254         }
2255       } else {
2256         // Copy the previous row (different address or source)
2257         EmitInt8(DW_LNS_copy); EOL("DW_LNS_copy");
2258       }
2259     }
2260
2261     // Define last address of section.
2262     EmitInt8(0); EOL("Extended Op");
2263     EmitInt8(4 + 1); EOL("Op size");
2264     EmitInt8(DW_LNE_set_address); EOL("DW_LNE_set_address");
2265     EmitReference("section_end", j + 1); EOL("Section end label");
2266
2267     // Mark end of matrix.
2268     EmitInt8(0); EOL("DW_LNE_end_sequence");
2269     EmitULEB128Bytes(1);  O << "\n";
2270     EmitInt8(1); O << "\n";
2271   }
2272   
2273   EmitLabel("line_end", 0);
2274   
2275   O << "\n";
2276 }
2277   
2278 /// EmitInitialDebugFrame - Emit common frame info into a debug frame section.
2279 ///
2280 void DwarfWriter::EmitInitialDebugFrame() {
2281   int stackGrowth =
2282       Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2283         TargetFrameInfo::StackGrowsUp ?
2284       TAI->getAddressSize() : -TAI->getAddressSize();
2285
2286   // Start the dwarf frame section.
2287   Asm->SwitchToDataSection(TAI->getDwarfFrameSection(), 0);
2288
2289   EmitLabel("frame_common", 0);
2290   EmitDifference("frame_common_end", 0,
2291                  "frame_common_begin", 0);
2292   EOL("Length of Common Information Entry");
2293
2294   EmitLabel("frame_common_begin", 0);
2295   EmitInt32(DW_CIE_ID); EOL("CIE Identifier Tag");
2296   EmitInt8(DW_CIE_VERSION); EOL("CIE Version");
2297   EmitString("");  EOL("CIE Augmentation");
2298   EmitULEB128Bytes(1); EOL("CIE Code Alignment Factor");
2299   EmitSLEB128Bytes(stackGrowth); EOL("CIE Data Alignment Factor");   
2300   EmitInt8(RI->getDwarfRegNum(RI->getRARegister())); EOL("CIE RA Column");
2301   
2302   std::vector<MachineMove *> Moves;
2303   RI->getInitialFrameState(Moves);
2304   EmitFrameMoves(NULL, 0, Moves);
2305   for (unsigned i = 0, N = Moves.size(); i < N; ++i) delete Moves[i];
2306
2307   EmitAlign(2);
2308   EmitLabel("frame_common_end", 0);
2309   
2310   O << "\n";
2311 }
2312
2313 /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2314 /// section.
2315 void DwarfWriter::EmitFunctionDebugFrame() {
2316   // Start the dwarf frame section.
2317   Asm->SwitchToDataSection(TAI->getDwarfFrameSection(), 0);
2318   
2319   EmitDifference("frame_end", SubprogramCount,
2320                  "frame_begin", SubprogramCount);
2321   EOL("Length of Frame Information Entry");
2322   
2323   EmitLabel("frame_begin", SubprogramCount);
2324   
2325   EmitDifference("frame_common", 0, "section_frame", 0);
2326   EOL("FDE CIE offset");
2327
2328   EmitReference("func_begin", SubprogramCount); EOL("FDE initial location");
2329   EmitDifference("func_end", SubprogramCount,
2330                  "func_begin", SubprogramCount);
2331   EOL("FDE address range");
2332   
2333   std::vector<MachineMove *> &Moves = DebugInfo->getFrameMoves();
2334   
2335   EmitFrameMoves("func_begin", SubprogramCount, Moves);
2336   
2337   EmitAlign(2);
2338   EmitLabel("frame_end", SubprogramCount);
2339
2340   O << "\n";
2341 }
2342
2343 /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2344 ///
2345 void DwarfWriter::EmitDebugPubNames() {
2346   // Start the dwarf pubnames section.
2347   Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection(), 0);
2348     
2349   // Process each compile unit.
2350   for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
2351     CompileUnit *Unit = CompileUnits[i];
2352     
2353     if (Unit->hasContent()) {
2354       EmitDifference("pubnames_end", Unit->getID(),
2355                      "pubnames_begin", Unit->getID());
2356       EOL("Length of Public Names Info");
2357       
2358       EmitLabel("pubnames_begin", Unit->getID());
2359       
2360       EmitInt16(DWARF_VERSION); EOL("DWARF Version");
2361       
2362       EmitDifference("info_begin", Unit->getID(), "section_info", 0);
2363       EOL("Offset of Compilation Unit Info");
2364
2365       EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID());
2366       EOL("Compilation Unit Length");
2367       
2368       std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2369       
2370       for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2371                                                   GE = Globals.end();
2372            GI != GE; ++GI) {
2373         const std::string &Name = GI->first;
2374         DIE * Entity = GI->second;
2375         
2376         EmitInt32(Entity->getOffset()); EOL("DIE offset");
2377         EmitString(Name); EOL("External Name");
2378       }
2379     
2380       EmitInt32(0); EOL("End Mark");
2381       EmitLabel("pubnames_end", Unit->getID());
2382     
2383       O << "\n";
2384     }
2385   }
2386 }
2387
2388 /// EmitDebugStr - Emit visible names into a debug str section.
2389 ///
2390 void DwarfWriter::EmitDebugStr() {
2391   // Check to see if it is worth the effort.
2392   if (!StringPool.empty()) {
2393     // Start the dwarf str section.
2394     Asm->SwitchToDataSection(TAI->getDwarfStrSection(), 0);
2395     
2396     // For each of strings in the string pool.
2397     for (unsigned StringID = 1, N = StringPool.size();
2398          StringID <= N; ++StringID) {
2399       // Emit a label for reference from debug information entries.
2400       EmitLabel("string", StringID);
2401       // Emit the string itself.
2402       const std::string &String = StringPool[StringID];
2403       EmitString(String); O << "\n";
2404     }
2405   
2406     O << "\n";
2407   }
2408 }
2409
2410 /// EmitDebugLoc - Emit visible names into a debug loc section.
2411 ///
2412 void DwarfWriter::EmitDebugLoc() {
2413   // Start the dwarf loc section.
2414   Asm->SwitchToDataSection(TAI->getDwarfLocSection(), 0);
2415   
2416   O << "\n";
2417 }
2418
2419 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2420 ///
2421 void DwarfWriter::EmitDebugARanges() {
2422   // Start the dwarf aranges section.
2423   Asm->SwitchToDataSection(TAI->getDwarfARangesSection(), 0);
2424   
2425   // FIXME - Mock up
2426 #if 0
2427   // Process each compile unit.
2428   for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
2429     CompileUnit *Unit = CompileUnits[i];
2430     
2431     if (Unit->hasContent()) {
2432       // Don't include size of length
2433       EmitInt32(0x1c); EOL("Length of Address Ranges Info");
2434       
2435       EmitInt16(DWARF_VERSION); EOL("Dwarf Version");
2436       
2437       EmitReference("info_begin", Unit->getID());
2438       EOL("Offset of Compilation Unit Info");
2439
2440       EmitInt8(TAI->getAddressSize()); EOL("Size of Address");
2441
2442       EmitInt8(0); EOL("Size of Segment Descriptor");
2443
2444       EmitInt16(0);  EOL("Pad (1)");
2445       EmitInt16(0);  EOL("Pad (2)");
2446
2447       // Range 1
2448       EmitReference("text_begin", 0); EOL("Address");
2449       EmitDifference("text_end", 0, "text_begin", 0); EOL("Length");
2450
2451       EmitInt32(0); EOL("EOM (1)");
2452       EmitInt32(0); EOL("EOM (2)");
2453       
2454       O << "\n";
2455     }
2456   }
2457 #endif
2458 }
2459
2460 /// EmitDebugRanges - Emit visible names into a debug ranges section.
2461 ///
2462 void DwarfWriter::EmitDebugRanges() {
2463   // Start the dwarf ranges section.
2464   Asm->SwitchToDataSection(TAI->getDwarfRangesSection(), 0);
2465   
2466   O << "\n";
2467 }
2468
2469 /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2470 ///
2471 void DwarfWriter::EmitDebugMacInfo() {
2472   // Start the dwarf macinfo section.
2473   Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection(), 0);
2474   
2475   O << "\n";
2476 }
2477
2478 /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
2479 /// header file.
2480 void DwarfWriter::ConstructCompileUnitDIEs() {
2481   const UniqueVector<CompileUnitDesc *> CUW = DebugInfo->getCompileUnits();
2482   
2483   for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
2484     CompileUnit *Unit = NewCompileUnit(CUW[i], i);
2485     CompileUnits.push_back(Unit);
2486   }
2487 }
2488
2489 /// ConstructGlobalDIEs - Create DIEs for each of the externally visible global
2490 /// variables.
2491 void DwarfWriter::ConstructGlobalDIEs() {
2492   std::vector<GlobalVariableDesc *> GlobalVariables =
2493       DebugInfo->getAnchoredDescriptors<GlobalVariableDesc>(*M);
2494   
2495   for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
2496     GlobalVariableDesc *GVD = GlobalVariables[i];
2497     NewGlobalVariable(GVD);
2498   }
2499 }
2500
2501 /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
2502 /// subprograms.
2503 void DwarfWriter::ConstructSubprogramDIEs() {
2504   std::vector<SubprogramDesc *> Subprograms =
2505       DebugInfo->getAnchoredDescriptors<SubprogramDesc>(*M);
2506   
2507   for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2508     SubprogramDesc *SPD = Subprograms[i];
2509     NewSubprogram(SPD);
2510   }
2511 }
2512
2513 //===----------------------------------------------------------------------===//
2514 // Main entry points.
2515 //
2516   
2517 DwarfWriter::DwarfWriter(std::ostream &OS, AsmPrinter *A,
2518   const TargetAsmInfo *T)
2519 : O(OS)
2520 , Asm(A)
2521 , TAI(T)
2522 , TD(Asm->TM.getTargetData())
2523 , RI(Asm->TM.getRegisterInfo())
2524 , M(NULL)
2525 , MF(NULL)
2526 , DebugInfo(NULL)
2527 , didInitial(false)
2528 , shouldEmit(false)
2529 , SubprogramCount(0)
2530 , CompileUnits()
2531 , Abbreviations()
2532 , StringPool()
2533 , DescToUnitMap()
2534 , DescToDieMap()
2535 , SectionMap()
2536 , SectionSourceLines()
2537 {}
2538 DwarfWriter::~DwarfWriter() {
2539   for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i) {
2540     delete CompileUnits[i];
2541   }
2542 }
2543
2544 /// SetDebugInfo - Set DebugInfo when it's known that pass manager has
2545 /// created it.  Set by the target AsmPrinter.
2546 void DwarfWriter::SetDebugInfo(MachineDebugInfo *DI) {
2547   // Make sure initial declarations are made.
2548   if (!DebugInfo && DI->hasInfo()) {
2549     DebugInfo = DI;
2550     shouldEmit = true;
2551     
2552     // Emit initial sections
2553     EmitInitial();
2554   
2555     // Create all the compile unit DIEs.
2556     ConstructCompileUnitDIEs();
2557     
2558     // Create DIEs for each of the externally visible global variables.
2559     ConstructGlobalDIEs();
2560
2561     // Create DIEs for each of the externally visible subprograms.
2562     ConstructSubprogramDIEs();
2563     
2564     // Prime section data.
2565     SectionMap.insert(std::string("\t") + TAI->getTextSection());
2566   }
2567 }
2568
2569 /// BeginModule - Emit all Dwarf sections that should come prior to the content.
2570 ///
2571 void DwarfWriter::BeginModule(Module *M) {
2572   this->M = M;
2573   
2574   if (!ShouldEmitDwarf()) return;
2575   EOL("Dwarf Begin Module");
2576 }
2577
2578 /// EndModule - Emit all Dwarf sections that should come after the content.
2579 ///
2580 void DwarfWriter::EndModule() {
2581   if (!ShouldEmitDwarf()) return;
2582   EOL("Dwarf End Module");
2583   
2584   // Standard sections final addresses.
2585   Asm->SwitchToTextSection(TAI->getTextSection(), 0);
2586   EmitLabel("text_end", 0);
2587   Asm->SwitchToDataSection(TAI->getDataSection(), 0);
2588   EmitLabel("data_end", 0);
2589   
2590   // End text sections.
2591   for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2592     Asm->SwitchToTextSection(SectionMap[i].c_str(), 0);
2593     EmitLabel("section_end", i);
2594   }
2595   
2596   // Compute DIE offsets and sizes.
2597   SizeAndOffsets();
2598   
2599   // Emit all the DIEs into a debug info section
2600   EmitDebugInfo();
2601   
2602   // Corresponding abbreviations into a abbrev section.
2603   EmitAbbreviations();
2604   
2605   // Emit source line correspondence into a debug line section.
2606   EmitDebugLines();
2607   
2608   // Emit info into a debug pubnames section.
2609   EmitDebugPubNames();
2610   
2611   // Emit info into a debug str section.
2612   EmitDebugStr();
2613   
2614   // Emit info into a debug loc section.
2615   EmitDebugLoc();
2616   
2617   // Emit info into a debug aranges section.
2618   EmitDebugARanges();
2619   
2620   // Emit info into a debug ranges section.
2621   EmitDebugRanges();
2622   
2623   // Emit info into a debug macinfo section.
2624   EmitDebugMacInfo();
2625 }
2626
2627 /// BeginFunction - Gather pre-function debug information.  Assumes being 
2628 /// emitted immediately after the function entry point.
2629 void DwarfWriter::BeginFunction(MachineFunction *MF) {
2630   this->MF = MF;
2631   
2632   if (!ShouldEmitDwarf()) return;
2633   EOL("Dwarf Begin Function");
2634
2635   // Begin accumulating function debug information.
2636   DebugInfo->BeginFunction(MF);
2637   
2638   // Assumes in correct section after the entry point.
2639   EmitLabel("func_begin", ++SubprogramCount);
2640 }
2641
2642 /// EndFunction - Gather and emit post-function debug information.
2643 ///
2644 void DwarfWriter::EndFunction() {
2645   if (!ShouldEmitDwarf()) return;
2646   EOL("Dwarf End Function");
2647   
2648   // Define end label for subprogram.
2649   EmitLabel("func_end", SubprogramCount);
2650     
2651   // Get function line info.
2652   const std::vector<SourceLineInfo> &LineInfos = DebugInfo->getSourceLines();
2653
2654   if (!LineInfos.empty()) {
2655     // Get section line info.
2656     unsigned ID = SectionMap.insert(Asm->CurrentSection);
2657     if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2658     std::vector<SourceLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2659     // Append the function info to section info.
2660     SectionLineInfos.insert(SectionLineInfos.end(),
2661                             LineInfos.begin(), LineInfos.end());
2662   }
2663   
2664   // Construct scopes for subprogram.
2665   ConstructRootScope(DebugInfo->getRootScope());
2666   
2667   // Emit function frame information.
2668   EmitFunctionDebugFrame();
2669   
2670   // Reset the line numbers for the next function.
2671   // FIXME: move this to release memory of the debuginfo object.
2672   DebugInfo->ClearLineInfo();
2673
2674   // Clear function debug information.
2675   DebugInfo->EndFunction();
2676 }