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