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