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