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