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