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