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