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