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