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