Convert DwarfWriter into a pass.
[oota-llvm.git] / lib / CodeGen / AsmPrinter / DwarfWriter.cpp
index 99e94e2ac049b986e210962ad1c88ed3b209e387..6293590fd67690c1e258c5920b05152374098355 100644 (file)
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/UniqueVector.h"
 #include "llvm/Module.h"
-#include "llvm/Type.h"
+#include "llvm/DerivedTypes.h"
 #include "llvm/CodeGen/AsmPrinter.h"
 #include "llvm/CodeGen/MachineModuleInfo.h"
 #include "llvm/CodeGen/MachineFrameInfo.h"
 #include "llvm/CodeGen/MachineLocation.h"
+#include "llvm/Analysis/DebugInfo.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/Dwarf.h"
 #include "llvm/Support/CommandLine.h"
 using namespace llvm;
 using namespace llvm::dwarf;
 
+static RegisterPass<DwarfWriter>
+X("dwarfwriter", "DWARF Information Writer");
+char DwarfWriter::ID = 0;
+
 namespace llvm {
 
 //===----------------------------------------------------------------------===//
@@ -58,6 +63,43 @@ static const unsigned InitValuesSetSize        = 9; // 512
 class DIE;
 class DIEValue;
 
+//===----------------------------------------------------------------------===//
+/// Utility routines.
+///
+/// getGlobalVariablesUsing - Return all of the GlobalVariables which have the            
+/// specified value in their initializer somewhere.                                       
+static void
+getGlobalVariablesUsing(Value *V, std::vector<GlobalVariable*> &Result) {
+  // Scan though value users.                                                             
+  for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
+    if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I)) {
+      // If the user is a GlobalVariable then add to result.                              
+      Result.push_back(GV);
+    } else if (Constant *C = dyn_cast<Constant>(*I)) {
+      // If the user is a constant variable then scan its users                           
+      getGlobalVariablesUsing(C, Result);
+    }
+  }
+}
+
+/// getGlobalVariablesUsing - Return all of the GlobalVariables that use the              
+/// named GlobalVariable.                                                                 
+static void
+getGlobalVariablesUsing(Module &M, const std::string &RootName,
+                        std::vector<GlobalVariable*> &Result) {
+  std::vector<const Type*> FieldTypes;
+  FieldTypes.push_back(Type::Int32Ty);
+  FieldTypes.push_back(Type::Int32Ty);
+
+  // Get the GlobalVariable root.                                                         
+  GlobalVariable *UseRoot = M.getGlobalVariable(RootName,
+                                                StructType::get(FieldTypes));
+
+  // If present and linkonce then scan for users.                                         
+  if (UseRoot && UseRoot->hasLinkOnceLinkage())
+    getGlobalVariablesUsing(UseRoot, Result);
+}
+
 //===----------------------------------------------------------------------===//
 /// DWLabel - Labels are used to track locations in the assembler file.
 /// Labels appear in the form @verbatim <prefix><Tag><Number> @endverbatim,
@@ -722,10 +764,12 @@ private:
   /// DescToDieMap - Tracks the mapping of unit level debug informaton
   /// descriptors to debug information entries.
   std::map<DebugInfoDesc *, DIE *> DescToDieMap;
+  DenseMap<GlobalVariable *, DIE *> GVToDieMap;
 
   /// DescToDIEntryMap - Tracks the mapping of unit level debug informaton
   /// descriptors to debug information entries using a DIEntry proxy.
   std::map<DebugInfoDesc *, DIEntry *> DescToDIEntryMap;
+  DenseMap<GlobalVariable *, DIEntry *> GVToDIEntryMap;
 
   /// Globals - A map of globally visible named entities for this unit.
   ///
@@ -740,12 +784,19 @@ private:
   std::vector<DIE *> Dies;
 
 public:
+  CompileUnit(unsigned I, DIE *D)
+    : ID(I), Die(D), DescToDieMap(), GVToDieMap(), DescToDIEntryMap(),
+      GVToDIEntryMap(), Globals(), DiesSet(InitDiesSetSize), Dies()
+  {}
+
   CompileUnit(CompileUnitDesc *CUD, unsigned I, DIE *D)
   : Desc(CUD)
   , ID(I)
   , Die(D)
   , DescToDieMap()
+  , GVToDieMap()
   , DescToDIEntryMap()
+  , GVToDIEntryMap()
   , Globals()
   , DiesSet(InitDiesSetSize)
   , Dies()
@@ -781,12 +832,18 @@ public:
   DIE *&getDieMapSlotFor(DebugInfoDesc *DID) {
     return DescToDieMap[DID];
   }
+  DIE *&getDieMapSlotFor(GlobalVariable *GV) {
+    return GVToDieMap[GV];
+  }
 
   /// getDIEntrySlotFor - Returns the debug information entry proxy slot for the
   /// specified debug descriptor.
   DIEntry *&getDIEntrySlotFor(DebugInfoDesc *DID) {
     return DescToDIEntryMap[DID];
   }
+  DIEntry *&getDIEntrySlotFor(GlobalVariable *GV) {
+    return GVToDIEntryMap[GV];
+  }
 
   /// AddDie - Adds or interns the DIE to the compile unit.
   ///
@@ -1050,15 +1107,15 @@ public:
       }
 
       // If advancing cfa.
-      if (Dst.isRegister() && Dst.getRegister() == MachineLocation::VirtualFP) {
-        if (!Src.isRegister()) {
-          if (Src.getRegister() == MachineLocation::VirtualFP) {
+      if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) {
+        if (!Src.isReg()) {
+          if (Src.getReg() == MachineLocation::VirtualFP) {
             Asm->EmitInt8(DW_CFA_def_cfa_offset);
             Asm->EOL("DW_CFA_def_cfa_offset");
           } else {
             Asm->EmitInt8(DW_CFA_def_cfa);
             Asm->EOL("DW_CFA_def_cfa");
-            Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getRegister(), isEH));
+            Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Src.getReg(), isEH));
             Asm->EOL("Register");
           }
 
@@ -1069,18 +1126,18 @@ public:
         } else {
           assert(0 && "Machine move no supported yet.");
         }
-      } else if (Src.isRegister() &&
-        Src.getRegister() == MachineLocation::VirtualFP) {
-        if (Dst.isRegister()) {
+      } else if (Src.isReg() &&
+        Src.getReg() == MachineLocation::VirtualFP) {
+        if (Dst.isReg()) {
           Asm->EmitInt8(DW_CFA_def_cfa_register);
           Asm->EOL("DW_CFA_def_cfa_register");
-          Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getRegister(), isEH));
+          Asm->EmitULEB128Bytes(RI->getDwarfRegNum(Dst.getReg(), isEH));
           Asm->EOL("Register");
         } else {
           assert(0 && "Machine move no supported yet.");
         }
       } else {
-        unsigned Reg = RI->getDwarfRegNum(Src.getRegister(), isEH);
+        unsigned Reg = RI->getDwarfRegNum(Src.getReg(), isEH);
         int Offset = Dst.getOffset() / stackGrowth;
 
         if (Offset < 0) {
@@ -1112,6 +1169,107 @@ public:
 
 };
 
+//===----------------------------------------------------------------------===//
+/// SourceLineInfo - This class is used to record source line correspondence.
+///
+class SrcLineInfo {
+  unsigned Line;                        // Source line number.
+  unsigned Column;                      // Source column.
+  unsigned SourceID;                    // Source ID number.
+  unsigned LabelID;                     // Label in code ID number.
+public:
+  SrcLineInfo(unsigned L, unsigned C, unsigned S, unsigned I)
+  : Line(L), Column(C), SourceID(S), LabelID(I) {}
+  
+  // Accessors
+  unsigned getLine()     const { return Line; }
+  unsigned getColumn()   const { return Column; }
+  unsigned getSourceID() const { return SourceID; }
+  unsigned getLabelID()  const { return LabelID; }
+};
+
+
+//===----------------------------------------------------------------------===//
+/// SrcFileInfo - This class is used to track source information.
+///
+class SrcFileInfo {
+  unsigned DirectoryID;                 // Directory ID number.
+  std::string Name;                     // File name (not including directory.)
+public:
+  SrcFileInfo(unsigned D, const std::string &N) : DirectoryID(D), Name(N) {}
+            
+  // Accessors
+  unsigned getDirectoryID()    const { return DirectoryID; }
+  const std::string &getName() const { return Name; }
+
+  /// operator== - Used by UniqueVector to locate entry.
+  ///
+  bool operator==(const SourceFileInfo &SI) const {
+    return getDirectoryID() == SI.getDirectoryID() && getName() == SI.getName();
+  }
+
+  /// operator< - Used by UniqueVector to locate entry.
+  ///
+  bool operator<(const SrcFileInfo &SI) const {
+    return getDirectoryID() < SI.getDirectoryID() ||
+          (getDirectoryID() == SI.getDirectoryID() && getName() < SI.getName());
+  }
+};
+
+//===----------------------------------------------------------------------===//
+/// DbgVariable - This class is used to track local variable information.
+///
+class DbgVariable {
+private:
+  DIVariable *Var;                   // Variable Descriptor.
+  unsigned FrameIndex;               // Variable frame index.
+
+public:
+  DbgVariable(DIVariable *V, unsigned I) : Var(V), FrameIndex(I)  {}
+  
+  // Accessors.
+  DIVariable *getVariable()  const { return Var; }
+  unsigned getFrameIndex() const { return FrameIndex; }
+};
+
+//===----------------------------------------------------------------------===//
+/// DbgScope - This class is used to track scope information.
+///
+class DbgScope {
+private:
+  DbgScope *Parent;                   // Parent to this scope.
+  DIDescriptor *Desc;                 // Debug info descriptor for scope.
+                                      // Either subprogram or block.
+  unsigned StartLabelID;              // Label ID of the beginning of scope.
+  unsigned EndLabelID;                // Label ID of the end of scope.
+  SmallVector<DbgScope *, 8> Scopes;     // Scopes defined in scope.
+  SmallVector<DbgVariable *, 32> Variables;// Variables declared in scope.
+  
+public:
+  DbgScope(DbgScope *P, DIDescriptor *D)
+  : Parent(P), Desc(D), StartLabelID(0), EndLabelID(0), Scopes(), Variables()
+  {}
+  ~DbgScope();
+  
+  // Accessors.
+  DbgScope *getParent()        const { return Parent; }
+  DIDescriptor *getDesc()       const { return Desc; }
+  unsigned getStartLabelID()     const { return StartLabelID; }
+  unsigned getEndLabelID()       const { return EndLabelID; }
+  SmallVector<DbgScope *, 8> &getScopes() { return Scopes; }
+  SmallVector<DbgVariable *, 32> &getVariables() { return Variables; }
+  void setStartLabelID(unsigned S) { StartLabelID = S; }
+  void setEndLabelID(unsigned E)   { EndLabelID = E; }
+  
+  /// AddScope - Add a scope to the scope.
+  ///
+  void AddScope(DbgScope *S) { Scopes.push_back(S); }
+  
+  /// AddVariable - Add a variable to the scope.
+  ///
+  void AddVariable(DbgVariable *V) { Variables.push_back(V); }
+};
+
 //===----------------------------------------------------------------------===//
 /// DwarfDebug - Emits Dwarf debug directives.
 ///
@@ -1125,6 +1283,7 @@ private:
   /// CompileUnits - All the compile units involved in this build.  The index
   /// of each entry in this vector corresponds to the sources in MMI.
   std::vector<CompileUnit *> CompileUnits;
+  DenseMap<Value *, CompileUnit *> DW_CUs;
 
   /// AbbreviationsSet - Used to uniquely define abbreviations.
   ///
@@ -1136,6 +1295,15 @@ private:
 
   /// ValuesSet - Used to uniquely define values.
   ///
+  // Directories - Uniquing vector for directories.                                       
+  UniqueVector<std::string> Directories;
+
+  // SourceFiles - Uniquing vector for source files.                                      
+  UniqueVector<SrcFileInfo> SrcFiles;
+
+  // Lines - List of of source line correspondence.
+  std::vector<SrcLineInfo> Lines;
+
   FoldingSet<DIEValue> ValuesSet;
 
   /// Values - A list of all the unique values in use.
@@ -1152,7 +1320,7 @@ private:
 
   /// SectionMap - Provides a unique id per text section.
   ///
-  UniqueVector<std::string> SectionMap;
+  UniqueVector<const Section*> SectionMap;
 
   /// SectionSourceLines - Tracks line numbers per text section.
   ///
@@ -1166,6 +1334,44 @@ private:
   ///
   bool shouldEmit;
 
+  // RootScope - Top level scope for the current function.
+  //
+  DbgScope *RootDbgScope;
+  
+  // DbgScopeMap - Tracks the scopes in the current function.
+  DenseMap<GlobalVariable *, DbgScope *> DbgScopeMap;
+  
+  // DbgLabelIDList - One entry per assigned label.  Normally the entry is equal to
+  // the list index(+1).  If the entry is zero then the label has been deleted.
+  // Any other value indicates the label has been deleted by is mapped to
+  // another label.
+  SmallVector<unsigned, 32> DbgLabelIDList;
+
+  /// NextLabelID - Return the next unique label id.
+  ///
+  unsigned NextLabelID() {
+    unsigned ID = (unsigned)DbgLabelIDList.size() + 1;
+    DbgLabelIDList.push_back(ID);
+    return ID;
+  }
+
+  /// RemapLabel - Indicate that a label has been merged into another.
+  ///
+  void RemapLabel(unsigned OldLabelID, unsigned NewLabelID) {
+    assert(0 < OldLabelID && OldLabelID <= DbgLabelIDList.size() &&
+          "Old label ID out of range.");
+    assert(NewLabelID <= DbgLabelIDList.size() &&
+          "New label ID out of range.");
+    DbgLabelIDList[OldLabelID - 1] = NewLabelID;
+  }
+  
+  /// MappedLabel - Find out the label's final ID.  Zero indicates deletion.
+  /// ID != Mapped ID indicates that the label was folded into another label.
+  unsigned MappedLabel(unsigned LabelID) const {
+    assert(LabelID <= DbgLabelIDList.size() && "Debug label ID out of range.");
+    return LabelID ? DbgLabelIDList[LabelID - 1] : 0;
+  }
+
   struct FunctionDebugFrameInfo {
     unsigned Number;
     std::vector<MachineMove> Moves;
@@ -1405,14 +1611,69 @@ private:
     }
   }
 
+  /// AddSourceLine - Add location information to specified debug information
+  /// entry.
+  void AddSourceLine(DIE *Die, DIVariable *V) {
+    unsigned FileID = 0;
+    unsigned Line = V->getLineNumber();
+    if (V->getVersion() < DIDescriptor::Version7) {
+      // Version6 or earlier. Use compile unit info to get file id.
+      CompileUnit *Unit = FindCompileUnit(V->getCompileUnit());
+      FileID = Unit->getID();
+    } else {
+      // Version7 or newer, use filename and directory info from DIVariable
+      // directly.
+      unsigned DID = Directories.idFor(V->getDirectory());
+      FileID = SrcFiles.idFor(SrcFileInfo(DID, V->getFilename()));
+    }
+    AddUInt(Die, DW_AT_decl_file, 0, FileID);
+    AddUInt(Die, DW_AT_decl_line, 0, Line);
+  }
+
+  /// AddSourceLine - Add location information to specified debug information
+  /// entry.
+  void AddSourceLine(DIE *Die, DIGlobal *G) {
+    unsigned FileID = 0;
+    unsigned Line = G->getLineNumber();
+    if (G->getVersion() < DIDescriptor::Version7) {
+      // Version6 or earlier. Use compile unit info to get file id.
+      CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
+      FileID = Unit->getID();
+    } else {
+      // Version7 or newer, use filename and directory info from DIGlobal
+      // directly.
+      unsigned DID = Directories.idFor(G->getDirectory());
+      FileID = SrcFiles.idFor(SrcFileInfo(DID, G->getFilename()));
+    }
+    AddUInt(Die, DW_AT_decl_file, 0, FileID);
+    AddUInt(Die, DW_AT_decl_line, 0, Line);
+  }
+
+  void AddSourceLine(DIE *Die, DIType *G) {
+    unsigned FileID = 0;
+    unsigned Line = G->getLineNumber();
+    if (G->getVersion() < DIDescriptor::Version7) {
+      // Version6 or earlier. Use compile unit info to get file id.
+      CompileUnit *Unit = FindCompileUnit(G->getCompileUnit());
+      FileID = Unit->getID();
+    } else {
+      // Version7 or newer, use filename and directory info from DIGlobal
+      // directly.
+      unsigned DID = Directories.idFor(G->getDirectory());
+      FileID = SrcFiles.idFor(SrcFileInfo(DID, G->getFilename()));
+    }
+    AddUInt(Die, DW_AT_decl_file, 0, FileID);
+    AddUInt(Die, DW_AT_decl_line, 0, Line);
+  }
+
   /// AddAddress - Add an address attribute to a die based on the location
   /// provided.
   void AddAddress(DIE *Die, unsigned Attribute,
                             const MachineLocation &Location) {
-    unsigned Reg = RI->getDwarfRegNum(Location.getRegister(), false);
+    unsigned Reg = RI->getDwarfRegNum(Location.getReg(), false);
     DIEBlock *Block = new DIEBlock();
 
-    if (Location.isRegister()) {
+    if (Location.isReg()) {
       if (Reg < 32) {
         AddUInt(Block, 0, DW_FORM_data1, DW_OP_reg0 + Reg);
       } else {
@@ -1437,36 +1698,23 @@ private:
   void AddBasicType(DIE *Entity, CompileUnit *Unit,
                     const std::string &Name,
                     unsigned Encoding, unsigned Size) {
-    DIE *Die = ConstructBasicType(Unit, Name, Encoding, Size);
-    AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
-  }
 
-  /// ConstructBasicType - Construct a new basic type.
-  ///
-  DIE *ConstructBasicType(CompileUnit *Unit,
-                          const std::string &Name,
-                          unsigned Encoding, unsigned Size) {
     DIE Buffer(DW_TAG_base_type);
     AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
     AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, Encoding);
     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
-    return Unit->AddDie(Buffer);
+    DIE *BasicTypeDie = Unit->AddDie(Buffer);
+    AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, BasicTypeDie);
   }
 
   /// AddPointerType - Add a new pointer type attribute to the specified entity.
   ///
   void AddPointerType(DIE *Entity, CompileUnit *Unit, const std::string &Name) {
-    DIE *Die = ConstructPointerType(Unit, Name);
-    AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, Die);
-  }
-
-  /// ConstructPointerType - Construct a new pointer type.
-  ///
-  DIE *ConstructPointerType(CompileUnit *Unit, const std::string &Name) {
     DIE Buffer(DW_TAG_pointer_type);
     AddUInt(&Buffer, DW_AT_byte_size, 0, TD->getPointerSize());
     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
-    return Unit->AddDie(Buffer);
+    DIE *PointerTypeDie =  Unit->AddDie(Buffer);
+    AddDIEntry(Entity, DW_AT_type, DW_FORM_ref4, PointerTypeDie);
   }
 
   /// AddType - Add a new type attribute to the specified entity.
@@ -1509,6 +1757,317 @@ private:
     }
   }
 
+  /// AddType - Add a new type attribute to the specified entity.
+  void AddType(CompileUnit *DW_Unit, DIE *Entity, DIType Ty) {
+    if (Ty.isNull()) {
+      AddBasicType(Entity, DW_Unit, "", DW_ATE_signed, sizeof(int32_t));
+      return;
+    }
+
+    // Check for pre-existence.
+    DIEntry *&Slot = DW_Unit->getDIEntrySlotFor(Ty.getGV());
+    // If it exists then use the existing value.
+    if (Slot) {
+      Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
+      return;
+    }
+
+    // Set up proxy. 
+    Slot = NewDIEntry();
+
+    // Construct type.
+    DIE Buffer(DW_TAG_base_type);
+    if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
+      ConstructTypeDIE(DW_Unit, Buffer, BT);
+    else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
+      ConstructTypeDIE(DW_Unit, Buffer, DT);
+    else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
+      ConstructTypeDIE(DW_Unit, Buffer, CT);
+
+    // Add debug information entry to entity and unit.
+    DIE *Die = DW_Unit->AddDie(Buffer);
+    SetDIEntry(Slot, Die);
+    Entity->AddValue(DW_AT_type, DW_FORM_ref4, Slot);
+  }
+
+  /// ConstructTypeDIE - Construct basic type die from DIBasicType.
+  void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
+                        DIBasicType *BTy) {
+    
+    // Get core information.
+    const std::string &Name = BTy->getName();
+    Buffer.setTag(DW_TAG_base_type);
+    AddUInt(&Buffer, DW_AT_encoding,  DW_FORM_data1, BTy->getEncoding());
+    // Add name if not anonymous or intermediate type.
+    if (!Name.empty())
+      AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
+    uint64_t Size = BTy->getSizeInBits() >> 3;
+    AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
+  }
+
+  /// ConstructTypeDIE - Construct derived type die from DIDerivedType.
+  void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
+                        DIDerivedType *DTy) {
+
+    // Get core information.
+    const std::string &Name = DTy->getName();
+    uint64_t Size = DTy->getSizeInBits() >> 3;
+    unsigned Tag = DTy->getTag();
+    // FIXME - Workaround for templates.
+    if (Tag == DW_TAG_inheritance) Tag = DW_TAG_reference_type;
+
+    Buffer.setTag(Tag);
+    // Map to main type, void will not have a type.
+    DIType FromTy = DTy->getTypeDerivedFrom();
+    AddType(DW_Unit, &Buffer, FromTy);
+
+    // Add name if not anonymous or intermediate type.
+    if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
+
+    // Add size if non-zero (derived types might be zero-sized.)
+    if (Size)
+      AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
+
+    // Add source line info if available and TyDesc is not a forward
+    // declaration.
+    // FIXME - Enable this. if (!DTy->isForwardDecl())
+    // FIXME - Enable this.     AddSourceLine(&Buffer, *DTy);
+  }
+
+  /// ConstructTypeDIE - Construct type DIE from DICompositeType.
+  void ConstructTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
+                        DICompositeType *CTy) {
+
+    // Get core information.                                                              
+    const std::string &Name = CTy->getName();
+    uint64_t Size = CTy->getSizeInBits() >> 3;
+    unsigned Tag = CTy->getTag();
+    switch (Tag) {
+    case DW_TAG_vector_type:
+    case DW_TAG_array_type:
+      ConstructArrayTypeDIE(DW_Unit, Buffer, CTy);
+      break;
+    //FIXME - Enable this. 
+    // case DW_TAG_enumeration_type:
+    //  DIArray Elements = CTy->getTypeArray();
+    //  // Add enumerators to enumeration type.
+    //  for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) 
+    //   ConstructEnumTypeDIE(Buffer, &Elements.getElement(i));
+    //  break;
+    case DW_TAG_subroutine_type: 
+      {
+        // Add prototype flag.
+        AddUInt(&Buffer, DW_AT_prototyped, DW_FORM_flag, 1);
+        DIArray Elements = CTy->getTypeArray();
+        // Add return type.
+        DIDescriptor RTy = Elements.getElement(0);
+        if (DIBasicType *BT = dyn_cast<DIBasicType>(&RTy))
+          AddType(DW_Unit, &Buffer, *BT);
+        else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&RTy))
+          AddType(DW_Unit, &Buffer, *DT);
+        else if (DICompositeType *CT = dyn_cast<DICompositeType>(&RTy))
+          AddType(DW_Unit, &Buffer, *CT);
+
+        //AddType(DW_Unit, &Buffer, Elements.getElement(0));
+        // Add arguments.
+        for (unsigned i = 1, N = Elements.getNumElements(); i < N; ++i) {
+          DIE *Arg = new DIE(DW_TAG_formal_parameter);
+          DIDescriptor Ty = Elements.getElement(i);
+          if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
+            AddType(DW_Unit, &Buffer, *BT);
+          else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
+            AddType(DW_Unit, &Buffer, *DT);
+          else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
+            AddType(DW_Unit, &Buffer, *CT);
+          Buffer.AddChild(Arg);
+        }
+      }
+      break;
+    case DW_TAG_structure_type:
+    case DW_TAG_union_type: 
+      {
+        // Add elements to structure type.
+        DIArray Elements = CTy->getTypeArray();
+        // Add elements to structure type.
+        for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
+          DIDescriptor Element = Elements.getElement(i);
+          if (DISubprogram *SP = dyn_cast<DISubprogram>(&Element))
+            ConstructFieldTypeDIE(DW_Unit, Buffer, SP);
+          else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Element))
+            ConstructFieldTypeDIE(DW_Unit, Buffer, DT);
+          else if (DIGlobalVariable *GV = dyn_cast<DIGlobalVariable>(&Element))
+            ConstructFieldTypeDIE(DW_Unit, Buffer, GV);
+        }
+      }
+      break;
+    default:
+      break;
+    }
+
+    // Add name if not anonymous or intermediate type.
+    if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
+
+    // Add size if non-zero (derived types might be zero-sized.)
+    if (Size)
+      AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
+    else {
+      // Add zero size even if it is not a forward declaration.
+      // FIXME - Enable this.
+      //      if (!CTy->isDefinition())
+      //        AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
+      //      else
+      //        AddUInt(&Buffer, DW_AT_byte_size, 0, 0); 
+    }
+
+    // Add source line info if available and TyDesc is not a forward
+    // declaration.
+    // FIXME - Enable this.
+    // if (CTy->isForwardDecl())                                            
+    //   AddSourceLine(&Buffer, *CTy);                                    
+  }
+  
+  // ConstructSubrangeDIE - Construct subrange DIE from DISubrange.
+  void ConstructSubrangeDIE (DIE &Buffer, DISubrange *SR, DIE *IndexTy) {
+    int64_t L = SR->getLo();
+    int64_t H = SR->getHi();
+    DIE *DW_Subrange = new DIE(DW_TAG_subrange_type);
+    if (L != H) {
+      AddDIEntry(DW_Subrange, DW_AT_type, DW_FORM_ref4, IndexTy);
+      if (L)
+       AddSInt(DW_Subrange, DW_AT_lower_bound, 0, L);
+        AddSInt(DW_Subrange, DW_AT_upper_bound, 0, H);
+    }
+    Buffer.AddChild(DW_Subrange);
+  }
+
+  /// ConstructArrayTypeDIE - Construct array type DIE from DICompositeType.
+  void ConstructArrayTypeDIE(CompileUnit *DW_Unit, DIE &Buffer, 
+                             DICompositeType *CTy) {
+    Buffer.setTag(DW_TAG_array_type);
+    if (CTy->getTag() == DW_TAG_vector_type)
+      AddUInt(&Buffer, DW_AT_GNU_vector, DW_FORM_flag, 1);
+    
+    DIArray Elements = CTy->getTypeArray();
+    // FIXME - Enable this. 
+    AddType(DW_Unit, &Buffer, CTy->getTypeDerivedFrom());
+
+    // Construct an anonymous type for index type.
+    DIE IdxBuffer(DW_TAG_base_type);
+    AddUInt(&IdxBuffer, DW_AT_byte_size, 0, sizeof(int32_t));
+    AddUInt(&IdxBuffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
+    DIE *IndexTy = DW_Unit->AddDie(IdxBuffer);
+
+    // Add subranges to array type.
+    for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
+      DIDescriptor Element = Elements.getElement(i);
+      if (DISubrange *SR = dyn_cast<DISubrange>(&Element))
+        ConstructSubrangeDIE(Buffer, SR, IndexTy);
+    }
+  }
+
+  /// ConstructEnumTypeDIE - Construct enum type DIE from 
+  /// DIEnumerator.
+  void ConstructEnumTypeDIE(CompileUnit *DW_Unit, 
+                            DIE &Buffer, DIEnumerator *ETy) {
+
+    DIE *Enumerator = new DIE(DW_TAG_enumerator);
+    AddString(Enumerator, DW_AT_name, DW_FORM_string, ETy->getName());
+    int64_t Value = ETy->getEnumValue();                             
+    AddSInt(Enumerator, DW_AT_const_value, DW_FORM_sdata, Value);
+    Buffer.AddChild(Enumerator);
+  }
+
+  /// ConstructFieldTypeDIE - Construct variable DIE for a struct field.
+  void ConstructFieldTypeDIE(CompileUnit *DW_Unit,
+                             DIE &Buffer, DIGlobalVariable *V) {
+
+    DIE *VariableDie = new DIE(DW_TAG_variable);
+    const std::string &LinkageName = V->getLinkageName();
+    if (!LinkageName.empty())
+      AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
+                LinkageName);
+    // FIXME - Enable this. AddSourceLine(VariableDie, V);
+    AddType(DW_Unit, VariableDie, V->getType());
+    if (!V->isLocalToUnit())
+      AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);
+    AddUInt(VariableDie, DW_AT_declaration, DW_FORM_flag, 1);
+    Buffer.AddChild(VariableDie);
+  }
+
+  /// ConstructFieldTypeDIE - Construct subprogram DIE for a struct field.
+  void ConstructFieldTypeDIE(CompileUnit *DW_Unit,
+                             DIE &Buffer, DISubprogram *SP,
+                             bool IsConstructor = false) {
+    DIE *Method = new DIE(DW_TAG_subprogram);
+    AddString(Method, DW_AT_name, DW_FORM_string, SP->getName());
+    const std::string &LinkageName = SP->getLinkageName();
+    if (!LinkageName.empty())
+      AddString(Method, DW_AT_MIPS_linkage_name, DW_FORM_string, LinkageName);
+    // FIXME - Enable this. AddSourceLine(Method, SP);
+
+    DICompositeType MTy = SP->getType();
+    DIArray Args = MTy.getTypeArray();
+
+    // Add Return Type.
+    if (!IsConstructor) {
+      DIDescriptor Ty = Args.getElement(0);
+      if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
+        AddType(DW_Unit, Method, *BT);
+      else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
+        AddType(DW_Unit, Method, *DT);
+      else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
+        AddType(DW_Unit, Method, *CT);
+    }
+
+    // Add arguments.
+    for (unsigned i = 1, N =  Args.getNumElements(); i < N; ++i) {
+      DIE *Arg = new DIE(DW_TAG_formal_parameter);
+      DIDescriptor Ty = Args.getElement(i);
+      if (DIBasicType *BT = dyn_cast<DIBasicType>(&Ty))
+        AddType(DW_Unit, Method, *BT);
+      else if (DIDerivedType *DT = dyn_cast<DIDerivedType>(&Ty))
+        AddType(DW_Unit, Method, *DT);
+      else if (DICompositeType *CT = dyn_cast<DICompositeType>(&Ty))
+        AddType(DW_Unit, Method, *CT);
+      AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1); // ???
+      Method->AddChild(Arg);
+    }
+
+    if (!SP->isLocalToUnit())
+      AddUInt(Method, DW_AT_external, DW_FORM_flag, 1);                     
+    Buffer.AddChild(Method);
+  }
+
+  /// COnstructFieldTypeDIE - Construct derived type DIE for a struct field.
+ void ConstructFieldTypeDIE(CompileUnit *DW_Unit, DIE &Buffer,
+                            DIDerivedType *DTy) {
+    unsigned Tag = DTy->getTag();
+    DIE *MemberDie = new DIE(Tag);
+    if (!DTy->getName().empty())
+      AddString(MemberDie, DW_AT_name, DW_FORM_string, DTy->getName());
+    // FIXME - Enable this. AddSourceLine(MemberDie, DTy);
+
+    DIType FromTy = DTy->getTypeDerivedFrom();
+    AddType(DW_Unit, MemberDie, FromTy);
+
+    uint64_t Size = DTy->getSizeInBits();
+    uint64_t Offset = DTy->getOffsetInBits();
+
+    // FIXME Handle bitfields                                                      
+
+    // Add size.
+    AddUInt(MemberDie, DW_AT_bit_size, 0, Size);
+    // Add computation for offset.                                                        
+    DIEBlock *Block = new DIEBlock();
+    AddUInt(Block, 0, DW_FORM_data1, DW_OP_plus_uconst);
+    AddUInt(Block, 0, DW_FORM_udata, Offset >> 3);
+    AddBlock(MemberDie, DW_AT_data_member_location, 0, Block);
+
+    // FIXME Handle DW_AT_accessibility.
+
+    Buffer.AddChild(MemberDie);
+  }
+
   /// ConstructType - Adds all the required attributes to the type.
   ///
   void ConstructType(DIE &Buffer, TypeDesc *TyDesc, CompileUnit *Unit) {
@@ -1555,11 +2114,13 @@ private:
         Size = 0;
 
         // Construct an anonymous type for index type.
-        DIE *IndexTy = ConstructBasicType(Unit, "", DW_ATE_signed,
-                                          sizeof(int32_t));
+        DIE Buffer(DW_TAG_base_type);
+        AddUInt(&Buffer, DW_AT_byte_size, 0, sizeof(int32_t));
+        AddUInt(&Buffer, DW_AT_encoding, DW_FORM_data1, DW_ATE_signed);
+        DIE *IndexTy = Unit->AddDie(Buffer);
 
         // Add subranges to array type.
-        for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
+        for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
           SubrangeDesc *SRD = cast<SubrangeDesc>(Elements[i]);
           int64_t Lo = SRD->getLo();
           int64_t Hi = SRD->getHi();
@@ -1580,12 +2141,11 @@ private:
       case DW_TAG_structure_type:
       case DW_TAG_union_type: {
         // Add elements to structure type.
-        for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
+        for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
           DebugInfoDesc *Element = Elements[i];
 
           if (DerivedTypeDesc *MemberDesc = dyn_cast<DerivedTypeDesc>(Element)){
             // Add field or base class.
-
             unsigned Tag = MemberDesc->getTag();
 
             // Extract the basic information.
@@ -1600,6 +2160,7 @@ private:
             // Add name if not "".
             if (!Name.empty())
               AddString(Member, DW_AT_name, DW_FORM_string, Name);
+
             // Add location if available.
             AddSourceLine(Member, MemberDesc->getFile(), MemberDesc->getLine());
 
@@ -1616,7 +2177,7 @@ private:
             while (FromTy) {
               if (FromTy->getTag() != DW_TAG_typedef) {
                 FieldSize = FromTy->getSize();
-                FieldAlign = FromTy->getSize();
+                FieldAlign = FromTy->getAlign();
                 break;
               }
 
@@ -1723,7 +2284,7 @@ private:
               }
 
               // Add arguments.
-              for(unsigned i = 1, N = Args.size(); i < N; ++i) {
+              for (unsigned i = 1, N = Args.size(); i < N; ++i) {
                 DIE *Arg = new DIE(DW_TAG_formal_parameter);
                 AddType(Arg, cast<TypeDesc>(Args[i]), Unit);
                 AddUInt(Arg, DW_AT_artificial, DW_FORM_flag, 1);
@@ -1743,7 +2304,7 @@ private:
       }
       case DW_TAG_enumeration_type: {
         // Add enumerators to enumeration type.
-        for(unsigned i = 0, N = Elements.size(); i < N; ++i) {
+        for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
           EnumeratorDesc *ED = cast<EnumeratorDesc>(Elements[i]);
           const std::string &Name = ED->getName();
           int64_t Value = ED->getValue();
@@ -1762,7 +2323,7 @@ private:
         AddType(&Buffer, dyn_cast<TypeDesc>(Elements[0]), Unit);
 
         // Add arguments.
-        for(unsigned i = 1, N = Elements.size(); i < N; ++i) {
+        for (unsigned i = 1, N = Elements.size(); i < N; ++i) {
           DIE *Arg = new DIE(DW_TAG_formal_parameter);
           AddType(Arg, cast<TypeDesc>(Elements[i]), Unit);
           Buffer.AddChild(Arg);
@@ -1774,12 +2335,25 @@ private:
       }
     }
 
-    // Add size if non-zero (derived types don't have a size.)
-    if (Size) AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
     // Add name if not anonymous or intermediate type.
     if (!Name.empty()) AddString(&Buffer, DW_AT_name, DW_FORM_string, Name);
-    // Add source line info if available.
-    AddSourceLine(&Buffer, TyDesc->getFile(), TyDesc->getLine());
+
+    // Add size if non-zero (derived types might be zero-sized.)
+    if (Size)
+      AddUInt(&Buffer, DW_AT_byte_size, 0, Size);
+    else if (isa<CompositeTypeDesc>(TyDesc)) {
+      // If TyDesc is a composite type, then add size even if it's zero unless
+      // it's a forward declaration.
+      if (TyDesc->isForwardDecl())
+        AddUInt(&Buffer, DW_AT_declaration, DW_FORM_flag, 1);
+      else
+        AddUInt(&Buffer, DW_AT_byte_size, 0, 0);
+    }
+
+    // Add source line info if available and TyDesc is not a forward
+    // declaration.
+    if (!TyDesc->isForwardDecl())
+      AddSourceLine(&Buffer, TyDesc->getFile(), TyDesc->getLine());
   }
 
   /// NewCompileUnit - Create new compile unit and it's debug information entry.
@@ -1792,7 +2366,8 @@ private:
     AddString(Die, DW_AT_producer,  DW_FORM_string, UnitDesc->getProducer());
     AddUInt  (Die, DW_AT_language,  DW_FORM_data1,  UnitDesc->getLanguage());
     AddString(Die, DW_AT_name,      DW_FORM_string, UnitDesc->getFileName());
-    AddString(Die, DW_AT_comp_dir,  DW_FORM_string, UnitDesc->getDirectory());
+    if (!UnitDesc->getDirectory().empty())
+      AddString(Die, DW_AT_comp_dir,  DW_FORM_string, UnitDesc->getDirectory());
 
     // Construct compile unit.
     CompileUnit *Unit = new CompileUnit(UnitDesc, ID, Die);
@@ -1819,6 +2394,14 @@ private:
     return Unit;
   }
 
+  /// FindCompileUnit - Get the compile unit for the given descriptor.                    
+  ///                                                                                     
+  CompileUnit *FindCompileUnit(DICompileUnit Unit) {
+    CompileUnit *DW_Unit = DW_CUs[Unit.getGV()];
+    assert(DW_Unit && "Missing compile unit.");
+    return DW_Unit;
+  }
+
   /// NewGlobalVariable - Add a new global variable DIE.
   ///
   DIE *NewGlobalVariable(GlobalVariableDesc *GVD) {
@@ -1948,6 +2531,235 @@ private:
     return VariableDie;
   }
 
+  /// NewScopeVariable - Create a new scope variable.
+  ///
+  DIE *NewDbgScopeVariable(DbgVariable *DV, CompileUnit *Unit) {
+    // Get the descriptor.
+    DIVariable *VD = DV->getVariable();
+
+    // Translate tag to proper Dwarf tag.  The result variable is dropped for
+    // now.
+    unsigned Tag;
+    switch (VD->getTag()) {
+    case DW_TAG_return_variable:  return NULL;
+    case DW_TAG_arg_variable:     Tag = DW_TAG_formal_parameter; break;
+    case DW_TAG_auto_variable:    // fall thru
+    default:                      Tag = DW_TAG_variable; break;
+    }
+
+    // Define variable debug information entry.
+    DIE *VariableDie = new DIE(Tag);
+    AddString(VariableDie, DW_AT_name, DW_FORM_string, VD->getName());
+
+    // Add source line info if available.
+    AddSourceLine(VariableDie, VD);
+
+    // Add variable type.
+    AddType(Unit, VariableDie, VD->getType());
+
+    // Add variable address.
+    MachineLocation Location;
+    Location.set(RI->getFrameRegister(*MF),
+                 RI->getFrameIndexOffset(*MF, DV->getFrameIndex()));
+    AddAddress(VariableDie, DW_AT_location, Location);
+
+    return VariableDie;
+  }
+
+  unsigned RecordSourceLine(Value *V, unsigned Line, unsigned Col) {
+    CompileUnit *Unit = DW_CUs[V];
+    assert (Unit && "Unable to find CompileUnit");
+    unsigned ID = NextLabelID();
+    Lines.push_back(SrcLineInfo(Line, Col, Unit->getID(), ID));
+    return ID;
+  }
+  
+  unsigned getRecordSourceLineCount() {
+    return Lines.size();
+  }
+                            
+  unsigned RecordSource(const std::string &Directory,
+                        const std::string &File) {
+    unsigned DID = Directories.insert(Directory);
+    return SrcFiles.insert(SrcFileInfo(DID,File));
+  }
+
+  /// RecordRegionStart - Indicate the start of a region.
+  ///
+  unsigned RecordRegionStart(GlobalVariable *V) {
+    DbgScope *Scope = getOrCreateScope(V);
+    unsigned ID = NextLabelID();
+    if (!Scope->getStartLabelID()) Scope->setStartLabelID(ID);
+    return ID;
+  }
+
+  /// RecordRegionEnd - Indicate the end of a region.
+  ///
+  unsigned RecordRegionEnd(GlobalVariable *V) {
+    DbgScope *Scope = getOrCreateScope(V);
+    unsigned ID = NextLabelID();
+    Scope->setEndLabelID(ID);
+    return ID;
+  }
+
+  /// RecordVariable - Indicate the declaration of  a local variable.
+  ///
+  void RecordVariable(GlobalVariable *GV, unsigned FrameIndex) {
+    DbgScope *Scope = getOrCreateScope(GV);
+    DIVariable *VD = new DIVariable(GV);
+    DbgVariable *DV = new DbgVariable(VD, FrameIndex);
+    Scope->AddVariable(DV);
+  }
+
+  /// getOrCreateScope - Returns the scope associated with the given descriptor.
+  ///
+  DbgScope *getOrCreateScope(GlobalVariable *V) {
+    DbgScope *&Slot = DbgScopeMap[V];
+    if (!Slot) {
+      // FIXME - breaks down when the context is an inlined function.
+      DIDescriptor ParentDesc;
+      DIBlock *DB = new DIBlock(V);
+      if (DIBlock *Block = dyn_cast<DIBlock>(DB)) {
+        ParentDesc = Block->getContext();
+      }
+      DbgScope *Parent = ParentDesc.isNull() ? 
+        getOrCreateScope(ParentDesc.getGV()) : NULL;
+      Slot = new DbgScope(Parent, DB);
+      if (Parent) {
+        Parent->AddScope(Slot);
+      } else if (RootDbgScope) {
+        // FIXME - Add inlined function scopes to the root so we can delete
+        // them later.  Long term, handle inlined functions properly.
+        RootDbgScope->AddScope(Slot);
+      } else {
+        // First function is top level function.
+        RootDbgScope = Slot;
+      }
+    }
+    return Slot;
+  }
+
+  /// ConstructDbgScope - Construct the components of a scope.
+  ///
+  void ConstructDbgScope(DbgScope *ParentScope,
+                         unsigned ParentStartID, unsigned ParentEndID,
+                         DIE *ParentDie, CompileUnit *Unit) {
+    // Add variables to scope.
+    SmallVector<DbgVariable *, 32> &Variables = ParentScope->getVariables();
+    for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
+      DIE *VariableDie = NewDbgScopeVariable(Variables[i], Unit);
+      if (VariableDie) ParentDie->AddChild(VariableDie);
+    }
+
+    // Add nested scopes.
+    SmallVector<DbgScope *, 8> &Scopes = ParentScope->getScopes();
+    for (unsigned j = 0, M = Scopes.size(); j < M; ++j) {
+      // Define the Scope debug information entry.
+      DbgScope *Scope = Scopes[j];
+      // FIXME - Ignore inlined functions for the time being.
+      if (!Scope->getParent()) continue;
+
+      unsigned StartID = MappedLabel(Scope->getStartLabelID());
+      unsigned EndID = MappedLabel(Scope->getEndLabelID());
+
+      // Ignore empty scopes.
+      if (StartID == EndID && StartID != 0) continue;
+      if (Scope->getScopes().empty() && Scope->getVariables().empty()) continue;
+
+      if (StartID == ParentStartID && EndID == ParentEndID) {
+        // Just add stuff to the parent scope.
+        ConstructDbgScope(Scope, ParentStartID, ParentEndID, ParentDie, Unit);
+      } else {
+        DIE *ScopeDie = new DIE(DW_TAG_lexical_block);
+
+        // Add the scope bounds.
+        if (StartID) {
+          AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
+                             DWLabel("label", StartID));
+        } else {
+          AddLabel(ScopeDie, DW_AT_low_pc, DW_FORM_addr,
+                             DWLabel("func_begin", SubprogramCount));
+        }
+        if (EndID) {
+          AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
+                             DWLabel("label", EndID));
+        } else {
+          AddLabel(ScopeDie, DW_AT_high_pc, DW_FORM_addr,
+                             DWLabel("func_end", SubprogramCount));
+        }
+
+        // Add the scope contents.
+        ConstructDbgScope(Scope, StartID, EndID, ScopeDie, Unit);
+        ParentDie->AddChild(ScopeDie);
+      }
+    }
+  }
+
+  /// ConstructRootDbgScope - Construct the scope for the subprogram.
+  ///
+  void ConstructRootDbgScope(DbgScope *RootScope) {
+    // Exit if there is no root scope.
+    if (!RootScope) return;
+
+    // Get the subprogram debug information entry.
+    DISubprogram *SPD = cast<DISubprogram>(RootScope->getDesc());
+
+    // Get the compile unit context.
+    CompileUnit *Unit = FindCompileUnit(SPD->getCompileUnit());
+
+    // Get the subprogram die.
+    DIE *SPDie = Unit->getDieMapSlotFor(SPD->getGV());
+    assert(SPDie && "Missing subprogram descriptor");
+
+    // Add the function bounds.
+    AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
+                    DWLabel("func_begin", SubprogramCount));
+    AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
+                    DWLabel("func_end", SubprogramCount));
+    MachineLocation Location(RI->getFrameRegister(*MF));
+    AddAddress(SPDie, DW_AT_frame_base, Location);
+
+    ConstructDbgScope(RootScope, 0, 0, SPDie, Unit);
+  }
+
+  /// ConstructDefaultDbgScope - Construct a default scope for the subprogram.
+  ///
+  void ConstructDefaultDbgScope(MachineFunction *MF) {
+    // Find the correct subprogram descriptor.
+    std::string SPName = "llvm.dbg.subprograms";
+    std::vector<GlobalVariable*> Result;
+    getGlobalVariablesUsing(*M, SPName, Result);
+    for (std::vector<GlobalVariable *>::iterator I = Result.begin(),
+           E = Result.end(); I != E; ++I) {
+
+      DISubprogram *SPD = new DISubprogram(*I);
+
+      if (SPD->getName() == MF->getFunction()->getName()) {
+        // Get the compile unit context.
+        CompileUnit *Unit = FindCompileUnit(SPD->getCompileUnit());
+
+        // Get the subprogram die.
+        DIE *SPDie = Unit->getDieMapSlotFor(SPD->getGV());
+        assert(SPDie && "Missing subprogram descriptor");
+
+        // Add the function bounds.
+        AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
+                 DWLabel("func_begin", SubprogramCount));
+        AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
+                 DWLabel("func_end", SubprogramCount));
+
+        MachineLocation Location(RI->getFrameRegister(*MF));
+        AddAddress(SPDie, DW_AT_frame_base, Location);
+        return;
+      }
+    }
+#if 0
+    // FIXME: This is causing an abort because C++ mangled names are compared
+    // with their unmangled counterparts. See PR2885. Don't do this assert.
+    assert(0 && "Couldn't find DIE for machine function!");
+#endif
+  }
+
   /// ConstructScope - Construct the components of a scope.
   ///
   void ConstructScope(DebugScope *ParentScope,
@@ -2031,6 +2843,42 @@ private:
     ConstructScope(RootScope, 0, 0, SPDie, Unit);
   }
 
+  /// ConstructDefaultScope - Construct a default scope for the subprogram.
+  ///
+  void ConstructDefaultScope(MachineFunction *MF) {
+    // Find the correct subprogram descriptor.
+    std::vector<SubprogramDesc *> Subprograms;
+    MMI->getAnchoredDescriptors<SubprogramDesc>(*M, Subprograms);
+
+    for (unsigned i = 0, N = Subprograms.size(); i < N; ++i) {
+      SubprogramDesc *SPD = Subprograms[i];
+
+      if (SPD->getName() == MF->getFunction()->getName()) {
+        // Get the compile unit context.
+        CompileUnit *Unit = GetBaseCompileUnit();
+
+        // Get the subprogram die.
+        DIE *SPDie = Unit->getDieMapSlotFor(SPD);
+        assert(SPDie && "Missing subprogram descriptor");
+
+        // Add the function bounds.
+        AddLabel(SPDie, DW_AT_low_pc, DW_FORM_addr,
+                 DWLabel("func_begin", SubprogramCount));
+        AddLabel(SPDie, DW_AT_high_pc, DW_FORM_addr,
+                 DWLabel("func_end", SubprogramCount));
+
+        MachineLocation Location(RI->getFrameRegister(*MF));
+        AddAddress(SPDie, DW_AT_frame_base, Location);
+        return;
+      }
+    }
+#if 0
+    // FIXME: This is causing an abort because C++ mangled names are compared
+    // with their unmangled counterparts. See PR2885. Don't do this assert.
+    assert(0 && "Couldn't find DIE for machine function!");
+#endif
+  }
+
   /// EmitInitial - Emit initial Dwarf declarations.  This is necessary for cc
   /// tools to recognize the object file contains Dwarf information.
   void EmitInitial() {
@@ -2062,9 +2910,9 @@ private:
     Asm->SwitchToDataSection(TAI->getDwarfRangesSection());
     EmitLabel("section_ranges", 0);
 
-    Asm->SwitchToTextSection(TAI->getTextSection());
+    Asm->SwitchToSection(TAI->getTextSection());
     EmitLabel("text_begin", 0);
-    Asm->SwitchToDataSection(TAI->getDataSection());
+    Asm->SwitchToSection(TAI->getDataSection());
     EmitLabel("data_begin", 0);
   }
 
@@ -2353,9 +3201,10 @@ private:
       // Isolate current sections line info.
       const std::vector<SourceLineInfo> &LineInfos = SectionSourceLines[j];
 
-      if (VerboseAsm)
-        Asm->EOL(std::string("Section ") + SectionMap[j + 1]);
-      else
+      if (VerboseAsm) {
+        const Section* S = SectionMap[j + 1];
+        Asm->EOL(std::string("Section ") + S->getName());
+      } else
         Asm->EOL();
 
       // Dwarf assumes we start with first line of first source file.
@@ -2587,7 +3436,7 @@ private:
     Asm->SwitchToDataSection(TAI->getDwarfARangesSection());
 
     // FIXME - Mock up
-  #if 0
+#if 0
     CompileUnit *Unit = GetBaseCompileUnit();
 
     // Don't include size of length
@@ -2611,7 +3460,7 @@ private:
 
     Asm->EmitInt32(0); Asm->EOL("EOM (1)");
     Asm->EmitInt32(0); Asm->EOL("EOM (2)");
-  #endif
+#endif
 
     Asm->EOL();
   }
@@ -2634,6 +3483,32 @@ private:
     Asm->EOL();
   }
 
+  /// ConstructCompileUnits - Create a compile unit DIEs.
+  void ConstructCompileUnits() {
+    std::string CUName = "llvm.dbg.compile_units";
+    std::vector<GlobalVariable*> Result;
+    getGlobalVariablesUsing(*M, CUName, Result);
+    for (std::vector<GlobalVariable *>::iterator RI = Result.begin(),
+           RE = Result.end(); RI != RE; ++RI) {
+      DICompileUnit *DIUnit = new DICompileUnit(*RI);
+      unsigned ID = RecordSource(DIUnit->getDirectory(),
+                                 DIUnit->getFilename());
+
+      DIE *Die = new DIE(DW_TAG_compile_unit);
+      AddSectionOffset(Die, DW_AT_stmt_list, DW_FORM_data4,
+                       DWLabel("section_line", 0), DWLabel("section_line", 0),
+                       false);
+      AddString(Die, DW_AT_producer, DW_FORM_string, DIUnit->getProducer());
+      AddUInt(Die, DW_AT_language, DW_FORM_data1, DIUnit->getLanguage());
+      AddString(Die, DW_AT_name, DW_FORM_string, DIUnit->getFilename());
+      if (!DIUnit->getDirectory().empty())
+        AddString(Die, DW_AT_comp_dir, DW_FORM_string, DIUnit->getDirectory());
+
+      CompileUnit *Unit = new CompileUnit(ID, Die);
+      DW_CUs[DIUnit->getGV()] = Unit;
+    }
+  }
+
   /// ConstructCompileUnitDIEs - Create a compile unit DIE for each source and
   /// header file.
   void ConstructCompileUnitDIEs() {
@@ -2646,6 +3521,53 @@ private:
     }
   }
 
+  /// ConstructGlobalVariableDIEs - Create DIEs for each of the externally 
+  /// visible global variables.
+  void ConstructGlobalVariableDIEs() {
+    std::string GVName = "llvm.dbg.global_variables";
+    std::vector<GlobalVariable*> Result;
+    getGlobalVariablesUsing(*M, GVName, Result);
+    for (std::vector<GlobalVariable *>::iterator GVI = Result.begin(),
+           GVE = Result.end(); GVI != GVE; ++GVI) {
+      DIGlobalVariable *DI_GV = new DIGlobalVariable(*GVI);
+      CompileUnit *DW_Unit = FindCompileUnit(DI_GV->getCompileUnit());
+
+      // Check for pre-existence.
+      DIE *&Slot = DW_Unit->getDieMapSlotFor(DI_GV->getGV());
+      if (Slot) continue;
+
+      DIE *VariableDie = new DIE(DW_TAG_variable);
+      AddString(VariableDie, DW_AT_name, DW_FORM_string, DI_GV->getName());
+      const std::string &LinkageName  = DI_GV->getLinkageName();
+      if (!LinkageName.empty())
+        AddString(VariableDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
+                  LinkageName);
+      AddType(DW_Unit, VariableDie, DI_GV->getType());
+
+      if (!DI_GV->isLocalToUnit())
+        AddUInt(VariableDie, DW_AT_external, DW_FORM_flag, 1);              
+
+      // Add source line info, if available.
+      AddSourceLine(VariableDie, DI_GV);
+
+      // Add address.
+      DIEBlock *Block = new DIEBlock();
+      AddUInt(Block, 0, DW_FORM_data1, DW_OP_addr);
+      AddObjectLabel(Block, 0, DW_FORM_udata,
+                     Asm->getGlobalLinkName(DI_GV->getGV()));
+      AddBlock(VariableDie, DW_AT_location, 0, Block);
+
+      //Add to map.
+      Slot = VariableDie;
+
+      //Add to context owner.
+      DW_Unit->getDie()->AddChild(VariableDie);
+
+      //Expose as global. FIXME - need to check external flag.
+      DW_Unit->AddGlobal(DI_GV->getName(), VariableDie);
+    }
+  }
+
   /// ConstructGlobalDIEs - Create DIEs for each of the externally visible
   /// global variables.
   void ConstructGlobalDIEs() {
@@ -2658,6 +3580,45 @@ private:
     }
   }
 
+  /// ConstructSubprograms - Create DIEs for each of the externally visible
+  /// subprograms.
+  void ConstructSubprograms() {
+
+    std::string SPName = "llvm.dbg.subprograms";
+    std::vector<GlobalVariable*> Result;
+    getGlobalVariablesUsing(*M, SPName, Result);
+    for (std::vector<GlobalVariable *>::iterator RI = Result.begin(),
+           RE = Result.end(); RI != RE; ++RI) {
+
+      DISubprogram *SP = new DISubprogram(*RI);
+      CompileUnit *Unit = FindCompileUnit(SP->getCompileUnit());
+
+      // Check for pre-existence.                                                         
+      DIE *&Slot = Unit->getDieMapSlotFor(SP->getGV());
+      if (Slot) continue;
+
+      DIE *SubprogramDie = new DIE(DW_TAG_subprogram);
+      AddString(SubprogramDie, DW_AT_name, DW_FORM_string, SP->getName());
+      const std::string &LinkageName = SP->getLinkageName();
+      if (!LinkageName.empty())
+        AddString(SubprogramDie, DW_AT_MIPS_linkage_name, DW_FORM_string,
+                  LinkageName);
+      DIType SPTy = SP->getType();
+      AddType(Unit, SubprogramDie, SPTy);
+      if (!SP->isLocalToUnit())
+        AddUInt(SubprogramDie, DW_AT_external, DW_FORM_flag, 1);
+      AddUInt(SubprogramDie, DW_AT_prototyped, DW_FORM_flag, 1);
+
+      AddSourceLine(SubprogramDie, SP);
+      //Add to map.
+      Slot = SubprogramDie;
+      //Add to context owner.
+      Unit->getDie()->AddChild(SubprogramDie);
+      //Expose as global.
+      Unit->AddGlobal(SP->getName(), SubprogramDie);
+    }
+  }
+
   /// ConstructSubprogramDIEs - Create DIEs for each of the externally visible
   /// subprograms.
   void ConstructSubprogramDIEs() {
@@ -2687,6 +3648,7 @@ public:
   , SectionSourceLines()
   , didInitial(false)
   , shouldEmit(false)
+  , RootDbgScope(NULL)
   {
   }
   virtual ~DwarfDebug() {
@@ -2696,6 +3658,39 @@ public:
       delete Values[j];
   }
 
+  /// SetDebugInfo - Create global DIEs and emit initial debug info sections.
+  /// This is inovked by the target AsmPrinter.
+  void SetDebugInfo() {
+    // FIXME - Check if the module has debug info or not.
+      // Create all the compile unit DIEs.
+      ConstructCompileUnits();
+
+      // Create DIEs for each of the externally visible global variables.
+      ConstructGlobalVariableDIEs();
+
+      // Create DIEs for each of the externally visible subprograms.
+      ConstructSubprograms();
+
+      // Prime section data.
+      SectionMap.insert(TAI->getTextSection());
+
+      // Print out .file directives to specify files for .loc directives. These
+      // are printed out early so that they precede any .loc directives.
+      if (TAI->hasDotLocAndDotFile()) {
+        for (unsigned i = 1, e = SrcFiles.size(); i <= e; ++i) {
+          sys::Path FullPath(Directories[SrcFiles[i].getDirectoryID()]);
+          bool AppendOk = FullPath.appendComponent(SrcFiles[i].getName());
+          assert(AppendOk && "Could not append filename to directory!");
+          AppendOk = false;
+          Asm->EmitFile(i, FullPath.toString());
+          Asm->EOL();
+        }
+      }
+
+      // Emit initial sections
+      EmitInitial();
+  }
+
   /// SetModuleInfo - Set machine module information when it's known that pass
   /// manager has created it.  Set by the target AsmPrinter.
   void SetModuleInfo(MachineModuleInfo *mmi) {
@@ -2725,6 +3720,7 @@ public:
           sys::Path FullPath(Directories[SourceFiles[i].getDirectoryID()]);
           bool AppendOk = FullPath.appendComponent(SourceFiles[i].getName());
           assert(AppendOk && "Could not append filename to directory!");
+          AppendOk = false;
           Asm->EmitFile(i, FullPath.toString());
           Asm->EOL();
         }
@@ -2747,14 +3743,14 @@ public:
     if (!ShouldEmitDwarf()) return;
 
     // Standard sections final addresses.
-    Asm->SwitchToTextSection(TAI->getTextSection());
+    Asm->SwitchToSection(TAI->getTextSection());
     EmitLabel("text_end", 0);
-    Asm->SwitchToDataSection(TAI->getDataSection());
+    Asm->SwitchToSection(TAI->getDataSection());
     EmitLabel("data_end", 0);
 
     // End text sections.
     for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
-      Asm->SwitchToTextSection(SectionMap[i].c_str());
+      Asm->SwitchToSection(SectionMap[i]);
       EmitLabel("section_end", i);
     }
 
@@ -2821,7 +3817,7 @@ public:
 
   /// EndFunction - Gather and emit post-function debug information.
   ///
-  void EndFunction() {
+  void EndFunction(MachineFunction *MF) {
     if (!ShouldEmitDwarf()) return;
 
     // Define end label for subprogram.
@@ -2832,7 +3828,7 @@ public:
 
     if (!LineInfos.empty()) {
       // Get section line info.
-      unsigned ID = SectionMap.insert(Asm->CurrentSection);
+      unsigned ID = SectionMap.insert(Asm->CurrentSection_);
       if (SectionSourceLines.size() < ID) SectionSourceLines.resize(ID);
       std::vector<SourceLineInfo> &SectionLineInfos = SectionSourceLines[ID-1];
       // Append the function info to section info.
@@ -2841,7 +3837,18 @@ public:
     }
 
     // Construct scopes for subprogram.
-    ConstructRootScope(MMI->getRootScope());
+    if (MMI->getRootScope())
+      ConstructRootScope(MMI->getRootScope());
+    else
+      // FIXME: This is wrong. We are essentially getting past a problem with
+      // debug information not being able to handle unreachable blocks that have
+      // debug information in them. In particular, those unreachable blocks that
+      // have "region end" info in them. That situation results in the "root
+      // scope" not being created. If that's the case, then emit a "default"
+      // scope, i.e., one that encompasses the whole function. This isn't
+      // desirable. And a better way of handling this (and all of the debugging
+      // information) needs to be explored.
+      ConstructDefaultScope(MF);
 
     DebugFrames.push_back(FunctionDebugFrameInfo(SubprogramCount,
                                                  MMI->getFrameMoves()));
@@ -2900,6 +3907,9 @@ private:
 
     // Begin eh frame section.
     Asm->SwitchToTextSection(TAI->getDwarfEHFrameSection());
+
+    if (!TAI->doesRequireNonLocalEHFrameLabel())
+      O << TAI->getEHGlobalPrefix();
     O << "EH_frame" << Index << ":\n";
     EmitLabel("section_eh_frame", Index);
 
@@ -2954,11 +3964,13 @@ private:
 
       Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
       Asm->EOL("LSDA Encoding (pcrel sdata4)");
+
       Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
       Asm->EOL("FDE Encoding (pcrel sdata4)");
    } else {
       Asm->EmitULEB128Bytes(1);
       Asm->EOL("Augmentation Size");
+
       Asm->EmitInt8(DW_EH_PE_pcrel | DW_EH_PE_sdata4);
       Asm->EOL("FDE Encoding (pcrel sdata4)");
     }
@@ -3027,9 +4039,18 @@ private:
 
       EmitLabel("eh_frame_begin", EHFrameInfo.Number);
 
-      EmitSectionOffset("eh_frame_begin", "eh_frame_common",
-                        EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
-                        true, true, false);
+      if (TAI->doesRequireNonLocalEHFrameLabel()) {
+        PrintRelDirective(true, true);
+        PrintLabelName("eh_frame_begin", EHFrameInfo.Number);
+
+        if (!TAI->isAbsoluteEHSectionOffsets())
+          O << "-EH_frame" << EHFrameInfo.PersonalityIndex;
+      } else {
+        EmitSectionOffset("eh_frame_begin", "eh_frame_common",
+                          EHFrameInfo.Number, EHFrameInfo.PersonalityIndex,
+                          true, true, false);
+      }
+
       Asm->EOL("FDE CIE offset");
 
       EmitReference("eh_func_begin", EHFrameInfo.Number, true, true);
@@ -3385,8 +4406,8 @@ private:
 
     // Begin the exception table.
     Asm->SwitchToDataSection(TAI->getDwarfExceptionSection());
-    O << "GCC_except_table" << SubprogramCount << ":\n";
     Asm->EmitAlignment(2, 0, 0, false);
+    O << "GCC_except_table" << SubprogramCount << ":\n";
     for (unsigned i = 0; i != SizeAlign; ++i) {
       Asm->EmitInt8(0);
       Asm->EOL("Padding");
@@ -3880,10 +4901,7 @@ void DIE::dump() {
 /// DwarfWriter Implementation
 ///
 
-DwarfWriter::DwarfWriter(raw_ostream &OS, AsmPrinter *A,
-                         const TargetAsmInfo *T) {
-  DE = new DwarfException(OS, A, T);
-  DD = new DwarfDebug(OS, A, T);
+DwarfWriter::DwarfWriter() : ImmutablePass(&ID), DD(NULL), DE(NULL) {
 }
 
 DwarfWriter::~DwarfWriter() {
@@ -3891,18 +4909,18 @@ DwarfWriter::~DwarfWriter() {
   delete DD;
 }
 
-/// SetModuleInfo - Set machine module info when it's known that pass manager
-/// has created it.  Set by the target AsmPrinter.
-void DwarfWriter::SetModuleInfo(MachineModuleInfo *MMI) {
-  DD->SetModuleInfo(MMI);
-  DE->SetModuleInfo(MMI);
-}
-
 /// BeginModule - Emit all Dwarf sections that should come prior to the
 /// content.
-void DwarfWriter::BeginModule(Module *M) {
+void DwarfWriter::BeginModule(Module *M,
+                              MachineModuleInfo *MMI,
+                              raw_ostream &OS, AsmPrinter *A,
+                              const TargetAsmInfo *T) {
+  DE = new DwarfException(OS, A, T);
+  DD = new DwarfDebug(OS, A, T);
   DE->BeginModule(M);
   DD->BeginModule(M);
+  DD->SetModuleInfo(MMI);
+  DE->SetModuleInfo(MMI);
 }
 
 /// EndModule - Emit all Dwarf sections that should come after the content.
@@ -3921,8 +4939,8 @@ void DwarfWriter::BeginFunction(MachineFunction *MF) {
 
 /// EndFunction - Gather and emit post-function debug information.
 ///
-void DwarfWriter::EndFunction() {
-  DD->EndFunction();
+void DwarfWriter::EndFunction(MachineFunction *MF) {
+  DD->EndFunction(MF);
   DE->EndFunction();
 
   if (MachineModuleInfo *MMI = DD->getMMI() ? DD->getMMI() : DE->getMMI())