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