Construct enumerator DIE using DebugInfo.
[oota-llvm.git] / lib / CodeGen / AsmPrinter / DwarfWriter.cpp
1 //===-- llvm/CodeGen/DwarfWriter.cpp - Dwarf Framework ----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing dwarf info into asm files.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/DwarfWriter.h"
15
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/FoldingSet.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/UniqueVector.h"
20 #include "llvm/Module.h"
21 #include "llvm/Type.h"
22 #include "llvm/CodeGen/AsmPrinter.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineLocation.h"
26 #include "llvm/Analysis/DebugInfo.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/Dwarf.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/DataTypes.h"
31 #include "llvm/Support/Mangler.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/System/Path.h"
34 #include "llvm/Target/TargetAsmInfo.h"
35 #include "llvm/Target/TargetRegisterInfo.h"
36 #include "llvm/Target/TargetData.h"
37 #include "llvm/Target/TargetFrameInfo.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include <ostream>
42 #include <string>
43 using namespace llvm;
44 using namespace llvm::dwarf;
45
46 namespace llvm {
47
48 //===----------------------------------------------------------------------===//
49
50 /// Configuration values for initial hash set sizes (log2).
51 ///
52 static const unsigned InitDiesSetSize          = 9; // 512
53 static const unsigned InitAbbreviationsSetSize = 9; // 512
54 static const unsigned InitValuesSetSize        = 9; // 512
55
56 //===----------------------------------------------------------------------===//
57 /// Forward declarations.
58 ///
59 class DIE;
60 class DIEValue;
61
62 //===----------------------------------------------------------------------===//
63 /// DWLabel - Labels are used to track locations in the assembler file.
64 /// Labels appear in the form @verbatim <prefix><Tag><Number> @endverbatim,
65 /// where the tag is a category of label (Ex. location) and number is a value
66 /// unique in that category.
67 class DWLabel {
68 public:
69   /// Tag - Label category tag. Should always be a staticly declared C string.
70   ///
71   const char *Tag;
72
73   /// Number - Value to make label unique.
74   ///
75   unsigned    Number;
76
77   DWLabel(const char *T, unsigned N) : Tag(T), Number(N) {}
78
79   void Profile(FoldingSetNodeID &ID) const {
80     ID.AddString(std::string(Tag));
81     ID.AddInteger(Number);
82   }
83
84 #ifndef NDEBUG
85   void print(std::ostream *O) const {
86     if (O) print(*O);
87   }
88   void print(std::ostream &O) const {
89     O << "." << Tag;
90     if (Number) O << Number;
91   }
92 #endif
93 };
94
95 //===----------------------------------------------------------------------===//
96 /// DIEAbbrevData - Dwarf abbreviation data, describes the one attribute of a
97 /// Dwarf abbreviation.
98 class DIEAbbrevData {
99 private:
100   /// Attribute - Dwarf attribute code.
101   ///
102   unsigned Attribute;
103
104   /// Form - Dwarf form code.
105   ///
106   unsigned Form;
107
108 public:
109   DIEAbbrevData(unsigned A, unsigned F)
110   : Attribute(A)
111   , Form(F)
112   {}
113
114   // Accessors.
115   unsigned getAttribute() const { return Attribute; }
116   unsigned getForm()      const { return Form; }
117
118   /// Profile - Used to gather unique data for the abbreviation folding set.
119   ///
120   void Profile(FoldingSetNodeID &ID)const  {
121     ID.AddInteger(Attribute);
122     ID.AddInteger(Form);
123   }
124 };
125
126 //===----------------------------------------------------------------------===//
127 /// DIEAbbrev - Dwarf abbreviation, describes the organization of a debug
128 /// information object.
129 class DIEAbbrev : public FoldingSetNode {
130 private:
131   /// Tag - Dwarf tag code.
132   ///
133   unsigned Tag;
134
135   /// Unique number for node.
136   ///
137   unsigned Number;
138
139   /// ChildrenFlag - Dwarf children flag.
140   ///
141   unsigned ChildrenFlag;
142
143   /// Data - Raw data bytes for abbreviation.
144   ///
145   SmallVector<DIEAbbrevData, 8> Data;
146
147 public:
148
149   DIEAbbrev(unsigned T, unsigned C)
150   : Tag(T)
151   , ChildrenFlag(C)
152   , Data()
153   {}
154   ~DIEAbbrev() {}
155
156   // Accessors.
157   unsigned getTag()                           const { return Tag; }
158   unsigned getNumber()                        const { return Number; }
159   unsigned getChildrenFlag()                  const { return ChildrenFlag; }
160   const SmallVector<DIEAbbrevData, 8> &getData() const { return Data; }
161   void setTag(unsigned T)                           { Tag = T; }
162   void setChildrenFlag(unsigned CF)                 { ChildrenFlag = CF; }
163   void setNumber(unsigned N)                        { Number = N; }
164
165   /// AddAttribute - Adds another set of attribute information to the
166   /// abbreviation.
167   void AddAttribute(unsigned Attribute, unsigned Form) {
168     Data.push_back(DIEAbbrevData(Attribute, Form));
169   }
170
171   /// AddFirstAttribute - Adds a set of attribute information to the front
172   /// of the abbreviation.
173   void AddFirstAttribute(unsigned Attribute, unsigned Form) {
174     Data.insert(Data.begin(), DIEAbbrevData(Attribute, Form));
175   }
176
177   /// Profile - Used to gather unique data for the abbreviation folding set.
178   ///
179   void Profile(FoldingSetNodeID &ID) {
180     ID.AddInteger(Tag);
181     ID.AddInteger(ChildrenFlag);
182
183     // For each attribute description.
184     for (unsigned i = 0, N = Data.size(); i < N; ++i)
185       Data[i].Profile(ID);
186   }
187
188   /// Emit - Print the abbreviation using the specified Dwarf writer.
189   ///
190   void Emit(const DwarfDebug &DD) const;
191
192 #ifndef NDEBUG
193   void print(std::ostream *O) {
194     if (O) print(*O);
195   }
196   void print(std::ostream &O);
197   void dump();
198 #endif
199 };
200
201 //===----------------------------------------------------------------------===//
202 /// DIE - A structured debug information entry.  Has an abbreviation which
203 /// describes it's organization.
204 class DIE : public FoldingSetNode {
205 protected:
206   /// Abbrev - Buffer for constructing abbreviation.
207   ///
208   DIEAbbrev Abbrev;
209
210   /// Offset - Offset in debug info section.
211   ///
212   unsigned Offset;
213
214   /// Size - Size of instance + children.
215   ///
216   unsigned Size;
217
218   /// Children DIEs.
219   ///
220   std::vector<DIE *> Children;
221
222   /// Attributes values.
223   ///
224   SmallVector<DIEValue*, 32> Values;
225
226 public:
227   explicit DIE(unsigned Tag)
228   : Abbrev(Tag, DW_CHILDREN_no)
229   , Offset(0)
230   , Size(0)
231   , Children()
232   , Values()
233   {}
234   virtual ~DIE();
235
236   // Accessors.
237   DIEAbbrev &getAbbrev()                           { return Abbrev; }
238   unsigned   getAbbrevNumber()               const {
239     return Abbrev.getNumber();
240   }
241   unsigned getTag()                          const { return Abbrev.getTag(); }
242   unsigned getOffset()                       const { return Offset; }
243   unsigned getSize()                         const { return Size; }
244   const std::vector<DIE *> &getChildren()    const { return Children; }
245   SmallVector<DIEValue*, 32> &getValues()       { return Values; }
246   void setTag(unsigned Tag)                  { Abbrev.setTag(Tag); }
247   void setOffset(unsigned O)                 { Offset = O; }
248   void setSize(unsigned S)                   { Size = S; }
249
250   /// AddValue - Add a value and attributes to a DIE.
251   ///
252   void AddValue(unsigned Attribute, unsigned Form, DIEValue *Value) {
253     Abbrev.AddAttribute(Attribute, Form);
254     Values.push_back(Value);
255   }
256
257   /// SiblingOffset - Return the offset of the debug information entry's
258   /// sibling.
259   unsigned SiblingOffset() const { return Offset + Size; }
260
261   /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
262   ///
263   void AddSiblingOffset();
264
265   /// AddChild - Add a child to the DIE.
266   ///
267   void AddChild(DIE *Child) {
268     Abbrev.setChildrenFlag(DW_CHILDREN_yes);
269     Children.push_back(Child);
270   }
271
272   /// Detach - Detaches objects connected to it after copying.
273   ///
274   void Detach() {
275     Children.clear();
276   }
277
278   /// Profile - Used to gather unique data for the value folding set.
279   ///
280   void Profile(FoldingSetNodeID &ID) ;
281
282 #ifndef NDEBUG
283   void print(std::ostream *O, unsigned IncIndent = 0) {
284     if (O) print(*O, IncIndent);
285   }
286   void print(std::ostream &O, unsigned IncIndent = 0);
287   void dump();
288 #endif
289 };
290
291 //===----------------------------------------------------------------------===//
292 /// DIEValue - A debug information entry value.
293 ///
294 class DIEValue : public FoldingSetNode {
295 public:
296   enum {
297     isInteger,
298     isString,
299     isLabel,
300     isAsIsLabel,
301     isSectionOffset,
302     isDelta,
303     isEntry,
304     isBlock
305   };
306
307   /// Type - Type of data stored in the value.
308   ///
309   unsigned Type;
310
311   explicit DIEValue(unsigned T)
312   : Type(T)
313   {}
314   virtual ~DIEValue() {}
315
316   // Accessors
317   unsigned getType()  const { return Type; }
318
319   // Implement isa/cast/dyncast.
320   static bool classof(const DIEValue *) { return true; }
321
322   /// EmitValue - Emit value via the Dwarf writer.
323   ///
324   virtual void EmitValue(DwarfDebug &DD, unsigned Form) = 0;
325
326   /// SizeOf - Return the size of a value in bytes.
327   ///
328   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const = 0;
329
330   /// Profile - Used to gather unique data for the value folding set.
331   ///
332   virtual void Profile(FoldingSetNodeID &ID) = 0;
333
334 #ifndef NDEBUG
335   void print(std::ostream *O) {
336     if (O) print(*O);
337   }
338   virtual void print(std::ostream &O) = 0;
339   void dump();
340 #endif
341 };
342
343 //===----------------------------------------------------------------------===//
344 /// DWInteger - An integer value DIE.
345 ///
346 class DIEInteger : public DIEValue {
347 private:
348   uint64_t Integer;
349
350 public:
351   explicit DIEInteger(uint64_t I) : DIEValue(isInteger), Integer(I) {}
352
353   // Implement isa/cast/dyncast.
354   static bool classof(const DIEInteger *) { return true; }
355   static bool classof(const DIEValue *I)  { return I->Type == isInteger; }
356
357   /// BestForm - Choose the best form for integer.
358   ///
359   static unsigned BestForm(bool IsSigned, uint64_t Integer) {
360     if (IsSigned) {
361       if ((char)Integer == (signed)Integer)   return DW_FORM_data1;
362       if ((short)Integer == (signed)Integer)  return DW_FORM_data2;
363       if ((int)Integer == (signed)Integer)    return DW_FORM_data4;
364     } else {
365       if ((unsigned char)Integer == Integer)  return DW_FORM_data1;
366       if ((unsigned short)Integer == Integer) return DW_FORM_data2;
367       if ((unsigned int)Integer == Integer)   return DW_FORM_data4;
368     }
369     return DW_FORM_data8;
370   }
371
372   /// EmitValue - Emit integer of appropriate size.
373   ///
374   virtual void EmitValue(DwarfDebug &DD, unsigned Form);
375
376   /// SizeOf - Determine size of integer value in bytes.
377   ///
378   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
379
380   /// Profile - Used to gather unique data for the value folding set.
381   ///
382   static void Profile(FoldingSetNodeID &ID, unsigned Integer) {
383     ID.AddInteger(isInteger);
384     ID.AddInteger(Integer);
385   }
386   virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Integer); }
387
388 #ifndef NDEBUG
389   virtual void print(std::ostream &O) {
390     O << "Int: " << (int64_t)Integer
391       << "  0x" << std::hex << Integer << std::dec;
392   }
393 #endif
394 };
395
396 //===----------------------------------------------------------------------===//
397 /// DIEString - A string value DIE.
398 ///
399 class DIEString : public DIEValue {
400 public:
401   const std::string String;
402
403   explicit DIEString(const std::string &S) : DIEValue(isString), String(S) {}
404
405   // Implement isa/cast/dyncast.
406   static bool classof(const DIEString *) { return true; }
407   static bool classof(const DIEValue *S) { return S->Type == isString; }
408
409   /// EmitValue - Emit string value.
410   ///
411   virtual void EmitValue(DwarfDebug &DD, unsigned Form);
412
413   /// SizeOf - Determine size of string value in bytes.
414   ///
415   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
416     return String.size() + sizeof(char); // sizeof('\0');
417   }
418
419   /// Profile - Used to gather unique data for the value folding set.
420   ///
421   static void Profile(FoldingSetNodeID &ID, const std::string &String) {
422     ID.AddInteger(isString);
423     ID.AddString(String);
424   }
425   virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, String); }
426
427 #ifndef NDEBUG
428   virtual void print(std::ostream &O) {
429     O << "Str: \"" << String << "\"";
430   }
431 #endif
432 };
433
434 //===----------------------------------------------------------------------===//
435 /// DIEDwarfLabel - A Dwarf internal label expression DIE.
436 //
437 class DIEDwarfLabel : public DIEValue {
438 public:
439
440   const DWLabel Label;
441
442   explicit DIEDwarfLabel(const DWLabel &L) : DIEValue(isLabel), Label(L) {}
443
444   // Implement isa/cast/dyncast.
445   static bool classof(const DIEDwarfLabel *)  { return true; }
446   static bool classof(const DIEValue *L) { return L->Type == isLabel; }
447
448   /// EmitValue - Emit label value.
449   ///
450   virtual void EmitValue(DwarfDebug &DD, unsigned Form);
451
452   /// SizeOf - Determine size of label value in bytes.
453   ///
454   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
455
456   /// Profile - Used to gather unique data for the value folding set.
457   ///
458   static void Profile(FoldingSetNodeID &ID, const DWLabel &Label) {
459     ID.AddInteger(isLabel);
460     Label.Profile(ID);
461   }
462   virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
463
464 #ifndef NDEBUG
465   virtual void print(std::ostream &O) {
466     O << "Lbl: ";
467     Label.print(O);
468   }
469 #endif
470 };
471
472
473 //===----------------------------------------------------------------------===//
474 /// DIEObjectLabel - A label to an object in code or data.
475 //
476 class DIEObjectLabel : public DIEValue {
477 public:
478   const std::string Label;
479
480   explicit DIEObjectLabel(const std::string &L)
481   : DIEValue(isAsIsLabel), Label(L) {}
482
483   // Implement isa/cast/dyncast.
484   static bool classof(const DIEObjectLabel *) { return true; }
485   static bool classof(const DIEValue *L)    { return L->Type == isAsIsLabel; }
486
487   /// EmitValue - Emit label value.
488   ///
489   virtual void EmitValue(DwarfDebug &DD, unsigned Form);
490
491   /// SizeOf - Determine size of label value in bytes.
492   ///
493   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
494
495   /// Profile - Used to gather unique data for the value folding set.
496   ///
497   static void Profile(FoldingSetNodeID &ID, const std::string &Label) {
498     ID.AddInteger(isAsIsLabel);
499     ID.AddString(Label);
500   }
501   virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label); }
502
503 #ifndef NDEBUG
504   virtual void print(std::ostream &O) {
505     O << "Obj: " << Label;
506   }
507 #endif
508 };
509
510 //===----------------------------------------------------------------------===//
511 /// DIESectionOffset - A section offset DIE.
512 //
513 class DIESectionOffset : public DIEValue {
514 public:
515   const DWLabel Label;
516   const DWLabel Section;
517   bool IsEH : 1;
518   bool UseSet : 1;
519
520   DIESectionOffset(const DWLabel &Lab, const DWLabel &Sec,
521                    bool isEH = false, bool useSet = true)
522   : DIEValue(isSectionOffset), Label(Lab), Section(Sec),
523                                IsEH(isEH), UseSet(useSet) {}
524
525   // Implement isa/cast/dyncast.
526   static bool classof(const DIESectionOffset *)  { return true; }
527   static bool classof(const DIEValue *D) { return D->Type == isSectionOffset; }
528
529   /// EmitValue - Emit section offset.
530   ///
531   virtual void EmitValue(DwarfDebug &DD, unsigned Form);
532
533   /// SizeOf - Determine size of section offset value in bytes.
534   ///
535   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
536
537   /// Profile - Used to gather unique data for the value folding set.
538   ///
539   static void Profile(FoldingSetNodeID &ID, const DWLabel &Label,
540                                             const DWLabel &Section) {
541     ID.AddInteger(isSectionOffset);
542     Label.Profile(ID);
543     Section.Profile(ID);
544     // IsEH and UseSet are specific to the Label/Section that we will emit
545     // the offset for; so Label/Section are enough for uniqueness.
546   }
547   virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, Label, Section); }
548
549 #ifndef NDEBUG
550   virtual void print(std::ostream &O) {
551     O << "Off: ";
552     Label.print(O);
553     O << "-";
554     Section.print(O);
555     O << "-" << IsEH << "-" << UseSet;
556   }
557 #endif
558 };
559
560 //===----------------------------------------------------------------------===//
561 /// DIEDelta - A simple label difference DIE.
562 ///
563 class DIEDelta : public DIEValue {
564 public:
565   const DWLabel LabelHi;
566   const DWLabel LabelLo;
567
568   DIEDelta(const DWLabel &Hi, const DWLabel &Lo)
569   : DIEValue(isDelta), LabelHi(Hi), LabelLo(Lo) {}
570
571   // Implement isa/cast/dyncast.
572   static bool classof(const DIEDelta *)  { return true; }
573   static bool classof(const DIEValue *D) { return D->Type == isDelta; }
574
575   /// EmitValue - Emit delta value.
576   ///
577   virtual void EmitValue(DwarfDebug &DD, unsigned Form);
578
579   /// SizeOf - Determine size of delta value in bytes.
580   ///
581   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
582
583   /// Profile - Used to gather unique data for the value folding set.
584   ///
585   static void Profile(FoldingSetNodeID &ID, const DWLabel &LabelHi,
586                                             const DWLabel &LabelLo) {
587     ID.AddInteger(isDelta);
588     LabelHi.Profile(ID);
589     LabelLo.Profile(ID);
590   }
591   virtual void Profile(FoldingSetNodeID &ID) { Profile(ID, LabelHi, LabelLo); }
592
593 #ifndef NDEBUG
594   virtual void print(std::ostream &O) {
595     O << "Del: ";
596     LabelHi.print(O);
597     O << "-";
598     LabelLo.print(O);
599   }
600 #endif
601 };
602
603 //===----------------------------------------------------------------------===//
604 /// DIEntry - A pointer to another debug information entry.  An instance of this
605 /// class can also be used as a proxy for a debug information entry not yet
606 /// defined (ie. types.)
607 class DIEntry : public DIEValue {
608 public:
609   DIE *Entry;
610
611   explicit DIEntry(DIE *E) : DIEValue(isEntry), Entry(E) {}
612
613   // Implement isa/cast/dyncast.
614   static bool classof(const DIEntry *)   { return true; }
615   static bool classof(const DIEValue *E) { return E->Type == isEntry; }
616
617   /// EmitValue - Emit debug information entry offset.
618   ///
619   virtual void EmitValue(DwarfDebug &DD, unsigned Form);
620
621   /// SizeOf - Determine size of debug information entry in bytes.
622   ///
623   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const {
624     return sizeof(int32_t);
625   }
626
627   /// Profile - Used to gather unique data for the value folding set.
628   ///
629   static void Profile(FoldingSetNodeID &ID, DIE *Entry) {
630     ID.AddInteger(isEntry);
631     ID.AddPointer(Entry);
632   }
633   virtual void Profile(FoldingSetNodeID &ID) {
634     ID.AddInteger(isEntry);
635
636     if (Entry) {
637       ID.AddPointer(Entry);
638     } else {
639       ID.AddPointer(this);
640     }
641   }
642
643 #ifndef NDEBUG
644   virtual void print(std::ostream &O) {
645     O << "Die: 0x" << std::hex << (intptr_t)Entry << std::dec;
646   }
647 #endif
648 };
649
650 //===----------------------------------------------------------------------===//
651 /// DIEBlock - A block of values.  Primarily used for location expressions.
652 //
653 class DIEBlock : public DIEValue, public DIE {
654 public:
655   unsigned Size;                        // Size in bytes excluding size header.
656
657   DIEBlock()
658   : DIEValue(isBlock)
659   , DIE(0)
660   , Size(0)
661   {}
662   ~DIEBlock()  {
663   }
664
665   // Implement isa/cast/dyncast.
666   static bool classof(const DIEBlock *)  { return true; }
667   static bool classof(const DIEValue *E) { return E->Type == isBlock; }
668
669   /// ComputeSize - calculate the size of the block.
670   ///
671   unsigned ComputeSize(DwarfDebug &DD);
672
673   /// BestForm - Choose the best form for data.
674   ///
675   unsigned BestForm() const {
676     if ((unsigned char)Size == Size)  return DW_FORM_block1;
677     if ((unsigned short)Size == Size) return DW_FORM_block2;
678     if ((unsigned int)Size == Size)   return DW_FORM_block4;
679     return DW_FORM_block;
680   }
681
682   /// EmitValue - Emit block data.
683   ///
684   virtual void EmitValue(DwarfDebug &DD, unsigned Form);
685
686   /// SizeOf - Determine size of block data in bytes.
687   ///
688   virtual unsigned SizeOf(const DwarfDebug &DD, unsigned Form) const;
689
690
691   /// Profile - Used to gather unique data for the value folding set.
692   ///
693   virtual void Profile(FoldingSetNodeID &ID) {
694     ID.AddInteger(isBlock);
695     DIE::Profile(ID);
696   }
697
698 #ifndef NDEBUG
699   virtual void print(std::ostream &O) {
700     O << "Blk: ";
701     DIE::print(O, 5);
702   }
703 #endif
704 };
705
706 //===----------------------------------------------------------------------===//
707 /// CompileUnit - This dwarf writer support class manages information associate
708 /// with a source file.
709 class CompileUnit {
710 private:
711   /// Desc - Compile unit debug descriptor.
712   ///
713   CompileUnitDesc *Desc;
714
715   /// ID - File identifier for source.
716   ///
717   unsigned ID;
718
719   /// Die - Compile unit debug information entry.
720   ///
721   DIE *Die;
722
723   /// DescToDieMap - Tracks the mapping of unit level debug informaton
724   /// descriptors to debug information entries.
725   std::map<DebugInfoDesc *, DIE *> DescToDieMap;
726
727   /// DescToDIEntryMap - Tracks the mapping of unit level debug informaton
728   /// descriptors to debug information entries using a DIEntry proxy.
729   std::map<DebugInfoDesc *, DIEntry *> DescToDIEntryMap;
730
731   /// Globals - A map of globally visible named entities for this unit.
732   ///
733   std::map<std::string, DIE *> Globals;
734
735   /// DiesSet - Used to uniquely define dies within the compile unit.
736   ///
737   FoldingSet<DIE> DiesSet;
738
739   /// Dies - List of all dies in the compile unit.
740   ///
741   std::vector<DIE *> Dies;
742
743 public:
744   CompileUnit(CompileUnitDesc *CUD, unsigned I, DIE *D)
745   : Desc(CUD)
746   , ID(I)
747   , Die(D)
748   , DescToDieMap()
749   , DescToDIEntryMap()
750   , Globals()
751   , DiesSet(InitDiesSetSize)
752   , Dies()
753   {}
754
755   ~CompileUnit() {
756     delete Die;
757
758     for (unsigned i = 0, N = Dies.size(); i < N; ++i)
759       delete Dies[i];
760   }
761
762   // Accessors.
763   CompileUnitDesc *getDesc() const { return Desc; }
764   unsigned getID()           const { return ID; }
765   DIE* getDie()              const { return Die; }
766   std::map<std::string, DIE *> &getGlobals() { return Globals; }
767
768   /// hasContent - Return true if this compile unit has something to write out.
769   ///
770   bool hasContent() const {
771     return !Die->getChildren().empty();
772   }
773
774   /// AddGlobal - Add a new global entity to the compile unit.
775   ///
776   void AddGlobal(const std::string &Name, DIE *Die) {
777     Globals[Name] = Die;
778   }
779
780   /// getDieMapSlotFor - Returns the debug information entry map slot for the
781   /// specified debug descriptor.
782   DIE *&getDieMapSlotFor(DebugInfoDesc *DID) {
783     return DescToDieMap[DID];
784   }
785
786   /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
787   /// specified debug descriptor.
788   DIEntry *&getDIEntrySlotFor(DebugInfoDesc *DID) {
789     return DescToDIEntryMap[DID];
790   }
791
792   /// AddDie - Adds or interns the DIE to the compile unit.
793   ///
794   DIE *AddDie(DIE &Buffer) {
795     FoldingSetNodeID ID;
796     Buffer.Profile(ID);
797     void *Where;
798     DIE *Die = DiesSet.FindNodeOrInsertPos(ID, Where);
799
800     if (!Die) {
801       Die = new DIE(Buffer);
802       DiesSet.InsertNode(Die, Where);
803       this->Die->AddChild(Die);
804       Buffer.Detach();
805     }
806
807     return Die;
808   }
809 };
810
811 //===----------------------------------------------------------------------===//
812 /// Dwarf - Emits general Dwarf directives.
813 ///
814 class Dwarf {
815
816 protected:
817
818   //===--------------------------------------------------------------------===//
819   // Core attributes used by the Dwarf writer.
820   //
821
822   //
823   /// O - Stream to .s file.
824   ///
825   raw_ostream &O;
826
827   /// Asm - Target of Dwarf emission.
828   ///
829   AsmPrinter *Asm;
830
831   /// TAI - Target asm information.
832   const TargetAsmInfo *TAI;
833
834   /// TD - Target data.
835   const TargetData *TD;
836
837   /// RI - Register Information.
838   const TargetRegisterInfo *RI;
839
840   /// M - Current module.
841   ///
842   Module *M;
843
844   /// MF - Current machine function.
845   ///
846   MachineFunction *MF;
847
848   /// MMI - Collected machine module information.
849   ///
850   MachineModuleInfo *MMI;
851
852   /// SubprogramCount - The running count of functions being compiled.
853   ///
854   unsigned SubprogramCount;
855
856   /// Flavor - A unique string indicating what dwarf producer this is, used to
857   /// unique labels.
858   const char * const Flavor;
859
860   unsigned SetCounter;
861   Dwarf(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T,
862         const char *flavor)
863   : O(OS)
864   , Asm(A)
865   , TAI(T)
866   , TD(Asm->TM.getTargetData())
867   , RI(Asm->TM.getRegisterInfo())
868   , M(NULL)
869   , MF(NULL)
870   , MMI(NULL)
871   , SubprogramCount(0)
872   , Flavor(flavor)
873   , SetCounter(1)
874   {
875   }
876
877 public:
878
879   //===--------------------------------------------------------------------===//
880   // Accessors.
881   //
882   AsmPrinter *getAsm() const { return Asm; }
883   MachineModuleInfo *getMMI() const { return MMI; }
884   const TargetAsmInfo *getTargetAsmInfo() const { return TAI; }
885   const TargetData *getTargetData() const { return TD; }
886
887   void PrintRelDirective(bool Force32Bit = false, bool isInSection = false)
888                                                                          const {
889     if (isInSection && TAI->getDwarfSectionOffsetDirective())
890       O << TAI->getDwarfSectionOffsetDirective();
891     else if (Force32Bit || TD->getPointerSize() == sizeof(int32_t))
892       O << TAI->getData32bitsDirective();
893     else
894       O << TAI->getData64bitsDirective();
895   }
896
897   /// PrintLabelName - Print label name in form used by Dwarf writer.
898   ///
899   void PrintLabelName(DWLabel Label) const {
900     PrintLabelName(Label.Tag, Label.Number);
901   }
902   void PrintLabelName(const char *Tag, unsigned Number) const {
903     O << TAI->getPrivateGlobalPrefix() << Tag;
904     if (Number) O << Number;
905   }
906
907   void PrintLabelName(const char *Tag, unsigned Number,
908                       const char *Suffix) const {
909     O << TAI->getPrivateGlobalPrefix() << Tag;
910     if (Number) O << Number;
911     O << Suffix;
912   }
913
914   /// EmitLabel - Emit location label for internal use by Dwarf.
915   ///
916   void EmitLabel(DWLabel Label) const {
917     EmitLabel(Label.Tag, Label.Number);
918   }
919   void EmitLabel(const char *Tag, unsigned Number) const {
920     PrintLabelName(Tag, Number);
921     O << ":\n";
922   }
923
924   /// EmitReference - Emit a reference to a label.
925   ///
926   void EmitReference(DWLabel Label, bool IsPCRelative = false,
927                      bool Force32Bit = false) const {
928     EmitReference(Label.Tag, Label.Number, IsPCRelative, Force32Bit);
929   }
930   void EmitReference(const char *Tag, unsigned Number,
931                      bool IsPCRelative = false, bool Force32Bit = false) const {
932     PrintRelDirective(Force32Bit);
933     PrintLabelName(Tag, Number);
934
935     if (IsPCRelative) O << "-" << TAI->getPCSymbol();
936   }
937   void EmitReference(const std::string &Name, bool IsPCRelative = false,
938                      bool Force32Bit = false) const {
939     PrintRelDirective(Force32Bit);
940
941     O << Name;
942
943     if (IsPCRelative) O << "-" << TAI->getPCSymbol();
944   }
945
946   /// EmitDifference - Emit the difference between two labels.  Some
947   /// assemblers do not behave with absolute expressions with data directives,
948   /// so there is an option (needsSet) to use an intermediary set expression.
949   void EmitDifference(DWLabel LabelHi, DWLabel LabelLo,
950                       bool IsSmall = false) {
951     EmitDifference(LabelHi.Tag, LabelHi.Number,
952                    LabelLo.Tag, LabelLo.Number,
953                    IsSmall);
954   }
955   void EmitDifference(const char *TagHi, unsigned NumberHi,
956                       const char *TagLo, unsigned NumberLo,
957                       bool IsSmall = false) {
958     if (TAI->needsSet()) {
959       O << "\t.set\t";
960       PrintLabelName("set", SetCounter, Flavor);
961       O << ",";
962       PrintLabelName(TagHi, NumberHi);
963       O << "-";
964       PrintLabelName(TagLo, NumberLo);
965       O << "\n";
966
967       PrintRelDirective(IsSmall);
968       PrintLabelName("set", SetCounter, Flavor);
969       ++SetCounter;
970     } else {
971       PrintRelDirective(IsSmall);
972
973       PrintLabelName(TagHi, NumberHi);
974       O << "-";
975       PrintLabelName(TagLo, NumberLo);
976     }
977   }
978
979   void EmitSectionOffset(const char* Label, const char* Section,
980                          unsigned LabelNumber, unsigned SectionNumber,
981                          bool IsSmall = false, bool isEH = false,
982                          bool useSet = true) {
983     bool printAbsolute = false;
984     if (isEH)
985       printAbsolute = TAI->isAbsoluteEHSectionOffsets();
986     else
987       printAbsolute = TAI->isAbsoluteDebugSectionOffsets();
988
989     if (TAI->needsSet() && useSet) {
990       O << "\t.set\t";
991       PrintLabelName("set", SetCounter, Flavor);
992       O << ",";
993       PrintLabelName(Label, LabelNumber);
994
995       if (!printAbsolute) {
996         O << "-";
997         PrintLabelName(Section, SectionNumber);
998       }
999       O << "\n";
1000
1001       PrintRelDirective(IsSmall);
1002
1003       PrintLabelName("set", SetCounter, Flavor);
1004       ++SetCounter;
1005     } else {
1006       PrintRelDirective(IsSmall, true);
1007
1008       PrintLabelName(Label, LabelNumber);
1009
1010       if (!printAbsolute) {
1011         O << "-";
1012         PrintLabelName(Section, SectionNumber);
1013       }
1014     }
1015   }
1016
1017   /// EmitFrameMoves - Emit frame instructions to describe the layout of the
1018   /// frame.
1019   void EmitFrameMoves(const char *BaseLabel, unsigned BaseLabelID,
1020                       const std::vector<MachineMove> &Moves, bool isEH) {
1021     int stackGrowth =
1022         Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
1023           TargetFrameInfo::StackGrowsUp ?
1024             TD->getPointerSize() : -TD->getPointerSize();
1025     bool IsLocal = BaseLabel && strcmp(BaseLabel, "label") == 0;
1026
1027     for (unsigned i = 0, N = Moves.size(); i < N; ++i) {
1028       const MachineMove &Move = Moves[i];
1029       unsigned LabelID = Move.getLabelID();
1030
1031       if (LabelID) {
1032         LabelID = MMI->MappedLabel(LabelID);
1033
1034         // Throw out move if the label is invalid.
1035         if (!LabelID) continue;
1036       }
1037
1038       const MachineLocation &Dst = Move.getDestination();
1039       const MachineLocation &Src = Move.getSource();
1040
1041       // Advance row if new location.
1042       if (BaseLabel && LabelID && (BaseLabelID != LabelID || !IsLocal)) {
1043         Asm->EmitInt8(DW_CFA_advance_loc4);
1044         Asm->EOL("DW_CFA_advance_loc4");
1045         EmitDifference("label", LabelID, BaseLabel, BaseLabelID, true);
1046         Asm->EOL();
1047
1048         BaseLabelID = LabelID;
1049         BaseLabel = "label";
1050         IsLocal = true;
1051       }
1052
1053       // If advancing cfa.
1054       if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
1055         if (!Src.isReg()) {
1056           if (Src.getReg() == MachineLocation::VirtualFP) {
1057             Asm->EmitInt8(DW_CFA_def_cfa_offset);
1058             Asm->EOL("DW_CFA_def_cfa_offset");
1059           } else {
1060             Asm->EmitInt8(DW_CFA_def_cfa);
1061             Asm->EOL("DW_CFA_def_cfa");
1062             Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getReg(), isEH));
1063             Asm->EOL("Register");
1064           }
1065
1066           int Offset = -Src.getOffset();
1067
1068           Asm->EmitULEB128Bytes(Offset);
1069           Asm->EOL("Offset");
1070         } else {
1071           assert(0 && "Machine move no supported yet.");
1072         }
1073       } else if (Src.isReg() &&
1074         Src.getReg() == MachineLocation::VirtualFP) {
1075         if (Dst.isReg()) {
1076           Asm->EmitInt8(DW_CFA_def_cfa_register);
1077           Asm->EOL("DW_CFA_def_cfa_register");
1078           Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getReg(), isEH));
1079           Asm->EOL("Register");
1080         } else {
1081           assert(0 && "Machine move no supported yet.");
1082         }
1083       } else {
1084         unsigned Reg = RI->getDwarfRegNum(Src.getReg(), isEH);
1085         int Offset = Dst.getOffset() / stackGrowth;
1086
1087         if (Offset < 0) {
1088           Asm->EmitInt8(DW_CFA_offset_extended_sf);
1089           Asm->EOL("DW_CFA_offset_extended_sf");
1090           Asm->EmitULEB128Bytes(Reg);
1091           Asm->EOL("Reg");
1092           Asm->EmitSLEB128Bytes(Offset);
1093           Asm->EOL("Offset");
1094         } else if (Reg < 64) {
1095           Asm->EmitInt8(DW_CFA_offset + Reg);
1096           if (VerboseAsm)
1097             Asm->EOL("DW_CFA_offset + Reg (" + utostr(Reg) + ")");
1098           else
1099             Asm->EOL();
1100           Asm->EmitULEB128Bytes(Offset);
1101           Asm->EOL("Offset");
1102         } else {
1103           Asm->EmitInt8(DW_CFA_offset_extended);
1104           Asm->EOL("DW_CFA_offset_extended");
1105           Asm->EmitULEB128Bytes(Reg);
1106           Asm->EOL("Reg");
1107           Asm->EmitULEB128Bytes(Offset);
1108           Asm->EOL("Offset");
1109         }
1110       }
1111     }
1112   }
1113
1114 };
1115
1116 //===----------------------------------------------------------------------===//
1117 /// DwarfDebug - Emits Dwarf debug directives.
1118 ///
1119 class DwarfDebug : public Dwarf {
1120
1121 private:
1122   //===--------------------------------------------------------------------===//
1123   // Attributes used to construct specific Dwarf sections.
1124   //
1125
1126   /// CompileUnits - All the compile units involved in this build.  The index
1127   /// of each entry in this vector corresponds to the sources in MMI.
1128   std::vector<CompileUnit *> CompileUnits;
1129
1130   /// AbbreviationsSet - Used to uniquely define abbreviations.
1131   ///
1132   FoldingSet<DIEAbbrev> AbbreviationsSet;
1133
1134   /// Abbreviations - A list of all the unique abbreviations in use.
1135   ///
1136   std::vector<DIEAbbrev *> Abbreviations;
1137
1138   /// ValuesSet - Used to uniquely define values.
1139   ///
1140   FoldingSet<DIEValue> ValuesSet;
1141
1142   /// Values - A list of all the unique values in use.
1143   ///
1144   std::vector<DIEValue *> Values;
1145
1146   /// StringPool - A UniqueVector of strings used by indirect references.
1147   ///
1148   UniqueVector<std::string> StringPool;
1149
1150   /// UnitMap - Map debug information descriptor to compile unit.
1151   ///
1152   std::map<DebugInfoDesc *, CompileUnit *> DescToUnitMap;
1153
1154   /// SectionMap - Provides a unique id per text section.
1155   ///
1156   UniqueVector<const Section*> SectionMap;
1157
1158   /// SectionSourceLines - Tracks line numbers per text section.
1159   ///
1160   std::vector<std::vector<SourceLineInfo> > SectionSourceLines;
1161
1162   /// didInitial - Flag to indicate if initial emission has been done.
1163   ///
1164   bool didInitial;
1165
1166   /// shouldEmit - Flag to indicate if debug information should be emitted.
1167   ///
1168   bool shouldEmit;
1169
1170   struct FunctionDebugFrameInfo {
1171     unsigned Number;
1172     std::vector<MachineMove> Moves;
1173
1174     FunctionDebugFrameInfo(unsigned Num, const std::vector<MachineMove> &M):
1175       Number(Num), Moves(M) { }
1176   };
1177
1178   std::vector<FunctionDebugFrameInfo> DebugFrames;
1179
1180 public:
1181
1182   /// ShouldEmitDwarf - Returns true if Dwarf declarations should be made.
1183   ///
1184   bool ShouldEmitDwarf() const { return shouldEmit; }
1185
1186   /// AssignAbbrevNumber - Define a unique number for the abbreviation.
1187   ///
1188   void AssignAbbrevNumber(DIEAbbrev &Abbrev) {
1189     // Profile the node so that we can make it unique.
1190     FoldingSetNodeID ID;
1191     Abbrev.Profile(ID);
1192
1193     // Check the set for priors.
1194     DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
1195
1196     // If it's newly added.
1197     if (InSet == &Abbrev) {
1198       // Add to abbreviation list.
1199       Abbreviations.push_back(&Abbrev);
1200       // Assign the vector position + 1 as its number.
1201       Abbrev.setNumber(Abbreviations.size());
1202     } else {
1203       // Assign existing abbreviation number.
1204       Abbrev.setNumber(InSet->getNumber());
1205     }
1206   }
1207
1208   /// NewString - Add a string to the constant pool and returns a label.
1209   ///
1210   DWLabel NewString(const std::string &String) {
1211     unsigned StringID = StringPool.insert(String);
1212     return DWLabel("string", StringID);
1213   }
1214
1215   /// NewDIEntry - Creates a new DIEntry to be a proxy for a debug information
1216   /// entry.
1217   DIEntry *NewDIEntry(DIE *Entry = NULL) {
1218     DIEntry *Value;
1219
1220     if (Entry) {
1221       FoldingSetNodeID ID;
1222       DIEntry::Profile(ID, Entry);
1223       void *Where;
1224       Value = static_cast<DIEntry *>(ValuesSet.FindNodeOrInsertPos(ID, Where));
1225
1226       if (Value) return Value;
1227
1228       Value = new DIEntry(Entry);
1229       ValuesSet.InsertNode(Value, Where);
1230     } else {
1231       Value = new DIEntry(Entry);
1232     }
1233
1234     Values.push_back(Value);
1235     return Value;
1236   }
1237
1238   /// SetDIEntry - Set a DIEntry once the debug information entry is defined.
1239   ///
1240   void SetDIEntry(DIEntry *Value, DIE *Entry) {
1241     Value->Entry = Entry;
1242     // Add to values set if not already there.  If it is, we merely have a
1243     // duplicate in the values list (no harm.)
1244     ValuesSet.GetOrInsertNode(Value);
1245   }
1246
1247   /// AddUInt - Add an unsigned integer attribute data and value.
1248   ///
1249   void AddUInt(DIE *Die, unsigned Attribute, unsigned Form, uint64_t Integer) {
1250     if (!Form) Form = DIEInteger::BestForm(false, Integer);
1251
1252     FoldingSetNodeID ID;
1253     DIEInteger::Profile(ID, Integer);
1254     void *Where;
1255     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1256     if (!Value) {
1257       Value = new DIEInteger(Integer);
1258       ValuesSet.InsertNode(Value, Where);
1259       Values.push_back(Value);
1260     }
1261
1262     Die->AddValue(Attribute, Form, Value);
1263   }
1264
1265   /// AddSInt - Add an signed integer attribute data and value.
1266   ///
1267   void AddSInt(DIE *Die, unsigned Attribute, unsigned Form, int64_t Integer) {
1268     if (!Form) Form = DIEInteger::BestForm(true, Integer);
1269
1270     FoldingSetNodeID ID;
1271     DIEInteger::Profile(ID, (uint64_t)Integer);
1272     void *Where;
1273     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1274     if (!Value) {
1275       Value = new DIEInteger(Integer);
1276       ValuesSet.InsertNode(Value, Where);
1277       Values.push_back(Value);
1278     }
1279
1280     Die->AddValue(Attribute, Form, Value);
1281   }
1282
1283   /// AddString - Add a std::string attribute data and value.
1284   ///
1285   void AddString(DIE *Die, unsigned Attribute, unsigned Form,
1286                  const std::string &String) {
1287     FoldingSetNodeID ID;
1288     DIEString::Profile(ID, String);
1289     void *Where;
1290     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1291     if (!Value) {
1292       Value = new DIEString(String);
1293       ValuesSet.InsertNode(Value, Where);
1294       Values.push_back(Value);
1295     }
1296
1297     Die->AddValue(Attribute, Form, Value);
1298   }
1299
1300   /// AddLabel - Add a Dwarf label attribute data and value.
1301   ///
1302   void AddLabel(DIE *Die, unsigned Attribute, unsigned Form,
1303                      const DWLabel &Label) {
1304     FoldingSetNodeID ID;
1305     DIEDwarfLabel::Profile(ID, Label);
1306     void *Where;
1307     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1308     if (!Value) {
1309       Value = new DIEDwarfLabel(Label);
1310       ValuesSet.InsertNode(Value, Where);
1311       Values.push_back(Value);
1312     }
1313
1314     Die->AddValue(Attribute, Form, Value);
1315   }
1316
1317   /// AddObjectLabel - Add an non-Dwarf label attribute data and value.
1318   ///
1319   void AddObjectLabel(DIE *Die, unsigned Attribute, unsigned Form,
1320                       const std::string &Label) {
1321     FoldingSetNodeID ID;
1322     DIEObjectLabel::Profile(ID, Label);
1323     void *Where;
1324     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1325     if (!Value) {
1326       Value = new DIEObjectLabel(Label);
1327       ValuesSet.InsertNode(Value, Where);
1328       Values.push_back(Value);
1329     }
1330
1331     Die->AddValue(Attribute, Form, Value);
1332   }
1333
1334   /// AddSectionOffset - Add a section offset label attribute data and value.
1335   ///
1336   void AddSectionOffset(DIE *Die, unsigned Attribute, unsigned Form,
1337                         const DWLabel &Label, const DWLabel &Section,
1338                         bool isEH = false, bool useSet = true) {
1339     FoldingSetNodeID ID;
1340     DIESectionOffset::Profile(ID, Label, Section);
1341     void *Where;
1342     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1343     if (!Value) {
1344       Value = new DIESectionOffset(Label, Section, isEH, useSet);
1345       ValuesSet.InsertNode(Value, Where);
1346       Values.push_back(Value);
1347     }
1348
1349     Die->AddValue(Attribute, Form, Value);
1350   }
1351
1352   /// AddDelta - Add a label delta attribute data and value.
1353   ///
1354   void AddDelta(DIE *Die, unsigned Attribute, unsigned Form,
1355                           const DWLabel &Hi, const DWLabel &Lo) {
1356     FoldingSetNodeID ID;
1357     DIEDelta::Profile(ID, Hi, Lo);
1358     void *Where;
1359     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1360     if (!Value) {
1361       Value = new DIEDelta(Hi, Lo);
1362       ValuesSet.InsertNode(Value, Where);
1363       Values.push_back(Value);
1364     }
1365
1366     Die->AddValue(Attribute, Form, Value);
1367   }
1368
1369   /// AddDIEntry - Add a DIE attribute data and value.
1370   ///
1371   void AddDIEntry(DIE *Die, unsigned Attribute, unsigned Form, DIE *Entry) {
1372     Die->AddValue(Attribute, Form, NewDIEntry(Entry));
1373   }
1374
1375   /// AddBlock - Add block data.
1376   ///
1377   void AddBlock(DIE *Die, unsigned Attribute, unsigned Form, DIEBlock *Block) {
1378     Block->ComputeSize(*this);
1379     FoldingSetNodeID ID;
1380     Block->Profile(ID);
1381     void *Where;
1382     DIEValue *Value = ValuesSet.FindNodeOrInsertPos(ID, Where);
1383     if (!Value) {
1384       Value = Block;
1385       ValuesSet.InsertNode(Value, Where);
1386       Values.push_back(Value);
1387     } else {
1388       // Already exists, reuse the previous one.
1389       delete Block;
1390       Block = cast<DIEBlock>(Value);
1391     }
1392
1393     Die->AddValue(Attribute, Block->BestForm(), Value);
1394   }
1395
1396 private:
1397
1398   /// AddSourceLine - Add location information to specified debug information
1399   /// entry.
1400   void AddSourceLine(DIE *Die, CompileUnitDesc *File, unsigned Line) {
1401     if (File && Line) {
1402       CompileUnit *FileUnit = FindCompileUnit(File);
1403       unsigned FileID = FileUnit->getID();
1404       AddUInt(Die, DW_AT_decl_file, 0, FileID);
1405       AddUInt(Die, DW_AT_decl_line, 0, Line);
1406     }
1407   }
1408
1409   /// AddAddress - Add an address attribute to a die based on the location
1410   /// provided.
1411   void AddAddress(DIE *Die, unsigned Attribute,
1412                             const MachineLocation &Location) {
1413     unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
1414     DIEBlock *Block = new DIEBlock();
1415
1416     if (Location.isReg()) {
1417       if (Reg < 32) {
1418         AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
1419       } else {
1420         AddUInt(Block, 0, DW_FORM_data1, DW_OP_regx);
1421         AddUInt(Block, 0, DW_FORM_udata, Reg);
1422       }
1423     } else {
1424       if (Reg < 32) {
1425         AddUInt(Block, 0, DW_FORM_data1, DW_OP_breg0 + Reg);
1426       } else {
1427         AddUInt(Block, 0, DW_FORM_data1, DW_OP_bregx);
1428         AddUInt(Block, 0, DW_FORM_udata, Reg);
1429       }
1430       AddUInt(Block, 0, DW_FORM_sdata, Location.getOffset());
1431     }
1432
1433     AddBlock(Die, Attribute, 0, Block);
1434   }
1435
1436   /// AddBasicType - Add a new basic type attribute to the specified entity.
1437   ///
1438   void AddBasicType(DIE *Entity, CompileUnit *Unit,
1439                     const std::string &Name,
1440                     unsigned Encoding, unsigned Size) {
1441
1442     DIE Buffer(DW_TAG_base_type);
1443     AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1444     AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, Encoding);
1445     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1446     DIE *BasicTypeDie = Unit->AddDie(Buffer);
1447     AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, BasicTypeDie);
1448   }
1449
1450   /// AddPointerType - Add a new pointer type attribute to the specified entity.
1451   ///
1452   void AddPointerType(DIE *Entity, CompileUnit *Unit, const std::string &Name) {
1453     DIE Buffer(DW_TAG_pointer_type);
1454     AddUInt(&Buffer, DW_AT_byte_size, 0, TD->getPointerSize());
1455     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1456     DIE *PointerTypeDie =  Unit->AddDie(Buffer);
1457     AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, PointerTypeDie);
1458   }
1459
1460   /// AddType - Add a new type attribute to the specified entity.
1461   ///
1462   void AddType(DIE *Entity, TypeDesc *TyDesc, CompileUnit *Unit) {
1463     if (!TyDesc) {
1464       AddBasicType(Entity, Unit, "", DW_ATE_signed, sizeof(int32_t));
1465     } else {
1466       // Check for pre-existence.
1467       DIEntry *&Slot = Unit->getDIEntrySlotFor(TyDesc);
1468
1469       // If it exists then use the existing value.
1470       if (Slot) {
1471         Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1472         return;
1473       }
1474
1475       if (SubprogramDesc *SubprogramTy = dyn_cast<SubprogramDesc>(TyDesc)) {
1476         // FIXME - Not sure why programs and variables are coming through here.
1477         // Short cut for handling subprogram types (not really a TyDesc.)
1478         AddPointerType(Entity, Unit, SubprogramTy->getName());
1479       } else if (GlobalVariableDesc *GlobalTy =
1480                                          dyn_cast<GlobalVariableDesc>(TyDesc)) {
1481         // FIXME - Not sure why programs and variables are coming through here.
1482         // Short cut for handling global variable types (not really a TyDesc.)
1483         AddPointerType(Entity, Unit, GlobalTy->getName());
1484       } else {
1485         // Set up proxy.
1486         Slot = NewDIEntry();
1487
1488         // Construct type.
1489         DIE Buffer(DW_TAG_base_type);
1490         ConstructType(Buffer, TyDesc, Unit);
1491
1492         // Add debug information entry to entity and unit.
1493         DIE *Die = Unit->AddDie(Buffer);
1494         SetDIEntry(Slot, Die);
1495         Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
1496       }
1497     }
1498   }
1499
1500   /// ConstructType - Construct basic type die from DIBasicType.
1501   void ConstructType(CompileUnit *DW_Unit, DIE &Buffer,
1502                      DIBasicType *BTy) {
1503     
1504     // Get core information.
1505     const std::string &Name = BTy->getName();
1506     Buffer.setTag(DW_TAG_base_type);
1507     AddUInt(&Buffer, DW_AT_encoding,  DW_FORM_data1, BTy->getEncoding());
1508     // Add name if not anonymous or intermediate type.
1509     if (!Name.empty())
1510       AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1511     uint64_t Size = BTy->getSizeInBits() >> 3;
1512     AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1513   }
1514
1515   /// ConstructType - Construct derived type die from DIDerivedType.
1516   void ConstructType(CompileUnit *DW_Unit, DIE &Buffer,
1517                      DIDerivedType *DTy) {
1518
1519     // Get core information.
1520     const std::string &Name = DTy->getName();
1521     uint64_t Size = DTy->getSizeInBits() >> 3;
1522     unsigned Tag = DTy->getTag();
1523     // FIXME - Workaround for templates.
1524     if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1525
1526     Buffer.setTag(Tag);
1527     // Map to main type, void will not have a type.
1528     DIType FromTy = DTy->getTypeDerivedFrom();
1529     // FIXME - Enable this. AddType(&Buffer, FromTy, DW_Unit);
1530
1531     // Add name if not anonymous or intermediate type.
1532     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1533
1534     // Add size if non-zero (derived types might be zero-sized.)
1535     if (Size)
1536       AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1537
1538     // Add source line info if available and TyDesc is not a forward
1539     // declaration.
1540     // FIXME - Enable this. if (!DTy->isForwardDecl())
1541     // FIXME - Enable this.     AddSourceLine(&Buffer, *DTy);
1542   }
1543
1544   // ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
1545   void ConstructSubrangeDIE (DIE &Buffer, DISubrange *SR, DIE *IndexTy) {
1546     int64_t L = SR->getLo();
1547     int64_t H = SR->getHi();
1548     DIE *DW_Subrange = new DIE(DW_TAG_subrange_type);
1549     if (L != H) {
1550       AddDIEntry(DW_Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1551       if (L)
1552         AddSInt(DW_Subrange, DW_AT_lower_bound, 0, L);
1553         AddSInt(DW_Subrange, DW_AT_upper_bound, 0, H);
1554     }
1555     Buffer.AddChild(DW_Subrange);
1556   }
1557
1558   /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
1559   void ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer, 
1560                              DICompositeType *CTy) {
1561     Buffer.setTag(DW_TAG_array_type);
1562     if (CTy->getTag() == DW_TAG_vector_type)
1563       AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1564     
1565     DIArray Elements = CTy->getTypeArray();
1566     // FIXME - Enable this. 
1567     // AddType(&Buffer, CTy->getTypeDerivedFrom(), DW_Unit);
1568
1569     // Construct an anonymous type for index type.
1570     DIE IdxBuffer(DW_TAG_base_type);
1571     AddUInt(&IdxBuffer, DW_AT_byte_size, 0, sizeof(int32_t));
1572     AddUInt(&IdxBuffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1573     DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
1574
1575     // Add subranges to array type.
1576     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
1577       DISubrange Element = Elements.getElement(i);
1578       ConstructSubrangeDIE(Buffer, &Element, IndexTy);
1579     }
1580   }
1581
1582   /// ConstructEnumTypeDIE - Construct enum type DIE from 
1583   /// DIEnumerator.
1584   void ConstructEnumType(CompileUnit *DW_Unit, 
1585                          DIE &Buffer, DIEnumerator *ETy) {
1586
1587     DIE *Enumerator = new DIE(DW_TAG_enumerator);
1588     AddString(Enumerator, DW_AT_name, DW_FORM_string, ETy->getName());
1589     int64_t Value = ETy->getEnumValue();                             
1590     AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1591     Buffer.AddChild(Enumerator);
1592   }
1593
1594   /// ConstructType - Adds all the required attributes to the type.
1595   ///
1596   void ConstructType(DIE &Buffer, TypeDesc *TyDesc, CompileUnit *Unit) {
1597     // Get core information.
1598     const std::string &Name = TyDesc->getName();
1599     uint64_t Size = TyDesc->getSize() >> 3;
1600
1601     if (BasicTypeDesc *BasicTy = dyn_cast<BasicTypeDesc>(TyDesc)) {
1602       // Fundamental types like int, float, bool
1603       Buffer.setTag(DW_TAG_base_type);
1604       AddUInt(&Buffer, DW_AT_encoding,  DW_FORM_data1, BasicTy->getEncoding());
1605     } else if (DerivedTypeDesc *DerivedTy = dyn_cast<DerivedTypeDesc>(TyDesc)) {
1606       // Fetch tag.
1607       unsigned Tag = DerivedTy->getTag();
1608       // FIXME - Workaround for templates.
1609       if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
1610       // Pointers, typedefs et al.
1611       Buffer.setTag(Tag);
1612       // Map to main type, void will not have a type.
1613       if (TypeDesc *FromTy = DerivedTy->getFromType())
1614         AddType(&Buffer, FromTy, Unit);
1615     } else if (CompositeTypeDesc *CompTy = dyn_cast<CompositeTypeDesc>(TyDesc)){
1616       // Fetch tag.
1617       unsigned Tag = CompTy->getTag();
1618
1619       // Set tag accordingly.
1620       if (Tag == DW_TAG_vector_type)
1621         Buffer.setTag(DW_TAG_array_type);
1622       else
1623         Buffer.setTag(Tag);
1624
1625       std::vector<DebugInfoDesc *> &Elements = CompTy->getElements();
1626
1627       switch (Tag) {
1628       case DW_TAG_vector_type:
1629         AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
1630         // Fall thru
1631       case DW_TAG_array_type: {
1632         // Add element type.
1633         if (TypeDesc *FromTy = CompTy->getFromType())
1634           AddType(&Buffer, FromTy, Unit);
1635
1636         // Don't emit size attribute.
1637         Size = 0;
1638
1639         // Construct an anonymous type for index type.
1640         DIE Buffer(DW_TAG_base_type);
1641         AddUInt(&Buffer, DW_AT_byte_size, 0, sizeof(int32_t));
1642         AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
1643         DIE *IndexTy = Unit->AddDie(Buffer);
1644
1645         // Add subranges to array type.
1646         for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1647           SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
1648           int64_t Lo = SRD->getLo();
1649           int64_t Hi = SRD->getHi();
1650           DIE *Subrange = new DIE(DW_TAG_subrange_type);
1651
1652           // If a range is available.
1653           if (Lo != Hi) {
1654             AddDIEntry(Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
1655             // Only add low if non-zero.
1656             if (Lo) AddSInt(Subrange, DW_AT_lower_bound, 0, Lo);
1657             AddSInt(Subrange, DW_AT_upper_bound, 0, Hi);
1658           }
1659
1660           Buffer.AddChild(Subrange);
1661         }
1662         break;
1663       }
1664       case DW_TAG_structure_type:
1665       case DW_TAG_union_type: {
1666         // Add elements to structure type.
1667         for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1668           DebugInfoDesc *Element = Elements[i];
1669
1670           if (DerivedTypeDesc *MemberDesc = dyn_cast<DerivedTypeDesc>(Element)){
1671             // Add field or base class.
1672             unsigned Tag = MemberDesc->getTag();
1673
1674             // Extract the basic information.
1675             const std::string &Name = MemberDesc->getName();
1676             uint64_t Size = MemberDesc->getSize();
1677             uint64_t Align = MemberDesc->getAlign();
1678             uint64_t Offset = MemberDesc->getOffset();
1679
1680             // Construct member debug information entry.
1681             DIE *Member = new DIE(Tag);
1682
1683             // Add name if not "".
1684             if (!Name.empty())
1685               AddString(Member, DW_AT_name, DW_FORM_string, Name);
1686
1687             // Add location if available.
1688             AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
1689
1690             // Most of the time the field info is the same as the members.
1691             uint64_t FieldSize = Size;
1692             uint64_t FieldAlign = Align;
1693             uint64_t FieldOffset = Offset;
1694
1695             // Set the member type.
1696             TypeDesc *FromTy = MemberDesc->getFromType();
1697             AddType(Member, FromTy, Unit);
1698
1699             // Walk up typedefs until a real size is found.
1700             while (FromTy) {
1701               if (FromTy->getTag() != DW_TAG_typedef) {
1702                 FieldSize = FromTy->getSize();
1703                 FieldAlign = FromTy->getAlign();
1704                 break;
1705               }
1706
1707               FromTy = cast<DerivedTypeDesc>(FromTy)->getFromType();
1708             }
1709
1710             // Unless we have a bit field.
1711             if (Tag == DW_TAG_member && FieldSize != Size) {
1712               // Construct the alignment mask.
1713               uint64_t AlignMask = ~(FieldAlign - 1);
1714               // Determine the high bit + 1 of the declared size.
1715               uint64_t HiMark = (Offset + FieldSize) & AlignMask;
1716               // Work backwards to determine the base offset of the field.
1717               FieldOffset = HiMark - FieldSize;
1718               // Now normalize offset to the field.
1719               Offset -= FieldOffset;
1720
1721               // Maybe we need to work from the other end.
1722               if (TD->isLittleEndian()) Offset = FieldSize - (Offset + Size);
1723
1724               // Add size and offset.
1725               AddUInt(Member, DW_AT_byte_size, 0, FieldSize >> 3);
1726               AddUInt(Member, DW_AT_bit_size, 0, Size);
1727               AddUInt(Member, DW_AT_bit_offset, 0, Offset);
1728             }
1729
1730             // Add computation for offset.
1731             DIEBlock *Block = new DIEBlock();
1732             AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
1733             AddUInt(Block, 0, DW_FORM_udata, FieldOffset >> 3);
1734             AddBlock(Member, DW_AT_data_member_location, 0, Block);
1735
1736             // Add accessibility (public default unless is base class.
1737             if (MemberDesc->isProtected()) {
1738               AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_protected);
1739             } else if (MemberDesc->isPrivate()) {
1740               AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_private);
1741             } else if (Tag == DW_TAG_inheritance) {
1742               AddUInt(Member, DW_AT_accessibility, 0, DW_ACCESS_public);
1743             }
1744
1745             Buffer.AddChild(Member);
1746           } else if (GlobalVariableDesc *StaticDesc =
1747                                         dyn_cast<GlobalVariableDesc>(Element)) {
1748             // Add static member.
1749
1750             // Construct member debug information entry.
1751             DIE *Static = new DIE(DW_TAG_variable);
1752
1753             // Add name and mangled name.
1754             const std::string &Name = StaticDesc->getName();
1755             const std::string &LinkageName = StaticDesc->getLinkageName();
1756             AddString(Static, DW_AT_name, DW_FORM_string, Name);
1757             if (!LinkageName.empty()) {
1758               AddString(Static, DW_AT_MIPS_linkage_name, DW_FORM_string,
1759                                 LinkageName);
1760             }
1761
1762             // Add location.
1763             AddSourceLine(Static, StaticDesc->getFile(), StaticDesc->getLine());
1764
1765             // Add type.
1766             if (TypeDesc *StaticTy = StaticDesc->getType())
1767               AddType(Static, StaticTy, Unit);
1768
1769             // Add flags.
1770             if (!StaticDesc->isStatic())
1771               AddUInt(Static, DW_AT_external, DW_FORM_flag, 1);
1772             AddUInt(Static, DW_AT_declaration, DW_FORM_flag, 1);
1773
1774             Buffer.AddChild(Static);
1775           } else if (SubprogramDesc *MethodDesc =
1776                                             dyn_cast<SubprogramDesc>(Element)) {
1777             // Add member function.
1778
1779             // Construct member debug information entry.
1780             DIE *Method = new DIE(DW_TAG_subprogram);
1781
1782             // Add name and mangled name.
1783             const std::string &Name = MethodDesc->getName();
1784             const std::string &LinkageName = MethodDesc->getLinkageName();
1785
1786             AddString(Method, DW_AT_name, DW_FORM_string, Name);
1787             bool IsCTor = TyDesc->getName() == Name;
1788
1789             if (!LinkageName.empty()) {
1790               AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string,
1791                                 LinkageName);
1792             }
1793
1794             // Add location.
1795             AddSourceLine(Method, MethodDesc->getFile(), MethodDesc->getLine());
1796
1797             // Add type.
1798             if (CompositeTypeDesc *MethodTy =
1799                    dyn_cast_or_null<CompositeTypeDesc>(MethodDesc->getType())) {
1800               // Get argument information.
1801               std::vector<DebugInfoDesc *> &Args = MethodTy->getElements();
1802
1803               // If not a ctor.
1804               if (!IsCTor) {
1805                 // Add return type.
1806                 AddType(Method, dyn_cast<TypeDesc>(Args[0]), Unit);
1807               }
1808
1809               // Add arguments.
1810               for (unsigned i = 1, N = Args.size(); i < N; ++i) {
1811                 DIE *Arg = new DIE(DW_TAG_formal_parameter);
1812                 AddType(Arg, cast<TypeDesc>(Args[i]), Unit);
1813                 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1);
1814                 Method->AddChild(Arg);
1815               }
1816             }
1817
1818             // Add flags.
1819             if (!MethodDesc->isStatic())
1820               AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);
1821             AddUInt(Method, DW_AT_declaration, DW_FORM_flag, 1);
1822
1823             Buffer.AddChild(Method);
1824           }
1825         }
1826         break;
1827       }
1828       case DW_TAG_enumeration_type: {
1829         // Add enumerators to enumeration type.
1830         for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
1831           EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
1832           const std::string &Name = ED->getName();
1833           int64_t Value = ED->getValue();
1834           DIE *Enumerator = new DIE(DW_TAG_enumerator);
1835           AddString(Enumerator, DW_AT_name, DW_FORM_string, Name);
1836           AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
1837           Buffer.AddChild(Enumerator);
1838         }
1839
1840         break;
1841       }
1842       case DW_TAG_subroutine_type: {
1843         // Add prototype flag.
1844         AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
1845         // Add return type.
1846         AddType(&Buffer, dyn_cast<TypeDesc>(Elements[0]), Unit);
1847
1848         // Add arguments.
1849         for (unsigned i = 1, N = Elements.size(); i < N; ++i) {
1850           DIE *Arg = new DIE(DW_TAG_formal_parameter);
1851           AddType(Arg, cast<TypeDesc>(Elements[i]), Unit);
1852           Buffer.AddChild(Arg);
1853         }
1854
1855         break;
1856       }
1857       default: break;
1858       }
1859     }
1860
1861     // Add name if not anonymous or intermediate type.
1862     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
1863
1864     // Add size if non-zero (derived types might be zero-sized.)
1865     if (Size)
1866       AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
1867     else if (isa<CompositeTypeDesc>(TyDesc)) {
1868       // If TyDesc is a composite type, then add size even if it's zero unless
1869       // it's a forward declaration.
1870       if (TyDesc->isForwardDecl())
1871         AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
1872       else
1873         AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
1874     }
1875
1876     // Add source line info if available and TyDesc is not a forward
1877     // declaration.
1878     if (!TyDesc->isForwardDecl())
1879       AddSourceLine(&Buffer, TyDesc->getFile(), TyDesc->getLine());
1880   }
1881
1882   /// NewCompileUnit - Create new compile unit and it's debug information entry.
1883   ///
1884   CompileUnit *NewCompileUnit(CompileUnitDesc *UnitDesc, unsigned ID) {
1885     // Construct debug information entry.
1886     DIE *Die = new DIE(DW_TAG_compile_unit);
1887     AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
1888               DWLabel("section_line", 0), DWLabel("section_line", 0), false);
1889     AddString(Die, DW_AT_producer,  DW_FORM_string, UnitDesc->getProducer());
1890     AddUInt  (Die, DW_AT_language,  DW_FORM_data1,  UnitDesc->getLanguage());
1891     AddString(Die, DW_AT_name,      DW_FORM_string, UnitDesc->getFileName());
1892     if (!UnitDesc->getDirectory().empty())
1893       AddString(Die, DW_AT_comp_dir,  DW_FORM_string, UnitDesc->getDirectory());
1894
1895     // Construct compile unit.
1896     CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
1897
1898     // Add Unit to compile unit map.
1899     DescToUnitMap[UnitDesc] = Unit;
1900
1901     return Unit;
1902   }
1903
1904   /// GetBaseCompileUnit - Get the main compile unit.
1905   ///
1906   CompileUnit *GetBaseCompileUnit() const {
1907     CompileUnit *Unit = CompileUnits[0];
1908     assert(Unit && "Missing compile unit.");
1909     return Unit;
1910   }
1911
1912   /// FindCompileUnit - Get the compile unit for the given descriptor.
1913   ///
1914   CompileUnit *FindCompileUnit(CompileUnitDesc *UnitDesc) {
1915     CompileUnit *Unit = DescToUnitMap[UnitDesc];
1916     assert(Unit && "Missing compile unit.");
1917     return Unit;
1918   }
1919
1920   /// NewGlobalVariable - Add a new global variable DIE.
1921   ///
1922   DIE *NewGlobalVariable(GlobalVariableDesc *GVD) {
1923     // Get the compile unit context.
1924     CompileUnitDesc *UnitDesc =
1925       static_cast<CompileUnitDesc *>(GVD->getContext());
1926     CompileUnit *Unit = GetBaseCompileUnit();
1927
1928     // Check for pre-existence.
1929     DIE *&Slot = Unit->getDieMapSlotFor(GVD);
1930     if (Slot) return Slot;
1931
1932     // Get the global variable itself.
1933     GlobalVariable *GV = GVD->getGlobalVariable();
1934
1935     const std::string &Name = GVD->getName();
1936     const std::string &FullName = GVD->getFullName();
1937     const std::string &LinkageName = GVD->getLinkageName();
1938     // Create the global's variable DIE.
1939     DIE *VariableDie = new DIE(DW_TAG_variable);
1940     AddString(VariableDie, DW_AT_name, DW_FORM_string, Name);
1941     if (!LinkageName.empty()) {
1942       AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1943                              LinkageName);
1944     }
1945     AddType(VariableDie, GVD->getType(), Unit);
1946     if (!GVD->isStatic())
1947       AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
1948
1949     // Add source line info if available.
1950     AddSourceLine(VariableDie, UnitDesc, GVD->getLine());
1951
1952     // Add address.
1953     DIEBlock *Block = new DIEBlock();
1954     AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
1955     AddObjectLabel(Block, 0, DW_FORM_udata, Asm->getGlobalLinkName(GV));
1956     AddBlock(VariableDie, DW_AT_location, 0, Block);
1957
1958     // Add to map.
1959     Slot = VariableDie;
1960
1961     // Add to context owner.
1962     Unit->getDie()->AddChild(VariableDie);
1963
1964     // Expose as global.
1965     // FIXME - need to check external flag.
1966     Unit->AddGlobal(FullName, VariableDie);
1967
1968     return VariableDie;
1969   }
1970
1971   /// NewSubprogram - Add a new subprogram DIE.
1972   ///
1973   DIE *NewSubprogram(SubprogramDesc *SPD) {
1974     // Get the compile unit context.
1975     CompileUnitDesc *UnitDesc =
1976       static_cast<CompileUnitDesc *>(SPD->getContext());
1977     CompileUnit *Unit = GetBaseCompileUnit();
1978
1979     // Check for pre-existence.
1980     DIE *&Slot = Unit->getDieMapSlotFor(SPD);
1981     if (Slot) return Slot;
1982
1983     // Gather the details (simplify add attribute code.)
1984     const std::string &Name = SPD->getName();
1985     const std::string &FullName = SPD->getFullName();
1986     const std::string &LinkageName = SPD->getLinkageName();
1987
1988     DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
1989     AddString(SubprogramDie, DW_AT_name, DW_FORM_string, Name);
1990     if (!LinkageName.empty()) {
1991       AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
1992                                LinkageName);
1993     }
1994     if (SPD->getType()) AddType(SubprogramDie, SPD->getType(), Unit);
1995     if (!SPD->isStatic())
1996       AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
1997     AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
1998
1999     // Add source line info if available.
2000     AddSourceLine(SubprogramDie, UnitDesc, SPD->getLine());
2001
2002     // Add to map.
2003     Slot = SubprogramDie;
2004
2005     // Add to context owner.
2006     Unit->getDie()->AddChild(SubprogramDie);
2007
2008     // Expose as global.
2009     Unit->AddGlobal(FullName, SubprogramDie);
2010
2011     return SubprogramDie;
2012   }
2013
2014   /// NewScopeVariable - Create a new scope variable.
2015   ///
2016   DIE *NewScopeVariable(DebugVariable *DV, CompileUnit *Unit) {
2017     // Get the descriptor.
2018     VariableDesc *VD = DV->getDesc();
2019
2020     // Translate tag to proper Dwarf tag.  The result variable is dropped for
2021     // now.
2022     unsigned Tag;
2023     switch (VD->getTag()) {
2024     case DW_TAG_return_variable:  return NULL;
2025     case DW_TAG_arg_variable:     Tag = DW_TAG_formal_parameter; break;
2026     case DW_TAG_auto_variable:    // fall thru
2027     default:                      Tag = DW_TAG_variable; break;
2028     }
2029
2030     // Define variable debug information entry.
2031     DIE *VariableDie = new DIE(Tag);
2032     AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
2033
2034     // Add source line info if available.
2035     AddSourceLine(VariableDie, VD->getFile(), VD->getLine());
2036
2037     // Add variable type.
2038     AddType(VariableDie, VD->getType(), Unit);
2039
2040     // Add variable address.
2041     MachineLocation Location;
2042     Location.set(RI->getFrameRegister(*MF),
2043                  RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
2044     AddAddress(VariableDie, DW_AT_location, Location);
2045
2046     return VariableDie;
2047   }
2048
2049   /// ConstructScope - Construct the components of a scope.
2050   ///
2051   void ConstructScope(DebugScope *ParentScope,
2052                       unsigned ParentStartID, unsigned ParentEndID,
2053                       DIE *ParentDie, CompileUnit *Unit) {
2054     // Add variables to scope.
2055     std::vector<DebugVariable *> &Variables = ParentScope->getVariables();
2056     for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
2057       DIE *VariableDie = NewScopeVariable(Variables[i], Unit);
2058       if (VariableDie) ParentDie->AddChild(VariableDie);
2059     }
2060
2061     // Add nested scopes.
2062     std::vector<DebugScope *> &Scopes = ParentScope->getScopes();
2063     for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
2064       // Define the Scope debug information entry.
2065       DebugScope *Scope = Scopes[j];
2066       // FIXME - Ignore inlined functions for the time being.
2067       if (!Scope->getParent()) continue;
2068
2069       unsigned StartID = MMI->MappedLabel(Scope->getStartLabelID());
2070       unsigned EndID = MMI->MappedLabel(Scope->getEndLabelID());
2071
2072       // Ignore empty scopes.
2073       if (StartID == EndID && StartID != 0) continue;
2074       if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
2075
2076       if (StartID == ParentStartID && EndID == ParentEndID) {
2077         // Just add stuff to the parent scope.
2078         ConstructScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
2079       } else {
2080         DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
2081
2082         // Add the scope bounds.
2083         if (StartID) {
2084           AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2085                              DWLabel("label", StartID));
2086         } else {
2087           AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
2088                              DWLabel("func_begin", SubprogramCount));
2089         }
2090         if (EndID) {
2091           AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2092                              DWLabel("label", EndID));
2093         } else {
2094           AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
2095                              DWLabel("func_end", SubprogramCount));
2096         }
2097
2098         // Add the scope contents.
2099         ConstructScope(Scope, StartID, EndID, ScopeDie, Unit);
2100         ParentDie->AddChild(ScopeDie);
2101       }
2102     }
2103   }
2104
2105   /// ConstructRootScope - Construct the scope for the subprogram.
2106   ///
2107   void ConstructRootScope(DebugScope *RootScope) {
2108     // Exit if there is no root scope.
2109     if (!RootScope) return;
2110
2111     // Get the subprogram debug information entry.
2112     SubprogramDesc *SPD = cast<SubprogramDesc>(RootScope->getDesc());
2113
2114     // Get the compile unit context.
2115     CompileUnit *Unit = GetBaseCompileUnit();
2116
2117     // Get the subprogram die.
2118     DIE *SPDie = Unit->getDieMapSlotFor(SPD);
2119     assert(SPDie && "Missing subprogram descriptor");
2120
2121     // Add the function bounds.
2122     AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2123                     DWLabel("func_begin", SubprogramCount));
2124     AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2125                     DWLabel("func_end", SubprogramCount));
2126     MachineLocation Location(RI->getFrameRegister(*MF));
2127     AddAddress(SPDie, DW_AT_frame_base, Location);
2128
2129     ConstructScope(RootScope, 0, 0, SPDie, Unit);
2130   }
2131
2132   /// ConstructDefaultScope - Construct a default scope for the subprogram.
2133   ///
2134   void ConstructDefaultScope(MachineFunction *MF) {
2135     // Find the correct subprogram descriptor.
2136     std::vector<SubprogramDesc *> Subprograms;
2137     MMI->getAnchoredDescriptors<SubprogramDesc>(*M, Subprograms);
2138
2139     for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2140       SubprogramDesc *SPD = Subprograms[i];
2141
2142       if (SPD->getName() == MF->getFunction()->getName()) {
2143         // Get the compile unit context.
2144         CompileUnit *Unit = GetBaseCompileUnit();
2145
2146         // Get the subprogram die.
2147         DIE *SPDie = Unit->getDieMapSlotFor(SPD);
2148         assert(SPDie && "Missing subprogram descriptor");
2149
2150         // Add the function bounds.
2151         AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
2152                  DWLabel("func_begin", SubprogramCount));
2153         AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
2154                  DWLabel("func_end", SubprogramCount));
2155
2156         MachineLocation Location(RI->getFrameRegister(*MF));
2157         AddAddress(SPDie, DW_AT_frame_base, Location);
2158         return;
2159       }
2160     }
2161 #if 0
2162     // FIXME: This is causing an abort because C++ mangled names are compared
2163     // with their unmangled counterparts. See PR2885. Don't do this assert.
2164     assert(0 && "Couldn't find DIE for machine function!");
2165 #endif
2166   }
2167
2168   /// EmitInitial - Emit initial Dwarf declarations.  This is necessary for cc
2169   /// tools to recognize the object file contains Dwarf information.
2170   void EmitInitial() {
2171     // Check to see if we already emitted intial headers.
2172     if (didInitial) return;
2173     didInitial = true;
2174
2175     // Dwarf sections base addresses.
2176     if (TAI->doesDwarfRequireFrameSection()) {
2177       Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2178       EmitLabel("section_debug_frame", 0);
2179     }
2180     Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2181     EmitLabel("section_info", 0);
2182     Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2183     EmitLabel("section_abbrev", 0);
2184     Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2185     EmitLabel("section_aranges", 0);
2186     Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2187     EmitLabel("section_macinfo", 0);
2188     Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2189     EmitLabel("section_line", 0);
2190     Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2191     EmitLabel("section_loc", 0);
2192     Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2193     EmitLabel("section_pubnames", 0);
2194     Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2195     EmitLabel("section_str", 0);
2196     Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2197     EmitLabel("section_ranges", 0);
2198
2199     Asm->SwitchToSection(TAI->getTextSection());
2200     EmitLabel("text_begin", 0);
2201     Asm->SwitchToSection(TAI->getDataSection());
2202     EmitLabel("data_begin", 0);
2203   }
2204
2205   /// EmitDIE - Recusively Emits a debug information entry.
2206   ///
2207   void EmitDIE(DIE *Die) {
2208     // Get the abbreviation for this DIE.
2209     unsigned AbbrevNumber = Die->getAbbrevNumber();
2210     const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2211
2212     Asm->EOL();
2213
2214     // Emit the code (index) for the abbreviation.
2215     Asm->EmitULEB128Bytes(AbbrevNumber);
2216
2217     if (VerboseAsm)
2218       Asm->EOL(std::string("Abbrev [" +
2219                            utostr(AbbrevNumber) +
2220                            "] 0x" + utohexstr(Die->getOffset()) +
2221                            ":0x" + utohexstr(Die->getSize()) + " " +
2222                            TagString(Abbrev->getTag())));
2223     else
2224       Asm->EOL();
2225
2226     SmallVector<DIEValue*, 32> &Values = Die->getValues();
2227     const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2228
2229     // Emit the DIE attribute values.
2230     for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2231       unsigned Attr = AbbrevData[i].getAttribute();
2232       unsigned Form = AbbrevData[i].getForm();
2233       assert(Form && "Too many attributes for DIE (check abbreviation)");
2234
2235       switch (Attr) {
2236       case DW_AT_sibling: {
2237         Asm->EmitInt32(Die->SiblingOffset());
2238         break;
2239       }
2240       default: {
2241         // Emit an attribute using the defined form.
2242         Values[i]->EmitValue(*this, Form);
2243         break;
2244       }
2245       }
2246
2247       Asm->EOL(AttributeString(Attr));
2248     }
2249
2250     // Emit the DIE children if any.
2251     if (Abbrev->getChildrenFlag() == DW_CHILDREN_yes) {
2252       const std::vector<DIE *> &Children = Die->getChildren();
2253
2254       for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2255         EmitDIE(Children[j]);
2256       }
2257
2258       Asm->EmitInt8(0); Asm->EOL("End Of Children Mark");
2259     }
2260   }
2261
2262   /// SizeAndOffsetDie - Compute the size and offset of a DIE.
2263   ///
2264   unsigned SizeAndOffsetDie(DIE *Die, unsigned Offset, bool Last) {
2265     // Get the children.
2266     const std::vector<DIE *> &Children = Die->getChildren();
2267
2268     // If not last sibling and has children then add sibling offset attribute.
2269     if (!Last && !Children.empty()) Die->AddSiblingOffset();
2270
2271     // Record the abbreviation.
2272     AssignAbbrevNumber(Die->getAbbrev());
2273
2274     // Get the abbreviation for this DIE.
2275     unsigned AbbrevNumber = Die->getAbbrevNumber();
2276     const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
2277
2278     // Set DIE offset
2279     Die->setOffset(Offset);
2280
2281     // Start the size with the size of abbreviation code.
2282     Offset += TargetAsmInfo::getULEB128Size(AbbrevNumber);
2283
2284     const SmallVector<DIEValue*, 32> &Values = Die->getValues();
2285     const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
2286
2287     // Size the DIE attribute values.
2288     for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2289       // Size attribute value.
2290       Offset += Values[i]->SizeOf(*this, AbbrevData[i].getForm());
2291     }
2292
2293     // Size the DIE children if any.
2294     if (!Children.empty()) {
2295       assert(Abbrev->getChildrenFlag() == DW_CHILDREN_yes &&
2296              "Children flag not set");
2297
2298       for (unsigned j = 0, M = Children.size(); j < M; ++j) {
2299         Offset = SizeAndOffsetDie(Children[j], Offset, (j + 1) == M);
2300       }
2301
2302       // End of children marker.
2303       Offset += sizeof(int8_t);
2304     }
2305
2306     Die->setSize(Offset - Die->getOffset());
2307     return Offset;
2308   }
2309
2310   /// SizeAndOffsets - Compute the size and offset of all the DIEs.
2311   ///
2312   void SizeAndOffsets() {
2313     // Process base compile unit.
2314     CompileUnit *Unit = GetBaseCompileUnit();
2315     // Compute size of compile unit header
2316     unsigned Offset = sizeof(int32_t) + // Length of Compilation Unit Info
2317                       sizeof(int16_t) + // DWARF version number
2318                       sizeof(int32_t) + // Offset Into Abbrev. Section
2319                       sizeof(int8_t);   // Pointer Size (in bytes)
2320     SizeAndOffsetDie(Unit->getDie(), Offset, true);
2321   }
2322
2323   /// EmitDebugInfo - Emit the debug info section.
2324   ///
2325   void EmitDebugInfo() {
2326     // Start debug info section.
2327     Asm->SwitchToDataSection(TAI->getDwarfInfoSection());
2328
2329     CompileUnit *Unit = GetBaseCompileUnit();
2330     DIE *Die = Unit->getDie();
2331     // Emit the compile units header.
2332     EmitLabel("info_begin", Unit->getID());
2333     // Emit size of content not including length itself
2334     unsigned ContentSize = Die->getSize() +
2335                            sizeof(int16_t) + // DWARF version number
2336                            sizeof(int32_t) + // Offset Into Abbrev. Section
2337                            sizeof(int8_t) +  // Pointer Size (in bytes)
2338                            sizeof(int32_t);  // FIXME - extra pad for gdb bug.
2339
2340     Asm->EmitInt32(ContentSize);  Asm->EOL("Length of Compilation Unit Info");
2341     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2342     EmitSectionOffset("abbrev_begin", "section_abbrev", 0, 0, true, false);
2343     Asm->EOL("Offset Into Abbrev. Section");
2344     Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Address Size (in bytes)");
2345
2346     EmitDIE(Die);
2347     // FIXME - extra padding for gdb bug.
2348     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2349     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2350     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2351     Asm->EmitInt8(0); Asm->EOL("Extra Pad For GDB");
2352     EmitLabel("info_end", Unit->getID());
2353
2354     Asm->EOL();
2355   }
2356
2357   /// EmitAbbreviations - Emit the abbreviation section.
2358   ///
2359   void EmitAbbreviations() const {
2360     // Check to see if it is worth the effort.
2361     if (!Abbreviations.empty()) {
2362       // Start the debug abbrev section.
2363       Asm->SwitchToDataSection(TAI->getDwarfAbbrevSection());
2364
2365       EmitLabel("abbrev_begin", 0);
2366
2367       // For each abbrevation.
2368       for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2369         // Get abbreviation data
2370         const DIEAbbrev *Abbrev = Abbreviations[i];
2371
2372         // Emit the abbrevations code (base 1 index.)
2373         Asm->EmitULEB128Bytes(Abbrev->getNumber());
2374         Asm->EOL("Abbreviation Code");
2375
2376         // Emit the abbreviations data.
2377         Abbrev->Emit(*this);
2378
2379         Asm->EOL();
2380       }
2381
2382       // Mark end of abbreviations.
2383       Asm->EmitULEB128Bytes(0); Asm->EOL("EOM(3)");
2384
2385       EmitLabel("abbrev_end", 0);
2386
2387       Asm->EOL();
2388     }
2389   }
2390
2391   /// EmitEndOfLineMatrix - Emit the last address of the section and the end of
2392   /// the line matrix.
2393   ///
2394   void EmitEndOfLineMatrix(unsigned SectionEnd) {
2395     // Define last address of section.
2396     Asm->EmitInt8(0); Asm->EOL("Extended Op");
2397     Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2398     Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2399     EmitReference("section_end", SectionEnd); Asm->EOL("Section end label");
2400
2401     // Mark end of matrix.
2402     Asm->EmitInt8(0); Asm->EOL("DW_LNE_end_sequence");
2403     Asm->EmitULEB128Bytes(1); Asm->EOL();
2404     Asm->EmitInt8(1); Asm->EOL();
2405   }
2406
2407   /// EmitDebugLines - Emit source line information.
2408   ///
2409   void EmitDebugLines() {
2410     // If the target is using .loc/.file, the assembler will be emitting the
2411     // .debug_line table automatically.
2412     if (TAI->hasDotLocAndDotFile())
2413       return;
2414
2415     // Minimum line delta, thus ranging from -10..(255-10).
2416     const int MinLineDelta = -(DW_LNS_fixed_advance_pc + 1);
2417     // Maximum line delta, thus ranging from -10..(255-10).
2418     const int MaxLineDelta = 255 + MinLineDelta;
2419
2420     // Start the dwarf line section.
2421     Asm->SwitchToDataSection(TAI->getDwarfLineSection());
2422
2423     // Construct the section header.
2424
2425     EmitDifference("line_end", 0, "line_begin", 0, true);
2426     Asm->EOL("Length of Source Line Info");
2427     EmitLabel("line_begin", 0);
2428
2429     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF version number");
2430
2431     EmitDifference("line_prolog_end", 0, "line_prolog_begin", 0, true);
2432     Asm->EOL("Prolog Length");
2433     EmitLabel("line_prolog_begin", 0);
2434
2435     Asm->EmitInt8(1); Asm->EOL("Minimum Instruction Length");
2436
2437     Asm->EmitInt8(1); Asm->EOL("Default is_stmt_start flag");
2438
2439     Asm->EmitInt8(MinLineDelta); Asm->EOL("Line Base Value (Special Opcodes)");
2440
2441     Asm->EmitInt8(MaxLineDelta); Asm->EOL("Line Range Value (Special Opcodes)");
2442
2443     Asm->EmitInt8(-MinLineDelta); Asm->EOL("Special Opcode Base");
2444
2445     // Line number standard opcode encodings argument count
2446     Asm->EmitInt8(0); Asm->EOL("DW_LNS_copy arg count");
2447     Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_pc arg count");
2448     Asm->EmitInt8(1); Asm->EOL("DW_LNS_advance_line arg count");
2449     Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_file arg count");
2450     Asm->EmitInt8(1); Asm->EOL("DW_LNS_set_column arg count");
2451     Asm->EmitInt8(0); Asm->EOL("DW_LNS_negate_stmt arg count");
2452     Asm->EmitInt8(0); Asm->EOL("DW_LNS_set_basic_block arg count");
2453     Asm->EmitInt8(0); Asm->EOL("DW_LNS_const_add_pc arg count");
2454     Asm->EmitInt8(1); Asm->EOL("DW_LNS_fixed_advance_pc arg count");
2455
2456     const UniqueVector<std::string> &Directories = MMI->getDirectories();
2457     const UniqueVector<SourceFileInfo> &SourceFiles = MMI->getSourceFiles();
2458
2459     // Emit directories.
2460     for (unsigned DirectoryID = 1, NDID = Directories.size();
2461                   DirectoryID <= NDID; ++DirectoryID) {
2462       Asm->EmitString(Directories[DirectoryID]); Asm->EOL("Directory");
2463     }
2464     Asm->EmitInt8(0); Asm->EOL("End of directories");
2465
2466     // Emit files.
2467     for (unsigned SourceID = 1, NSID = SourceFiles.size();
2468                  SourceID <= NSID; ++SourceID) {
2469       const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2470       Asm->EmitString(SourceFile.getName());
2471       Asm->EOL("Source");
2472       Asm->EmitULEB128Bytes(SourceFile.getDirectoryID());
2473       Asm->EOL("Directory #");
2474       Asm->EmitULEB128Bytes(0);
2475       Asm->EOL("Mod date");
2476       Asm->EmitULEB128Bytes(0);
2477       Asm->EOL("File size");
2478     }
2479     Asm->EmitInt8(0); Asm->EOL("End of files");
2480
2481     EmitLabel("line_prolog_end", 0);
2482
2483     // A sequence for each text section.
2484     unsigned SecSrcLinesSize = SectionSourceLines.size();
2485
2486     for (unsigned j = 0; j < SecSrcLinesSize; ++j) {
2487       // Isolate current sections line info.
2488       const std::vector<SourceLineInfo> &LineInfos = SectionSourceLines[j];
2489
2490       if (VerboseAsm) {
2491         const Section* S = SectionMap[j + 1];
2492         Asm->EOL(std::string("Section ") + S->getName());
2493       } else
2494         Asm->EOL();
2495
2496       // Dwarf assumes we start with first line of first source file.
2497       unsigned Source = 1;
2498       unsigned Line = 1;
2499
2500       // Construct rows of the address, source, line, column matrix.
2501       for (unsigned i = 0, N = LineInfos.size(); i < N; ++i) {
2502         const SourceLineInfo &LineInfo = LineInfos[i];
2503         unsigned LabelID = MMI->MappedLabel(LineInfo.getLabelID());
2504         if (!LabelID) continue;
2505
2506         unsigned SourceID = LineInfo.getSourceID();
2507         const SourceFileInfo &SourceFile = SourceFiles[SourceID];
2508         unsigned DirectoryID = SourceFile.getDirectoryID();
2509         if (VerboseAsm)
2510           Asm->EOL(Directories[DirectoryID]
2511                    + SourceFile.getName()
2512                    + ":"
2513                    + utostr_32(LineInfo.getLine()));
2514         else
2515           Asm->EOL();
2516
2517         // Define the line address.
2518         Asm->EmitInt8(0); Asm->EOL("Extended Op");
2519         Asm->EmitInt8(TD->getPointerSize() + 1); Asm->EOL("Op size");
2520         Asm->EmitInt8(DW_LNE_set_address); Asm->EOL("DW_LNE_set_address");
2521         EmitReference("label",  LabelID); Asm->EOL("Location label");
2522
2523         // If change of source, then switch to the new source.
2524         if (Source != LineInfo.getSourceID()) {
2525           Source = LineInfo.getSourceID();
2526           Asm->EmitInt8(DW_LNS_set_file); Asm->EOL("DW_LNS_set_file");
2527           Asm->EmitULEB128Bytes(Source); Asm->EOL("New Source");
2528         }
2529
2530         // If change of line.
2531         if (Line != LineInfo.getLine()) {
2532           // Determine offset.
2533           int Offset = LineInfo.getLine() - Line;
2534           int Delta = Offset - MinLineDelta;
2535
2536           // Update line.
2537           Line = LineInfo.getLine();
2538
2539           // If delta is small enough and in range...
2540           if (Delta >= 0 && Delta < (MaxLineDelta - 1)) {
2541             // ... then use fast opcode.
2542             Asm->EmitInt8(Delta - MinLineDelta); Asm->EOL("Line Delta");
2543           } else {
2544             // ... otherwise use long hand.
2545             Asm->EmitInt8(DW_LNS_advance_line); Asm->EOL("DW_LNS_advance_line");
2546             Asm->EmitSLEB128Bytes(Offset); Asm->EOL("Line Offset");
2547             Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2548           }
2549         } else {
2550           // Copy the previous row (different address or source)
2551           Asm->EmitInt8(DW_LNS_copy); Asm->EOL("DW_LNS_copy");
2552         }
2553       }
2554
2555       EmitEndOfLineMatrix(j + 1);
2556     }
2557
2558     if (SecSrcLinesSize == 0)
2559       // Because we're emitting a debug_line section, we still need a line
2560       // table. The linker and friends expect it to exist. If there's nothing to
2561       // put into it, emit an empty table.
2562       EmitEndOfLineMatrix(1);
2563
2564     EmitLabel("line_end", 0);
2565
2566     Asm->EOL();
2567   }
2568
2569   /// EmitCommonDebugFrame - Emit common frame info into a debug frame section.
2570   ///
2571   void EmitCommonDebugFrame() {
2572     if (!TAI->doesDwarfRequireFrameSection())
2573       return;
2574
2575     int stackGrowth =
2576         Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
2577           TargetFrameInfo::StackGrowsUp ?
2578         TD->getPointerSize() : -TD->getPointerSize();
2579
2580     // Start the dwarf frame section.
2581     Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2582
2583     EmitLabel("debug_frame_common", 0);
2584     EmitDifference("debug_frame_common_end", 0,
2585                    "debug_frame_common_begin", 0, true);
2586     Asm->EOL("Length of Common Information Entry");
2587
2588     EmitLabel("debug_frame_common_begin", 0);
2589     Asm->EmitInt32((int)DW_CIE_ID);
2590     Asm->EOL("CIE Identifier Tag");
2591     Asm->EmitInt8(DW_CIE_VERSION);
2592     Asm->EOL("CIE Version");
2593     Asm->EmitString("");
2594     Asm->EOL("CIE Augmentation");
2595     Asm->EmitULEB128Bytes(1);
2596     Asm->EOL("CIE Code Alignment Factor");
2597     Asm->EmitSLEB128Bytes(stackGrowth);
2598     Asm->EOL("CIE Data Alignment Factor");
2599     Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), false));
2600     Asm->EOL("CIE RA Column");
2601
2602     std::vector<MachineMove> Moves;
2603     RI->getInitialFrameState(Moves);
2604
2605     EmitFrameMoves(NULL, 0, Moves, false);
2606
2607     Asm->EmitAlignment(2, 0, 0, false);
2608     EmitLabel("debug_frame_common_end", 0);
2609
2610     Asm->EOL();
2611   }
2612
2613   /// EmitFunctionDebugFrame - Emit per function frame info into a debug frame
2614   /// section.
2615   void EmitFunctionDebugFrame(const FunctionDebugFrameInfo &DebugFrameInfo) {
2616     if (!TAI->doesDwarfRequireFrameSection())
2617       return;
2618
2619     // Start the dwarf frame section.
2620     Asm->SwitchToDataSection(TAI->getDwarfFrameSection());
2621
2622     EmitDifference("debug_frame_end", DebugFrameInfo.Number,
2623                    "debug_frame_begin", DebugFrameInfo.Number, true);
2624     Asm->EOL("Length of Frame Information Entry");
2625
2626     EmitLabel("debug_frame_begin", DebugFrameInfo.Number);
2627
2628     EmitSectionOffset("debug_frame_common", "section_debug_frame",
2629                       0, 0, true, false);
2630     Asm->EOL("FDE CIE offset");
2631
2632     EmitReference("func_begin", DebugFrameInfo.Number);
2633     Asm->EOL("FDE initial location");
2634     EmitDifference("func_end", DebugFrameInfo.Number,
2635                    "func_begin", DebugFrameInfo.Number);
2636     Asm->EOL("FDE address range");
2637
2638     EmitFrameMoves("func_begin", DebugFrameInfo.Number, DebugFrameInfo.Moves, false);
2639
2640     Asm->EmitAlignment(2, 0, 0, false);
2641     EmitLabel("debug_frame_end", DebugFrameInfo.Number);
2642
2643     Asm->EOL();
2644   }
2645
2646   /// EmitDebugPubNames - Emit visible names into a debug pubnames section.
2647   ///
2648   void EmitDebugPubNames() {
2649     // Start the dwarf pubnames section.
2650     Asm->SwitchToDataSection(TAI->getDwarfPubNamesSection());
2651
2652     CompileUnit *Unit = GetBaseCompileUnit();
2653
2654     EmitDifference("pubnames_end", Unit->getID(),
2655                    "pubnames_begin", Unit->getID(), true);
2656     Asm->EOL("Length of Public Names Info");
2657
2658     EmitLabel("pubnames_begin", Unit->getID());
2659
2660     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("DWARF Version");
2661
2662     EmitSectionOffset("info_begin", "section_info",
2663                       Unit->getID(), 0, true, false);
2664     Asm->EOL("Offset of Compilation Unit Info");
2665
2666     EmitDifference("info_end", Unit->getID(), "info_begin", Unit->getID(),true);
2667     Asm->EOL("Compilation Unit Length");
2668
2669     std::map<std::string, DIE *> &Globals = Unit->getGlobals();
2670
2671     for (std::map<std::string, DIE *>::iterator GI = Globals.begin(),
2672                                                 GE = Globals.end();
2673          GI != GE; ++GI) {
2674       const std::string &Name = GI->first;
2675       DIE * Entity = GI->second;
2676
2677       Asm->EmitInt32(Entity->getOffset()); Asm->EOL("DIE offset");
2678       Asm->EmitString(Name); Asm->EOL("External Name");
2679     }
2680
2681     Asm->EmitInt32(0); Asm->EOL("End Mark");
2682     EmitLabel("pubnames_end", Unit->getID());
2683
2684     Asm->EOL();
2685   }
2686
2687   /// EmitDebugStr - Emit visible names into a debug str section.
2688   ///
2689   void EmitDebugStr() {
2690     // Check to see if it is worth the effort.
2691     if (!StringPool.empty()) {
2692       // Start the dwarf str section.
2693       Asm->SwitchToDataSection(TAI->getDwarfStrSection());
2694
2695       // For each of strings in the string pool.
2696       for (unsigned StringID = 1, N = StringPool.size();
2697            StringID <= N; ++StringID) {
2698         // Emit a label for reference from debug information entries.
2699         EmitLabel("string", StringID);
2700         // Emit the string itself.
2701         const std::string &String = StringPool[StringID];
2702         Asm->EmitString(String); Asm->EOL();
2703       }
2704
2705       Asm->EOL();
2706     }
2707   }
2708
2709   /// EmitDebugLoc - Emit visible names into a debug loc section.
2710   ///
2711   void EmitDebugLoc() {
2712     // Start the dwarf loc section.
2713     Asm->SwitchToDataSection(TAI->getDwarfLocSection());
2714
2715     Asm->EOL();
2716   }
2717
2718   /// EmitDebugARanges - Emit visible names into a debug aranges section.
2719   ///
2720   void EmitDebugARanges() {
2721     // Start the dwarf aranges section.
2722     Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
2723
2724     // FIXME - Mock up
2725 #if 0
2726     CompileUnit *Unit = GetBaseCompileUnit();
2727
2728     // Don't include size of length
2729     Asm->EmitInt32(0x1c); Asm->EOL("Length of Address Ranges Info");
2730
2731     Asm->EmitInt16(DWARF_VERSION); Asm->EOL("Dwarf Version");
2732
2733     EmitReference("info_begin", Unit->getID());
2734     Asm->EOL("Offset of Compilation Unit Info");
2735
2736     Asm->EmitInt8(TD->getPointerSize()); Asm->EOL("Size of Address");
2737
2738     Asm->EmitInt8(0); Asm->EOL("Size of Segment Descriptor");
2739
2740     Asm->EmitInt16(0);  Asm->EOL("Pad (1)");
2741     Asm->EmitInt16(0);  Asm->EOL("Pad (2)");
2742
2743     // Range 1
2744     EmitReference("text_begin", 0); Asm->EOL("Address");
2745     EmitDifference("text_end", 0, "text_begin", 0, true); Asm->EOL("Length");
2746
2747     Asm->EmitInt32(0); Asm->EOL("EOM (1)");
2748     Asm->EmitInt32(0); Asm->EOL("EOM (2)");
2749 #endif
2750
2751     Asm->EOL();
2752   }
2753
2754   /// EmitDebugRanges - Emit visible names into a debug ranges section.
2755   ///
2756   void EmitDebugRanges() {
2757     // Start the dwarf ranges section.
2758     Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
2759
2760     Asm->EOL();
2761   }
2762
2763   /// EmitDebugMacInfo - Emit visible names into a debug macinfo section.
2764   ///
2765   void EmitDebugMacInfo() {
2766     // Start the dwarf macinfo section.
2767     Asm->SwitchToDataSection(TAI->getDwarfMacInfoSection());
2768
2769     Asm->EOL();
2770   }
2771
2772   /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
2773   /// header file.
2774   void ConstructCompileUnitDIEs() {
2775     const UniqueVector<CompileUnitDesc *> CUW = MMI->getCompileUnits();
2776
2777     for (unsigned i = 1, N = CUW.size(); i <= N; ++i) {
2778       unsigned ID = MMI->RecordSource(CUW[i]);
2779       CompileUnit *Unit = NewCompileUnit(CUW[i], ID);
2780       CompileUnits.push_back(Unit);
2781     }
2782   }
2783
2784   /// ConstructGlobalDIEs - Create DIEs for each of the externally visible
2785   /// global variables.
2786   void ConstructGlobalDIEs() {
2787     std::vector<GlobalVariableDesc *> GlobalVariables;
2788     MMI->getAnchoredDescriptors<GlobalVariableDesc>(*M, GlobalVariables);
2789
2790     for (unsigned i = 0, N = GlobalVariables.size(); i < N; ++i) {
2791       GlobalVariableDesc *GVD = GlobalVariables[i];
2792       NewGlobalVariable(GVD);
2793     }
2794   }
2795
2796   /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
2797   /// subprograms.
2798   void ConstructSubprogramDIEs() {
2799     std::vector<SubprogramDesc *> Subprograms;
2800     MMI->getAnchoredDescriptors<SubprogramDesc>(*M, Subprograms);
2801
2802     for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
2803       SubprogramDesc *SPD = Subprograms[i];
2804       NewSubprogram(SPD);
2805     }
2806   }
2807
2808 public:
2809   //===--------------------------------------------------------------------===//
2810   // Main entry points.
2811   //
2812   DwarfDebug(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
2813   : Dwarf(OS, A, T, "dbg")
2814   , CompileUnits()
2815   , AbbreviationsSet(InitAbbreviationsSetSize)
2816   , Abbreviations()
2817   , ValuesSet(InitValuesSetSize)
2818   , Values()
2819   , StringPool()
2820   , DescToUnitMap()
2821   , SectionMap()
2822   , SectionSourceLines()
2823   , didInitial(false)
2824   , shouldEmit(false)
2825   {
2826   }
2827   virtual ~DwarfDebug() {
2828     for (unsigned i = 0, N = CompileUnits.size(); i < N; ++i)
2829       delete CompileUnits[i];
2830     for (unsigned j = 0, M = Values.size(); j < M; ++j)
2831       delete Values[j];
2832   }
2833
2834   /// SetModuleInfo - Set machine module information when it's known that pass
2835   /// manager has created it.  Set by the target AsmPrinter.
2836   void SetModuleInfo(MachineModuleInfo *mmi) {
2837     // Make sure initial declarations are made.
2838     if (!MMI && mmi->hasDebugInfo()) {
2839       MMI = mmi;
2840       shouldEmit = true;
2841
2842       // Create all the compile unit DIEs.
2843       ConstructCompileUnitDIEs();
2844
2845       // Create DIEs for each of the externally visible global variables.
2846       ConstructGlobalDIEs();
2847
2848       // Create DIEs for each of the externally visible subprograms.
2849       ConstructSubprogramDIEs();
2850
2851       // Prime section data.
2852       SectionMap.insert(TAI->getTextSection());
2853
2854       // Print out .file directives to specify files for .loc directives. These
2855       // are printed out early so that they precede any .loc directives.
2856       if (TAI->hasDotLocAndDotFile()) {
2857         const UniqueVector<SourceFileInfo> &SourceFiles = MMI->getSourceFiles();
2858         const UniqueVector<std::string> &Directories = MMI->getDirectories();
2859         for (unsigned i = 1, e = SourceFiles.size(); i <= e; ++i) {
2860           sys::Path FullPath(Directories[SourceFiles[i].getDirectoryID()]);
2861           bool AppendOk = FullPath.appendComponent(SourceFiles[i].getName());
2862           assert(AppendOk && "Could not append filename to directory!");
2863           AppendOk = false;
2864           Asm->EmitFile(i, FullPath.toString());
2865           Asm->EOL();
2866         }
2867       }
2868
2869       // Emit initial sections
2870       EmitInitial();
2871     }
2872   }
2873
2874   /// BeginModule - Emit all Dwarf sections that should come prior to the
2875   /// content.
2876   void BeginModule(Module *M) {
2877     this->M = M;
2878   }
2879
2880   /// EndModule - Emit all Dwarf sections that should come after the content.
2881   ///
2882   void EndModule() {
2883     if (!ShouldEmitDwarf()) return;
2884
2885     // Standard sections final addresses.
2886     Asm->SwitchToSection(TAI->getTextSection());
2887     EmitLabel("text_end", 0);
2888     Asm->SwitchToSection(TAI->getDataSection());
2889     EmitLabel("data_end", 0);
2890
2891     // End text sections.
2892     for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
2893       Asm->SwitchToSection(SectionMap[i]);
2894       EmitLabel("section_end", i);
2895     }
2896
2897     // Emit common frame information.
2898     EmitCommonDebugFrame();
2899
2900     // Emit function debug frame information
2901     for (std::vector<FunctionDebugFrameInfo>::iterator I = DebugFrames.begin(),
2902            E = DebugFrames.end(); I != E; ++I)
2903       EmitFunctionDebugFrame(*I);
2904
2905     // Compute DIE offsets and sizes.
2906     SizeAndOffsets();
2907
2908     // Emit all the DIEs into a debug info section
2909     EmitDebugInfo();
2910
2911     // Corresponding abbreviations into a abbrev section.
2912     EmitAbbreviations();
2913
2914     // Emit source line correspondence into a debug line section.
2915     EmitDebugLines();
2916
2917     // Emit info into a debug pubnames section.
2918     EmitDebugPubNames();
2919
2920     // Emit info into a debug str section.
2921     EmitDebugStr();
2922
2923     // Emit info into a debug loc section.
2924     EmitDebugLoc();
2925
2926     // Emit info into a debug aranges section.
2927     EmitDebugARanges();
2928
2929     // Emit info into a debug ranges section.
2930     EmitDebugRanges();
2931
2932     // Emit info into a debug macinfo section.
2933     EmitDebugMacInfo();
2934   }
2935
2936   /// BeginFunction - Gather pre-function debug information.  Assumes being
2937   /// emitted immediately after the function entry point.
2938   void BeginFunction(MachineFunction *MF) {
2939     this->MF = MF;
2940
2941     if (!ShouldEmitDwarf()) return;
2942
2943     // Begin accumulating function debug information.
2944     MMI->BeginFunction(MF);
2945
2946     // Assumes in correct section after the entry point.
2947     EmitLabel("func_begin", ++SubprogramCount);
2948
2949     // Emit label for the implicitly defined dbg.stoppoint at the start of
2950     // the function.
2951     const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
2952     if (!LineInfos.empty()) {
2953       const SourceLineInfo &LineInfo = LineInfos[0];
2954       Asm->printLabel(LineInfo.getLabelID());
2955     }
2956   }
2957
2958   /// EndFunction - Gather and emit post-function debug information.
2959   ///
2960   void EndFunction(MachineFunction *MF) {
2961     if (!ShouldEmitDwarf()) return;
2962
2963     // Define end label for subprogram.
2964     EmitLabel("func_end", SubprogramCount);
2965
2966     // Get function line info.
2967     const std::vector<SourceLineInfo> &LineInfos = MMI->getSourceLines();
2968
2969     if (!LineInfos.empty()) {
2970       // Get section line info.
2971       unsigned ID = SectionMap.insert(Asm->CurrentSection_);
2972       if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
2973       std::vector<SourceLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
2974       // Append the function info to section info.
2975       SectionLineInfos.insert(SectionLineInfos.end(),
2976                               LineInfos.begin(), LineInfos.end());
2977     }
2978
2979     // Construct scopes for subprogram.
2980     if (MMI->getRootScope())
2981       ConstructRootScope(MMI->getRootScope());
2982     else
2983       // FIXME: This is wrong. We are essentially getting past a problem with
2984       // debug information not being able to handle unreachable blocks that have
2985       // debug information in them. In particular, those unreachable blocks that
2986       // have "region end" info in them. That situation results in the "root
2987       // scope" not being created. If that's the case, then emit a "default"
2988       // scope, i.e., one that encompasses the whole function. This isn't
2989       // desirable. And a better way of handling this (and all of the debugging
2990       // information) needs to be explored.
2991       ConstructDefaultScope(MF);
2992
2993     DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
2994                                                  MMI->getFrameMoves()));
2995   }
2996 };
2997
2998 //===----------------------------------------------------------------------===//
2999 /// DwarfException - Emits Dwarf exception handling directives.
3000 ///
3001 class DwarfException : public Dwarf  {
3002
3003 private:
3004   struct FunctionEHFrameInfo {
3005     std::string FnName;
3006     unsigned Number;
3007     unsigned PersonalityIndex;
3008     bool hasCalls;
3009     bool hasLandingPads;
3010     std::vector<MachineMove> Moves;
3011     const Function * function;
3012
3013     FunctionEHFrameInfo(const std::string &FN, unsigned Num, unsigned P,
3014                         bool hC, bool hL,
3015                         const std::vector<MachineMove> &M,
3016                         const Function *f):
3017       FnName(FN), Number(Num), PersonalityIndex(P),
3018       hasCalls(hC), hasLandingPads(hL), Moves(M), function (f) { }
3019   };
3020
3021   std::vector<FunctionEHFrameInfo> EHFrames;
3022
3023   /// shouldEmitTable - Per-function flag to indicate if EH tables should
3024   /// be emitted.
3025   bool shouldEmitTable;
3026
3027   /// shouldEmitMoves - Per-function flag to indicate if frame moves info
3028   /// should be emitted.
3029   bool shouldEmitMoves;
3030
3031   /// shouldEmitTableModule - Per-module flag to indicate if EH tables
3032   /// should be emitted.
3033   bool shouldEmitTableModule;
3034
3035   /// shouldEmitFrameModule - Per-module flag to indicate if frame moves
3036   /// should be emitted.
3037   bool shouldEmitMovesModule;
3038
3039   /// EmitCommonEHFrame - Emit the common eh unwind frame.
3040   ///
3041   void EmitCommonEHFrame(const Function *Personality, unsigned Index) {
3042     // Size and sign of stack growth.
3043     int stackGrowth =
3044         Asm->TM.getFrameInfo()->getStackGrowthDirection() ==
3045           TargetFrameInfo::StackGrowsUp ?
3046         TD->getPointerSize() : -TD->getPointerSize();
3047
3048     // Begin eh frame section.
3049     Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3050
3051     if (!TAI->doesRequireNonLocalEHFrameLabel())
3052       O << TAI->getEHGlobalPrefix();
3053     O << "EH_frame" << Index << ":\n";
3054     EmitLabel("section_eh_frame", Index);
3055
3056     // Define base labels.
3057     EmitLabel("eh_frame_common", Index);
3058
3059     // Define the eh frame length.
3060     EmitDifference("eh_frame_common_end", Index,
3061                    "eh_frame_common_begin", Index, true);
3062     Asm->EOL("Length of Common Information Entry");
3063
3064     // EH frame header.
3065     EmitLabel("eh_frame_common_begin", Index);
3066     Asm->EmitInt32((int)0);
3067     Asm->EOL("CIE Identifier Tag");
3068     Asm->EmitInt8(DW_CIE_VERSION);
3069     Asm->EOL("CIE Version");
3070
3071     // The personality presence indicates that language specific information
3072     // will show up in the eh frame.
3073     Asm->EmitString(Personality ? "zPLR" : "zR");
3074     Asm->EOL("CIE Augmentation");
3075
3076     // Round out reader.
3077     Asm->EmitULEB128Bytes(1);
3078     Asm->EOL("CIE Code Alignment Factor");
3079     Asm->EmitSLEB128Bytes(stackGrowth);
3080     Asm->EOL("CIE Data Alignment Factor");
3081     Asm->EmitInt8(RI->getDwarfRegNum(RI->getRARegister(), true));
3082     Asm->EOL("CIE Return Address Column");
3083
3084     // If there is a personality, we need to indicate the functions location.
3085     if (Personality) {
3086       Asm->EmitULEB128Bytes(7);
3087       Asm->EOL("Augmentation Size");
3088
3089       if (TAI->getNeedsIndirectEncoding()) {
3090         Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4 | DW_EH_PE_indirect);
3091         Asm->EOL("Personality (pcrel sdata4 indirect)");
3092       } else {
3093         Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3094         Asm->EOL("Personality (pcrel sdata4)");
3095       }
3096
3097       PrintRelDirective(true);
3098       O << TAI->getPersonalityPrefix();
3099       Asm->EmitExternalGlobal((const GlobalVariable *)(Personality));
3100       O << TAI->getPersonalitySuffix();
3101       if (strcmp(TAI->getPersonalitySuffix(), "+4@GOTPCREL"))
3102         O << "-" << TAI->getPCSymbol();
3103       Asm->EOL("Personality");
3104
3105       Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3106       Asm->EOL("LSDA Encoding (pcrel sdata4)");
3107
3108       if (TAI->doesFDEEncodingRequireSData4()) {
3109         Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3110         Asm->EOL("FDE Encoding (pcrel sdata4)");
3111       } else {
3112         Asm->EmitInt8(DW_EH_PE_pcrel);
3113         Asm->EOL("FDE Encoding (pcrel)");
3114       }
3115    } else {
3116       Asm->EmitULEB128Bytes(1);
3117       Asm->EOL("Augmentation Size");
3118
3119       if (TAI->doesFDEEncodingRequireSData4()) {
3120         Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
3121         Asm->EOL("FDE Encoding (pcrel sdata4)");
3122       } else {
3123         Asm->EmitInt8(DW_EH_PE_pcrel);
3124         Asm->EOL("FDE Encoding (pcrel)");
3125       }
3126     }
3127
3128     // Indicate locations of general callee saved registers in frame.
3129     std::vector<MachineMove> Moves;
3130     RI->getInitialFrameState(Moves);
3131     EmitFrameMoves(NULL, 0, Moves, true);
3132
3133     // On Darwin the linker honors the alignment of eh_frame, which means it
3134     // must be 8-byte on 64-bit targets to match what gcc does.  Otherwise
3135     // you get holes which confuse readers of eh_frame.
3136     Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3137                        0, 0, false);
3138     EmitLabel("eh_frame_common_end", Index);
3139
3140     Asm->EOL();
3141   }
3142
3143   /// EmitEHFrame - Emit function exception frame information.
3144   ///
3145   void EmitEHFrame(const FunctionEHFrameInfo &EHFrameInfo) {
3146     Function::LinkageTypes linkage = EHFrameInfo.function->getLinkage();
3147
3148     Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
3149
3150     // Externally visible entry into the functions eh frame info.
3151     // If the corresponding function is static, this should not be
3152     // externally visible.
3153     if (linkage != Function::InternalLinkage) {
3154       if (const char *GlobalEHDirective = TAI->getGlobalEHDirective())
3155         O << GlobalEHDirective << EHFrameInfo.FnName << "\n";
3156     }
3157
3158     // If corresponding function is weak definition, this should be too.
3159     if ((linkage == Function::WeakLinkage ||
3160          linkage == Function::LinkOnceLinkage) &&
3161         TAI->getWeakDefDirective())
3162       O << TAI->getWeakDefDirective() << EHFrameInfo.FnName << "\n";
3163
3164     // If there are no calls then you can't unwind.  This may mean we can
3165     // omit the EH Frame, but some environments do not handle weak absolute
3166     // symbols.
3167     // If UnwindTablesMandatory is set we cannot do this optimization; the
3168     // unwind info is to be available for non-EH uses.
3169     if (!EHFrameInfo.hasCalls &&
3170         !UnwindTablesMandatory &&
3171         ((linkage != Function::WeakLinkage &&
3172           linkage != Function::LinkOnceLinkage) ||
3173          !TAI->getWeakDefDirective() ||
3174          TAI->getSupportsWeakOmittedEHFrame()))
3175     {
3176       O << EHFrameInfo.FnName << " = 0\n";
3177       // This name has no connection to the function, so it might get
3178       // dead-stripped when the function is not, erroneously.  Prohibit
3179       // dead-stripping unconditionally.
3180       if (const char *UsedDirective = TAI->getUsedDirective())
3181         O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3182     } else {
3183       O << EHFrameInfo.FnName << ":\n";
3184
3185       // EH frame header.
3186       EmitDifference("eh_frame_end", EHFrameInfo.Number,
3187                      "eh_frame_begin", EHFrameInfo.Number, true);
3188       Asm->EOL("Length of Frame Information Entry");
3189
3190       EmitLabel("eh_frame_begin", EHFrameInfo.Number);
3191
3192       if (TAI->doesRequireNonLocalEHFrameLabel()) {
3193         PrintRelDirective(true, true);
3194         PrintLabelName("eh_frame_begin", EHFrameInfo.Number);
3195
3196         if (!TAI->isAbsoluteEHSectionOffsets())
3197           O << "-EH_frame" << EHFrameInfo.PersonalityIndex;
3198       } else {
3199         EmitSectionOffset("eh_frame_begin", "eh_frame_common",
3200                           EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
3201                           true, true, false);
3202       }
3203
3204       Asm->EOL("FDE CIE offset");
3205
3206       EmitReference("eh_func_begin", EHFrameInfo.Number, true, 
3207                     TAI->doesRequire32BitFDEReference());
3208       Asm->EOL("FDE initial location");
3209       EmitDifference("eh_func_end", EHFrameInfo.Number,
3210                      "eh_func_begin", EHFrameInfo.Number,
3211                      TAI->doesRequire32BitFDEReference());
3212       Asm->EOL("FDE address range");
3213
3214       // If there is a personality and landing pads then point to the language
3215       // specific data area in the exception table.
3216       if (EHFrameInfo.PersonalityIndex) {
3217         Asm->EmitULEB128Bytes(4);
3218         Asm->EOL("Augmentation size");
3219
3220         if (EHFrameInfo.hasLandingPads)
3221           EmitReference("exception", EHFrameInfo.Number, true, true);
3222         else
3223           Asm->EmitInt32((int)0);
3224         Asm->EOL("Language Specific Data Area");
3225       } else {
3226         Asm->EmitULEB128Bytes(0);
3227         Asm->EOL("Augmentation size");
3228       }
3229
3230       // Indicate locations of function specific  callee saved registers in
3231       // frame.
3232       EmitFrameMoves("eh_func_begin", EHFrameInfo.Number, EHFrameInfo.Moves, true);
3233
3234       // On Darwin the linker honors the alignment of eh_frame, which means it
3235       // must be 8-byte on 64-bit targets to match what gcc does.  Otherwise
3236       // you get holes which confuse readers of eh_frame.
3237       Asm->EmitAlignment(TD->getPointerSize() == sizeof(int32_t) ? 2 : 3,
3238                          0, 0, false);
3239       EmitLabel("eh_frame_end", EHFrameInfo.Number);
3240
3241       // If the function is marked used, this table should be also.  We cannot
3242       // make the mark unconditional in this case, since retaining the table
3243       // also retains the function in this case, and there is code around
3244       // that depends on unused functions (calling undefined externals) being
3245       // dead-stripped to link correctly.  Yes, there really is.
3246       if (MMI->getUsedFunctions().count(EHFrameInfo.function))
3247         if (const char *UsedDirective = TAI->getUsedDirective())
3248           O << UsedDirective << EHFrameInfo.FnName << "\n\n";
3249     }
3250   }
3251
3252   /// EmitExceptionTable - Emit landing pads and actions.
3253   ///
3254   /// The general organization of the table is complex, but the basic concepts
3255   /// are easy.  First there is a header which describes the location and
3256   /// organization of the three components that follow.
3257   ///  1. The landing pad site information describes the range of code covered
3258   ///     by the try.  In our case it's an accumulation of the ranges covered
3259   ///     by the invokes in the try.  There is also a reference to the landing
3260   ///     pad that handles the exception once processed.  Finally an index into
3261   ///     the actions table.
3262   ///  2. The action table, in our case, is composed of pairs of type ids
3263   ///     and next action offset.  Starting with the action index from the
3264   ///     landing pad site, each type Id is checked for a match to the current
3265   ///     exception.  If it matches then the exception and type id are passed
3266   ///     on to the landing pad.  Otherwise the next action is looked up.  This
3267   ///     chain is terminated with a next action of zero.  If no type id is
3268   ///     found the the frame is unwound and handling continues.
3269   ///  3. Type id table contains references to all the C++ typeinfo for all
3270   ///     catches in the function.  This tables is reversed indexed base 1.
3271
3272   /// SharedTypeIds - How many leading type ids two landing pads have in common.
3273   static unsigned SharedTypeIds(const LandingPadInfo *L,
3274                                 const LandingPadInfo *R) {
3275     const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3276     unsigned LSize = LIds.size(), RSize = RIds.size();
3277     unsigned MinSize = LSize < RSize ? LSize : RSize;
3278     unsigned Count = 0;
3279
3280     for (; Count != MinSize; ++Count)
3281       if (LIds[Count] != RIds[Count])
3282         return Count;
3283
3284     return Count;
3285   }
3286
3287   /// PadLT - Order landing pads lexicographically by type id.
3288   static bool PadLT(const LandingPadInfo *L, const LandingPadInfo *R) {
3289     const std::vector<int> &LIds = L->TypeIds, &RIds = R->TypeIds;
3290     unsigned LSize = LIds.size(), RSize = RIds.size();
3291     unsigned MinSize = LSize < RSize ? LSize : RSize;
3292
3293     for (unsigned i = 0; i != MinSize; ++i)
3294       if (LIds[i] != RIds[i])
3295         return LIds[i] < RIds[i];
3296
3297     return LSize < RSize;
3298   }
3299
3300   struct KeyInfo {
3301     static inline unsigned getEmptyKey() { return -1U; }
3302     static inline unsigned getTombstoneKey() { return -2U; }
3303     static unsigned getHashValue(const unsigned &Key) { return Key; }
3304     static bool isEqual(unsigned LHS, unsigned RHS) { return LHS == RHS; }
3305     static bool isPod() { return true; }
3306   };
3307
3308   /// ActionEntry - Structure describing an entry in the actions table.
3309   struct ActionEntry {
3310     int ValueForTypeID; // The value to write - may not be equal to the type id.
3311     int NextAction;
3312     struct ActionEntry *Previous;
3313   };
3314
3315   /// PadRange - Structure holding a try-range and the associated landing pad.
3316   struct PadRange {
3317     // The index of the landing pad.
3318     unsigned PadIndex;
3319     // The index of the begin and end labels in the landing pad's label lists.
3320     unsigned RangeIndex;
3321   };
3322
3323   typedef DenseMap<unsigned, PadRange, KeyInfo> RangeMapType;
3324
3325   /// CallSiteEntry - Structure describing an entry in the call-site table.
3326   struct CallSiteEntry {
3327     // The 'try-range' is BeginLabel .. EndLabel.
3328     unsigned BeginLabel; // zero indicates the start of the function.
3329     unsigned EndLabel;   // zero indicates the end of the function.
3330     // The landing pad starts at PadLabel.
3331     unsigned PadLabel;   // zero indicates that there is no landing pad.
3332     unsigned Action;
3333   };
3334
3335   void EmitExceptionTable() {
3336     const std::vector<GlobalVariable *> &TypeInfos = MMI->getTypeInfos();
3337     const std::vector<unsigned> &FilterIds = MMI->getFilterIds();
3338     const std::vector<LandingPadInfo> &PadInfos = MMI->getLandingPads();
3339     if (PadInfos.empty()) return;
3340
3341     // Sort the landing pads in order of their type ids.  This is used to fold
3342     // duplicate actions.
3343     SmallVector<const LandingPadInfo *, 64> LandingPads;
3344     LandingPads.reserve(PadInfos.size());
3345     for (unsigned i = 0, N = PadInfos.size(); i != N; ++i)
3346       LandingPads.push_back(&PadInfos[i]);
3347     std::sort(LandingPads.begin(), LandingPads.end(), PadLT);
3348
3349     // Negative type ids index into FilterIds, positive type ids index into
3350     // TypeInfos.  The value written for a positive type id is just the type
3351     // id itself.  For a negative type id, however, the value written is the
3352     // (negative) byte offset of the corresponding FilterIds entry.  The byte
3353     // offset is usually equal to the type id, because the FilterIds entries
3354     // are written using a variable width encoding which outputs one byte per
3355     // entry as long as the value written is not too large, but can differ.
3356     // This kind of complication does not occur for positive type ids because
3357     // type infos are output using a fixed width encoding.
3358     // FilterOffsets[i] holds the byte offset corresponding to FilterIds[i].
3359     SmallVector<int, 16> FilterOffsets;
3360     FilterOffsets.reserve(FilterIds.size());
3361     int Offset = -1;
3362     for(std::vector<unsigned>::const_iterator I = FilterIds.begin(),
3363         E = FilterIds.end(); I != E; ++I) {
3364       FilterOffsets.push_back(Offset);
3365       Offset -= TargetAsmInfo::getULEB128Size(*I);
3366     }
3367
3368     // Compute the actions table and gather the first action index for each
3369     // landing pad site.
3370     SmallVector<ActionEntry, 32> Actions;
3371     SmallVector<unsigned, 64> FirstActions;
3372     FirstActions.reserve(LandingPads.size());
3373
3374     int FirstAction = 0;
3375     unsigned SizeActions = 0;
3376     for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3377       const LandingPadInfo *LP = LandingPads[i];
3378       const std::vector<int> &TypeIds = LP->TypeIds;
3379       const unsigned NumShared = i ? SharedTypeIds(LP, LandingPads[i-1]) : 0;
3380       unsigned SizeSiteActions = 0;
3381
3382       if (NumShared < TypeIds.size()) {
3383         unsigned SizeAction = 0;
3384         ActionEntry *PrevAction = 0;
3385
3386         if (NumShared) {
3387           const unsigned SizePrevIds = LandingPads[i-1]->TypeIds.size();
3388           assert(Actions.size());
3389           PrevAction = &Actions.back();
3390           SizeAction = TargetAsmInfo::getSLEB128Size(PrevAction->NextAction) +
3391             TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3392           for (unsigned j = NumShared; j != SizePrevIds; ++j) {
3393             SizeAction -=
3394               TargetAsmInfo::getSLEB128Size(PrevAction->ValueForTypeID);
3395             SizeAction += -PrevAction->NextAction;
3396             PrevAction = PrevAction->Previous;
3397           }
3398         }
3399
3400         // Compute the actions.
3401         for (unsigned I = NumShared, M = TypeIds.size(); I != M; ++I) {
3402           int TypeID = TypeIds[I];
3403           assert(-1-TypeID < (int)FilterOffsets.size() && "Unknown filter id!");
3404           int ValueForTypeID = TypeID < 0 ? FilterOffsets[-1 - TypeID] : TypeID;
3405           unsigned SizeTypeID = TargetAsmInfo::getSLEB128Size(ValueForTypeID);
3406
3407           int NextAction = SizeAction ? -(SizeAction + SizeTypeID) : 0;
3408           SizeAction = SizeTypeID + TargetAsmInfo::getSLEB128Size(NextAction);
3409           SizeSiteActions += SizeAction;
3410
3411           ActionEntry Action = {ValueForTypeID, NextAction, PrevAction};
3412           Actions.push_back(Action);
3413
3414           PrevAction = &Actions.back();
3415         }
3416
3417         // Record the first action of the landing pad site.
3418         FirstAction = SizeActions + SizeSiteActions - SizeAction + 1;
3419       } // else identical - re-use previous FirstAction
3420
3421       FirstActions.push_back(FirstAction);
3422
3423       // Compute this sites contribution to size.
3424       SizeActions += SizeSiteActions;
3425     }
3426
3427     // Compute the call-site table.  The entry for an invoke has a try-range
3428     // containing the call, a non-zero landing pad and an appropriate action.
3429     // The entry for an ordinary call has a try-range containing the call and
3430     // zero for the landing pad and the action.  Calls marked 'nounwind' have
3431     // no entry and must not be contained in the try-range of any entry - they
3432     // form gaps in the table.  Entries must be ordered by try-range address.
3433     SmallVector<CallSiteEntry, 64> CallSites;
3434
3435     RangeMapType PadMap;
3436     // Invokes and nounwind calls have entries in PadMap (due to being bracketed
3437     // by try-range labels when lowered).  Ordinary calls do not, so appropriate
3438     // try-ranges for them need be deduced.
3439     for (unsigned i = 0, N = LandingPads.size(); i != N; ++i) {
3440       const LandingPadInfo *LandingPad = LandingPads[i];
3441       for (unsigned j = 0, E = LandingPad->BeginLabels.size(); j != E; ++j) {
3442         unsigned BeginLabel = LandingPad->BeginLabels[j];
3443         assert(!PadMap.count(BeginLabel) && "Duplicate landing pad labels!");
3444         PadRange P = { i, j };
3445         PadMap[BeginLabel] = P;
3446       }
3447     }
3448
3449     // The end label of the previous invoke or nounwind try-range.
3450     unsigned LastLabel = 0;
3451
3452     // Whether there is a potentially throwing instruction (currently this means
3453     // an ordinary call) between the end of the previous try-range and now.
3454     bool SawPotentiallyThrowing = false;
3455
3456     // Whether the last callsite entry was for an invoke.
3457     bool PreviousIsInvoke = false;
3458
3459     // Visit all instructions in order of address.
3460     for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
3461          I != E; ++I) {
3462       for (MachineBasicBlock::const_iterator MI = I->begin(), E = I->end();
3463            MI != E; ++MI) {
3464         if (!MI->isLabel()) {
3465           SawPotentiallyThrowing |= MI->getDesc().isCall();
3466           continue;
3467         }
3468
3469         unsigned BeginLabel = MI->getOperand(0).getImm();
3470         assert(BeginLabel && "Invalid label!");
3471
3472         // End of the previous try-range?
3473         if (BeginLabel == LastLabel)
3474           SawPotentiallyThrowing = false;
3475
3476         // Beginning of a new try-range?
3477         RangeMapType::iterator L = PadMap.find(BeginLabel);
3478         if (L == PadMap.end())
3479           // Nope, it was just some random label.
3480           continue;
3481
3482         PadRange P = L->second;
3483         const LandingPadInfo *LandingPad = LandingPads[P.PadIndex];
3484
3485         assert(BeginLabel == LandingPad->BeginLabels[P.RangeIndex] &&
3486                "Inconsistent landing pad map!");
3487
3488         // If some instruction between the previous try-range and this one may
3489         // throw, create a call-site entry with no landing pad for the region
3490         // between the try-ranges.
3491         if (SawPotentiallyThrowing) {
3492           CallSiteEntry Site = {LastLabel, BeginLabel, 0, 0};
3493           CallSites.push_back(Site);
3494           PreviousIsInvoke = false;
3495         }
3496
3497         LastLabel = LandingPad->EndLabels[P.RangeIndex];
3498         assert(BeginLabel && LastLabel && "Invalid landing pad!");
3499
3500         if (LandingPad->LandingPadLabel) {
3501           // This try-range is for an invoke.
3502           CallSiteEntry Site = {BeginLabel, LastLabel,
3503             LandingPad->LandingPadLabel, FirstActions[P.PadIndex]};
3504
3505           // Try to merge with the previous call-site.
3506           if (PreviousIsInvoke) {
3507             CallSiteEntry &Prev = CallSites.back();
3508             if (Site.PadLabel == Prev.PadLabel && Site.Action == Prev.Action) {
3509               // Extend the range of the previous entry.
3510               Prev.EndLabel = Site.EndLabel;
3511               continue;
3512             }
3513           }
3514
3515           // Otherwise, create a new call-site.
3516           CallSites.push_back(Site);
3517           PreviousIsInvoke = true;
3518         } else {
3519           // Create a gap.
3520           PreviousIsInvoke = false;
3521         }
3522       }
3523     }
3524     // If some instruction between the previous try-range and the end of the
3525     // function may throw, create a call-site entry with no landing pad for the
3526     // region following the try-range.
3527     if (SawPotentiallyThrowing) {
3528       CallSiteEntry Site = {LastLabel, 0, 0, 0};
3529       CallSites.push_back(Site);
3530     }
3531
3532     // Final tallies.
3533
3534     // Call sites.
3535     const unsigned SiteStartSize  = sizeof(int32_t); // DW_EH_PE_udata4
3536     const unsigned SiteLengthSize = sizeof(int32_t); // DW_EH_PE_udata4
3537     const unsigned LandingPadSize = sizeof(int32_t); // DW_EH_PE_udata4
3538     unsigned SizeSites = CallSites.size() * (SiteStartSize +
3539                                              SiteLengthSize +
3540                                              LandingPadSize);
3541     for (unsigned i = 0, e = CallSites.size(); i < e; ++i)
3542       SizeSites += TargetAsmInfo::getULEB128Size(CallSites[i].Action);
3543
3544     // Type infos.
3545     const unsigned TypeInfoSize = TD->getPointerSize(); // DW_EH_PE_absptr
3546     unsigned SizeTypes = TypeInfos.size() * TypeInfoSize;
3547
3548     unsigned TypeOffset = sizeof(int8_t) + // Call site format
3549            TargetAsmInfo::getULEB128Size(SizeSites) + // Call-site table length
3550                           SizeSites + SizeActions + SizeTypes;
3551
3552     unsigned TotalSize = sizeof(int8_t) + // LPStart format
3553                          sizeof(int8_t) + // TType format
3554            TargetAsmInfo::getULEB128Size(TypeOffset) + // TType base offset
3555                          TypeOffset;
3556
3557     unsigned SizeAlign = (4 - TotalSize) & 3;
3558
3559     // Begin the exception table.
3560     Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
3561     Asm->EmitAlignment(2, 0, 0, false);
3562     O << "GCC_except_table" << SubprogramCount << ":\n";
3563     for (unsigned i = 0; i != SizeAlign; ++i) {
3564       Asm->EmitInt8(0);
3565       Asm->EOL("Padding");
3566     }
3567     EmitLabel("exception", SubprogramCount);
3568
3569     // Emit the header.
3570     Asm->EmitInt8(DW_EH_PE_omit);
3571     Asm->EOL("LPStart format (DW_EH_PE_omit)");
3572     Asm->EmitInt8(DW_EH_PE_absptr);
3573     Asm->EOL("TType format (DW_EH_PE_absptr)");
3574     Asm->EmitULEB128Bytes(TypeOffset);
3575     Asm->EOL("TType base offset");
3576     Asm->EmitInt8(DW_EH_PE_udata4);
3577     Asm->EOL("Call site format (DW_EH_PE_udata4)");
3578     Asm->EmitULEB128Bytes(SizeSites);
3579     Asm->EOL("Call-site table length");
3580
3581     // Emit the landing pad site information.
3582     for (unsigned i = 0; i < CallSites.size(); ++i) {
3583       CallSiteEntry &S = CallSites[i];
3584       const char *BeginTag;
3585       unsigned BeginNumber;
3586
3587       if (!S.BeginLabel) {
3588         BeginTag = "eh_func_begin";
3589         BeginNumber = SubprogramCount;
3590       } else {
3591         BeginTag = "label";
3592         BeginNumber = S.BeginLabel;
3593       }
3594
3595       EmitSectionOffset(BeginTag, "eh_func_begin", BeginNumber, SubprogramCount,
3596                         true, true);
3597       Asm->EOL("Region start");
3598
3599       if (!S.EndLabel) {
3600         EmitDifference("eh_func_end", SubprogramCount, BeginTag, BeginNumber,
3601                        true);
3602       } else {
3603         EmitDifference("label", S.EndLabel, BeginTag, BeginNumber, true);
3604       }
3605       Asm->EOL("Region length");
3606
3607       if (!S.PadLabel)
3608         Asm->EmitInt32(0);
3609       else
3610         EmitSectionOffset("label", "eh_func_begin", S.PadLabel, SubprogramCount,
3611                           true, true);
3612       Asm->EOL("Landing pad");
3613
3614       Asm->EmitULEB128Bytes(S.Action);
3615       Asm->EOL("Action");
3616     }
3617
3618     // Emit the actions.
3619     for (unsigned I = 0, N = Actions.size(); I != N; ++I) {
3620       ActionEntry &Action = Actions[I];
3621
3622       Asm->EmitSLEB128Bytes(Action.ValueForTypeID);
3623       Asm->EOL("TypeInfo index");
3624       Asm->EmitSLEB128Bytes(Action.NextAction);
3625       Asm->EOL("Next action");
3626     }
3627
3628     // Emit the type ids.
3629     for (unsigned M = TypeInfos.size(); M; --M) {
3630       GlobalVariable *GV = TypeInfos[M - 1];
3631
3632       PrintRelDirective();
3633
3634       if (GV)
3635         O << Asm->getGlobalLinkName(GV);
3636       else
3637         O << "0";
3638
3639       Asm->EOL("TypeInfo");
3640     }
3641
3642     // Emit the filter typeids.
3643     for (unsigned j = 0, M = FilterIds.size(); j < M; ++j) {
3644       unsigned TypeID = FilterIds[j];
3645       Asm->EmitULEB128Bytes(TypeID);
3646       Asm->EOL("Filter TypeInfo index");
3647     }
3648
3649     Asm->EmitAlignment(2, 0, 0, false);
3650   }
3651
3652 public:
3653   //===--------------------------------------------------------------------===//
3654   // Main entry points.
3655   //
3656   DwarfException(raw_ostream &OS, AsmPrinter *A, const TargetAsmInfo *T)
3657   : Dwarf(OS, A, T, "eh")
3658   , shouldEmitTable(false)
3659   , shouldEmitMoves(false)
3660   , shouldEmitTableModule(false)
3661   , shouldEmitMovesModule(false)
3662   {}
3663
3664   virtual ~DwarfException() {}
3665
3666   /// SetModuleInfo - Set machine module information when it's known that pass
3667   /// manager has created it.  Set by the target AsmPrinter.
3668   void SetModuleInfo(MachineModuleInfo *mmi) {
3669     MMI = mmi;
3670   }
3671
3672   /// BeginModule - Emit all exception information that should come prior to the
3673   /// content.
3674   void BeginModule(Module *M) {
3675     this->M = M;
3676   }
3677
3678   /// EndModule - Emit all exception information that should come after the
3679   /// content.
3680   void EndModule() {
3681     if (shouldEmitMovesModule || shouldEmitTableModule) {
3682       const std::vector<Function *> Personalities = MMI->getPersonalities();
3683       for (unsigned i =0; i < Personalities.size(); ++i)
3684         EmitCommonEHFrame(Personalities[i], i);
3685
3686       for (std::vector<FunctionEHFrameInfo>::iterator I = EHFrames.begin(),
3687              E = EHFrames.end(); I != E; ++I)
3688         EmitEHFrame(*I);
3689     }
3690   }
3691
3692   /// BeginFunction - Gather pre-function exception information.  Assumes being
3693   /// emitted immediately after the function entry point.
3694   void BeginFunction(MachineFunction *MF) {
3695     this->MF = MF;
3696     shouldEmitTable = shouldEmitMoves = false;
3697     if (MMI && TAI->doesSupportExceptionHandling()) {
3698
3699       // Map all labels and get rid of any dead landing pads.
3700       MMI->TidyLandingPads();
3701       // If any landing pads survive, we need an EH table.
3702       if (MMI->getLandingPads().size())
3703         shouldEmitTable = true;
3704
3705       // See if we need frame move info.
3706       if (!MF->getFunction()->doesNotThrow() || UnwindTablesMandatory)
3707         shouldEmitMoves = true;
3708
3709       if (shouldEmitMoves || shouldEmitTable)
3710         // Assumes in correct section after the entry point.
3711         EmitLabel("eh_func_begin", ++SubprogramCount);
3712     }
3713     shouldEmitTableModule |= shouldEmitTable;
3714     shouldEmitMovesModule |= shouldEmitMoves;
3715   }
3716
3717   /// EndFunction - Gather and emit post-function exception information.
3718   ///
3719   void EndFunction() {
3720     if (shouldEmitMoves || shouldEmitTable) {
3721       EmitLabel("eh_func_end", SubprogramCount);
3722       EmitExceptionTable();
3723
3724       // Save EH frame information
3725       EHFrames.
3726         push_back(FunctionEHFrameInfo(getAsm()->getCurrentFunctionEHName(MF),
3727                                     SubprogramCount,
3728                                     MMI->getPersonalityIndex(),
3729                                     MF->getFrameInfo()->hasCalls(),
3730                                     !MMI->getLandingPads().empty(),
3731                                     MMI->getFrameMoves(),
3732                                     MF->getFunction()));
3733       }
3734   }
3735 };
3736
3737 } // End of namespace llvm
3738
3739 //===----------------------------------------------------------------------===//
3740
3741 /// Emit - Print the abbreviation using the specified Dwarf writer.
3742 ///
3743 void DIEAbbrev::Emit(const DwarfDebug &DD) const {
3744   // Emit its Dwarf tag type.
3745   DD.getAsm()->EmitULEB128Bytes(Tag);
3746   DD.getAsm()->EOL(TagString(Tag));
3747
3748   // Emit whether it has children DIEs.
3749   DD.getAsm()->EmitULEB128Bytes(ChildrenFlag);
3750   DD.getAsm()->EOL(ChildrenString(ChildrenFlag));
3751
3752   // For each attribute description.
3753   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3754     const DIEAbbrevData &AttrData = Data[i];
3755
3756     // Emit attribute type.
3757     DD.getAsm()->EmitULEB128Bytes(AttrData.getAttribute());
3758     DD.getAsm()->EOL(AttributeString(AttrData.getAttribute()));
3759
3760     // Emit form type.
3761     DD.getAsm()->EmitULEB128Bytes(AttrData.getForm());
3762     DD.getAsm()->EOL(FormEncodingString(AttrData.getForm()));
3763   }
3764
3765   // Mark end of abbreviation.
3766   DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(1)");
3767   DD.getAsm()->EmitULEB128Bytes(0); DD.getAsm()->EOL("EOM(2)");
3768 }
3769
3770 #ifndef NDEBUG
3771 void DIEAbbrev::print(std::ostream &O) {
3772   O << "Abbreviation @"
3773     << std::hex << (intptr_t)this << std::dec
3774     << "  "
3775     << TagString(Tag)
3776     << " "
3777     << ChildrenString(ChildrenFlag)
3778     << "\n";
3779
3780   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
3781     O << "  "
3782       << AttributeString(Data[i].getAttribute())
3783       << "  "
3784       << FormEncodingString(Data[i].getForm())
3785       << "\n";
3786   }
3787 }
3788 void DIEAbbrev::dump() { print(cerr); }
3789 #endif
3790
3791 //===----------------------------------------------------------------------===//
3792
3793 #ifndef NDEBUG
3794 void DIEValue::dump() {
3795   print(cerr);
3796 }
3797 #endif
3798
3799 //===----------------------------------------------------------------------===//
3800
3801 /// EmitValue - Emit integer of appropriate size.
3802 ///
3803 void DIEInteger::EmitValue(DwarfDebug &DD, unsigned Form) {
3804   switch (Form) {
3805   case DW_FORM_flag:  // Fall thru
3806   case DW_FORM_ref1:  // Fall thru
3807   case DW_FORM_data1: DD.getAsm()->EmitInt8(Integer);         break;
3808   case DW_FORM_ref2:  // Fall thru
3809   case DW_FORM_data2: DD.getAsm()->EmitInt16(Integer);        break;
3810   case DW_FORM_ref4:  // Fall thru
3811   case DW_FORM_data4: DD.getAsm()->EmitInt32(Integer);        break;
3812   case DW_FORM_ref8:  // Fall thru
3813   case DW_FORM_data8: DD.getAsm()->EmitInt64(Integer);        break;
3814   case DW_FORM_udata: DD.getAsm()->EmitULEB128Bytes(Integer); break;
3815   case DW_FORM_sdata: DD.getAsm()->EmitSLEB128Bytes(Integer); break;
3816   default: assert(0 && "DIE Value form not supported yet");   break;
3817   }
3818 }
3819
3820 /// SizeOf - Determine size of integer value in bytes.
3821 ///
3822 unsigned DIEInteger::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3823   switch (Form) {
3824   case DW_FORM_flag:  // Fall thru
3825   case DW_FORM_ref1:  // Fall thru
3826   case DW_FORM_data1: return sizeof(int8_t);
3827   case DW_FORM_ref2:  // Fall thru
3828   case DW_FORM_data2: return sizeof(int16_t);
3829   case DW_FORM_ref4:  // Fall thru
3830   case DW_FORM_data4: return sizeof(int32_t);
3831   case DW_FORM_ref8:  // Fall thru
3832   case DW_FORM_data8: return sizeof(int64_t);
3833   case DW_FORM_udata: return TargetAsmInfo::getULEB128Size(Integer);
3834   case DW_FORM_sdata: return TargetAsmInfo::getSLEB128Size(Integer);
3835   default: assert(0 && "DIE Value form not supported yet"); break;
3836   }
3837   return 0;
3838 }
3839
3840 //===----------------------------------------------------------------------===//
3841
3842 /// EmitValue - Emit string value.
3843 ///
3844 void DIEString::EmitValue(DwarfDebug &DD, unsigned Form) {
3845   DD.getAsm()->EmitString(String);
3846 }
3847
3848 //===----------------------------------------------------------------------===//
3849
3850 /// EmitValue - Emit label value.
3851 ///
3852 void DIEDwarfLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
3853   bool IsSmall = Form == DW_FORM_data4;
3854   DD.EmitReference(Label, false, IsSmall);
3855 }
3856
3857 /// SizeOf - Determine size of label value in bytes.
3858 ///
3859 unsigned DIEDwarfLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3860   if (Form == DW_FORM_data4) return 4;
3861   return DD.getTargetData()->getPointerSize();
3862 }
3863
3864 //===----------------------------------------------------------------------===//
3865
3866 /// EmitValue - Emit label value.
3867 ///
3868 void DIEObjectLabel::EmitValue(DwarfDebug &DD, unsigned Form) {
3869   bool IsSmall = Form == DW_FORM_data4;
3870   DD.EmitReference(Label, false, IsSmall);
3871 }
3872
3873 /// SizeOf - Determine size of label value in bytes.
3874 ///
3875 unsigned DIEObjectLabel::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3876   if (Form == DW_FORM_data4) return 4;
3877   return DD.getTargetData()->getPointerSize();
3878 }
3879
3880 //===----------------------------------------------------------------------===//
3881
3882 /// EmitValue - Emit delta value.
3883 ///
3884 void DIESectionOffset::EmitValue(DwarfDebug &DD, unsigned Form) {
3885   bool IsSmall = Form == DW_FORM_data4;
3886   DD.EmitSectionOffset(Label.Tag, Section.Tag,
3887                        Label.Number, Section.Number, IsSmall, IsEH, UseSet);
3888 }
3889
3890 /// SizeOf - Determine size of delta value in bytes.
3891 ///
3892 unsigned DIESectionOffset::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3893   if (Form == DW_FORM_data4) return 4;
3894   return DD.getTargetData()->getPointerSize();
3895 }
3896
3897 //===----------------------------------------------------------------------===//
3898
3899 /// EmitValue - Emit delta value.
3900 ///
3901 void DIEDelta::EmitValue(DwarfDebug &DD, unsigned Form) {
3902   bool IsSmall = Form == DW_FORM_data4;
3903   DD.EmitDifference(LabelHi, LabelLo, IsSmall);
3904 }
3905
3906 /// SizeOf - Determine size of delta value in bytes.
3907 ///
3908 unsigned DIEDelta::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3909   if (Form == DW_FORM_data4) return 4;
3910   return DD.getTargetData()->getPointerSize();
3911 }
3912
3913 //===----------------------------------------------------------------------===//
3914
3915 /// EmitValue - Emit debug information entry offset.
3916 ///
3917 void DIEntry::EmitValue(DwarfDebug &DD, unsigned Form) {
3918   DD.getAsm()->EmitInt32(Entry->getOffset());
3919 }
3920
3921 //===----------------------------------------------------------------------===//
3922
3923 /// ComputeSize - calculate the size of the block.
3924 ///
3925 unsigned DIEBlock::ComputeSize(DwarfDebug &DD) {
3926   if (!Size) {
3927     const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
3928
3929     for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3930       Size += Values[i]->SizeOf(DD, AbbrevData[i].getForm());
3931     }
3932   }
3933   return Size;
3934 }
3935
3936 /// EmitValue - Emit block data.
3937 ///
3938 void DIEBlock::EmitValue(DwarfDebug &DD, unsigned Form) {
3939   switch (Form) {
3940   case DW_FORM_block1: DD.getAsm()->EmitInt8(Size);         break;
3941   case DW_FORM_block2: DD.getAsm()->EmitInt16(Size);        break;
3942   case DW_FORM_block4: DD.getAsm()->EmitInt32(Size);        break;
3943   case DW_FORM_block:  DD.getAsm()->EmitULEB128Bytes(Size); break;
3944   default: assert(0 && "Improper form for block");          break;
3945   }
3946
3947   const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev.getData();
3948
3949   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
3950     DD.getAsm()->EOL();
3951     Values[i]->EmitValue(DD, AbbrevData[i].getForm());
3952   }
3953 }
3954
3955 /// SizeOf - Determine size of block data in bytes.
3956 ///
3957 unsigned DIEBlock::SizeOf(const DwarfDebug &DD, unsigned Form) const {
3958   switch (Form) {
3959   case DW_FORM_block1: return Size + sizeof(int8_t);
3960   case DW_FORM_block2: return Size + sizeof(int16_t);
3961   case DW_FORM_block4: return Size + sizeof(int32_t);
3962   case DW_FORM_block: return Size + TargetAsmInfo::getULEB128Size(Size);
3963   default: assert(0 && "Improper form for block"); break;
3964   }
3965   return 0;
3966 }
3967
3968 //===----------------------------------------------------------------------===//
3969 /// DIE Implementation
3970
3971 DIE::~DIE() {
3972   for (unsigned i = 0, N = Children.size(); i < N; ++i)
3973     delete Children[i];
3974 }
3975
3976 /// AddSiblingOffset - Add a sibling offset field to the front of the DIE.
3977 ///
3978 void DIE::AddSiblingOffset() {
3979   DIEInteger *DI = new DIEInteger(0);
3980   Values.insert(Values.begin(), DI);
3981   Abbrev.AddFirstAttribute(DW_AT_sibling, DW_FORM_ref4);
3982 }
3983
3984 /// Profile - Used to gather unique data for the value folding set.
3985 ///
3986 void DIE::Profile(FoldingSetNodeID &ID) {
3987   Abbrev.Profile(ID);
3988
3989   for (unsigned i = 0, N = Children.size(); i < N; ++i)
3990     ID.AddPointer(Children[i]);
3991
3992   for (unsigned j = 0, M = Values.size(); j < M; ++j)
3993     ID.AddPointer(Values[j]);
3994 }
3995
3996 #ifndef NDEBUG
3997 void DIE::print(std::ostream &O, unsigned IncIndent) {
3998   static unsigned IndentCount = 0;
3999   IndentCount += IncIndent;
4000   const std::string Indent(IndentCount, ' ');
4001   bool isBlock = Abbrev.getTag() == 0;
4002
4003   if (!isBlock) {
4004     O << Indent
4005       << "Die: "
4006       << "0x" << std::hex << (intptr_t)this << std::dec
4007       << ", Offset: " << Offset
4008       << ", Size: " << Size
4009       << "\n";
4010
4011     O << Indent
4012       << TagString(Abbrev.getTag())
4013       << " "
4014       << ChildrenString(Abbrev.getChildrenFlag());
4015   } else {
4016     O << "Size: " << Size;
4017   }
4018   O << "\n";
4019
4020   const SmallVector<DIEAbbrevData, 8> &Data = Abbrev.getData();
4021
4022   IndentCount += 2;
4023   for (unsigned i = 0, N = Data.size(); i < N; ++i) {
4024     O << Indent;
4025
4026     if (!isBlock)
4027       O << AttributeString(Data[i].getAttribute());
4028     else
4029       O << "Blk[" << i << "]";
4030
4031     O <<  "  "
4032       << FormEncodingString(Data[i].getForm())
4033       << " ";
4034     Values[i]->print(O);
4035     O << "\n";
4036   }
4037   IndentCount -= 2;
4038
4039   for (unsigned j = 0, M = Children.size(); j < M; ++j) {
4040     Children[j]->print(O, 4);
4041   }
4042
4043   if (!isBlock) O << "\n";
4044   IndentCount -= IncIndent;
4045 }
4046
4047 void DIE::dump() {
4048   print(cerr);
4049 }
4050 #endif
4051
4052 //===----------------------------------------------------------------------===//
4053 /// DwarfWriter Implementation
4054 ///
4055
4056 DwarfWriter::DwarfWriter(raw_ostream &OS, AsmPrinter *A,
4057                          const TargetAsmInfo *T) {
4058   DE = new DwarfException(OS, A, T);
4059   DD = new DwarfDebug(OS, A, T);
4060 }
4061
4062 DwarfWriter::~DwarfWriter() {
4063   delete DE;
4064   delete DD;
4065 }
4066
4067 /// SetModuleInfo - Set machine module info when it's known that pass manager
4068 /// has created it.  Set by the target AsmPrinter.
4069 void DwarfWriter::SetModuleInfo(MachineModuleInfo *MMI) {
4070   DD->SetModuleInfo(MMI);
4071   DE->SetModuleInfo(MMI);
4072 }
4073
4074 /// BeginModule - Emit all Dwarf sections that should come prior to the
4075 /// content.
4076 void DwarfWriter::BeginModule(Module *M) {
4077   DE->BeginModule(M);
4078   DD->BeginModule(M);
4079 }
4080
4081 /// EndModule - Emit all Dwarf sections that should come after the content.
4082 ///
4083 void DwarfWriter::EndModule() {
4084   DE->EndModule();
4085   DD->EndModule();
4086 }
4087
4088 /// BeginFunction - Gather pre-function debug information.  Assumes being
4089 /// emitted immediately after the function entry point.
4090 void DwarfWriter::BeginFunction(MachineFunction *MF) {
4091   DE->BeginFunction(MF);
4092   DD->BeginFunction(MF);
4093 }
4094
4095 /// EndFunction - Gather and emit post-function debug information.
4096 ///
4097 void DwarfWriter::EndFunction(MachineFunction *MF) {
4098   DD->EndFunction(MF);
4099   DE->EndFunction();
4100
4101   if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())
4102     // Clear function debug information.
4103     MMI->EndFunction();
4104 }