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