these two pieces of code are the same because we always
[oota-llvm.git] / lib / CodeGen / ELFWriter.cpp
index aeccefbd3e801708e178ddaa0ad043747c6f999f..3e1645b2c341ef54b2dd29d6d642c79218662412 100644 (file)
@@ -30,9 +30,9 @@
 
 #define DEBUG_TYPE "elfwriter"
 
+#include "ELF.h"
 #include "ELFWriter.h"
 #include "ELFCodeEmitter.h"
-#include "ELF.h"
 #include "llvm/Constants.h"
 #include "llvm/Module.h"
 #include "llvm/PassManager.h"
 #include "llvm/CodeGen/BinaryObject.h"
 #include "llvm/CodeGen/FileWriters.h"
 #include "llvm/CodeGen/MachineCodeEmitter.h"
+#include "llvm/CodeGen/ObjectCodeEmitter.h"
+#include "llvm/CodeGen/MachineCodeEmitter.h"
 #include "llvm/CodeGen/MachineConstantPool.h"
-#include "llvm/CodeGen/MachineFunctionPass.h"
+#include "llvm/Target/TargetAsmInfo.h"
 #include "llvm/Target/TargetData.h"
+#include "llvm/Target/TargetELFWriterInfo.h"
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/Support/Mangler.h"
 #include "llvm/Support/Streams.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Support/Debug.h"
-#include <list>
+#include "llvm/Support/ErrorHandling.h"
+
 using namespace llvm;
 
 char ELFWriter::ID = 0;
-/// AddELFWriter - Concrete function to add the ELF writer to the function pass
-/// manager.
-MachineCodeEmitter *llvm::AddELFWriter(PassManagerBase &PM,
-                                       raw_ostream &O,
-                                       TargetMachine &TM) {
+
+/// AddELFWriter - Add the ELF writer to the function pass manager
+ObjectCodeEmitter *llvm::AddELFWriter(PassManagerBase &PM,
+                                      raw_ostream &O,
+                                      TargetMachine &TM) {
   ELFWriter *EW = new ELFWriter(O, TM);
   PM.add(EW);
-  return &EW->getMachineCodeEmitter();
+  return EW->getObjectCodeEmitter();
 }
 
 //===----------------------------------------------------------------------===//
@@ -75,15 +79,15 @@ ELFWriter::ELFWriter(raw_ostream &o, TargetMachine &tm)
   TAI = TM.getTargetAsmInfo();
   TEW = TM.getELFWriterInfo();
 
-  // Create the machine code emitter object for this target.
-  MCE = new ELFCodeEmitter(*this);
+  // Create the object code emitter object for this target.
+  ElfCE = new ELFCodeEmitter(*this);
 
   // Inital number of sections
   NumSections = 0;
 }
 
 ELFWriter::~ELFWriter() {
-  delete MCE;
+  delete ElfCE;
 }
 
 // doInitialization - Emit the file header and all of the global variables for
@@ -136,137 +140,164 @@ bool ELFWriter::doInitialization(Module &M) {
   ElfHdr.emitWord16(0); // Placeholder
 
   // Add the null section, which is required to be first in the file.
-  getSection("", ELFSection::SHT_NULL, 0);
-
-  // Start up the symbol table.  The first entry in the symtab is the null 
-  // entry.
-  SymbolList.push_back(ELFSym(0));
+  getNullSection();
 
   return false;
 }
 
-void ELFWriter::EmitGlobal(GlobalVariable *GV) {
-
-  // XXX: put local symbols *before* global ones!
-  const Section *S = TAI->SectionForGlobal(GV);
-  DOUT << "Section " << S->getName() << " for global " << GV->getName() << "\n";
-
-  // If this is an external global, emit it now.  TODO: Note that it would be
-  // better to ignore the symbol here and only add it to the symbol table if
-  // referenced.
-  if (!GV->hasInitializer()) {
-    ELFSym ExternalSym(GV);
-    ExternalSym.SetBind(ELFSym::STB_GLOBAL);
-    ExternalSym.SetType(ELFSym::STT_NOTYPE);
-    ExternalSym.SectionIdx = ELFSection::SHN_UNDEF;
-    SymbolList.push_back(ExternalSym);
-    return;
+// getGlobalELFVisibility - Returns the ELF specific visibility type
+unsigned ELFWriter::getGlobalELFVisibility(const GlobalValue *GV) {
+  switch (GV->getVisibility()) {
+  default:
+    llvm_unreachable("unknown visibility type");
+  case GlobalValue::DefaultVisibility:
+    return ELFSym::STV_DEFAULT;
+  case GlobalValue::HiddenVisibility:
+    return ELFSym::STV_HIDDEN;
+  case GlobalValue::ProtectedVisibility:
+    return ELFSym::STV_PROTECTED;
   }
+  return 0;
+}
 
-  const TargetData *TD = TM.getTargetData();
-  unsigned Align = TD->getPreferredAlignment(GV);
-  Constant *CV = GV->getInitializer();
-  unsigned Size = TD->getTypeAllocSize(CV->getType());
+// getGlobalELFBinding - Returns the ELF specific binding type
+unsigned ELFWriter::getGlobalELFBinding(const GlobalValue *GV) {
+  if (GV->hasInternalLinkage())
+    return ELFSym::STB_LOCAL;
 
-  // If this global has a zero initializer, go to .bss or common section.
-  if (CV->isNullValue() || isa<UndefValue>(CV)) {
-    // If this global is part of the common block, add it now.  Variables are
-    // part of the common block if they are zero initialized and allowed to be
-    // merged with other symbols.
-    if (GV->hasLinkOnceLinkage() || GV->hasWeakLinkage() ||
-        GV->hasCommonLinkage()) {
-      ELFSym CommonSym(GV);
-      // Value for common symbols is the alignment required.
-      CommonSym.Value = Align;
-      CommonSym.Size  = Size;
-      CommonSym.SetBind(ELFSym::STB_GLOBAL);
-      CommonSym.SetType(ELFSym::STT_OBJECT);
-      CommonSym.SectionIdx = ELFSection::SHN_COMMON;
-      SymbolList.push_back(CommonSym);
-      getSection(S->getName(), ELFSection::SHT_NOBITS,
-        ELFSection::SHF_WRITE | ELFSection::SHF_ALLOC, 1);
-      return;
-    }
+  if (GV->hasWeakLinkage())
+    return ELFSym::STB_WEAK;
 
-    // Otherwise, this symbol is part of the .bss section.  Emit it now.
-    // Handle alignment.  Ensure section is aligned at least as much as required
-    // by this symbol.
-    ELFSection &BSSSection = getBSSSection();
-    BSSSection.Align = std::max(BSSSection.Align, Align);
-
-    // Within the section, emit enough virtual padding to get us to an alignment
-    // boundary.
-    if (Align)
-      BSSSection.Size = (BSSSection.Size + Align - 1) & ~(Align-1);
-
-    ELFSym BSSSym(GV);
-    BSSSym.Value = BSSSection.Size;
-    BSSSym.Size = Size;
-    BSSSym.SetType(ELFSym::STT_OBJECT);
-
-    switch (GV->getLinkage()) {
-    default:  // weak/linkonce/common handled above
-      assert(0 && "Unexpected linkage type!");
-    case GlobalValue::AppendingLinkage:  // FIXME: This should be improved!
-    case GlobalValue::ExternalLinkage:
-      BSSSym.SetBind(ELFSym::STB_GLOBAL);
-      break;
-    case GlobalValue::InternalLinkage:
-      BSSSym.SetBind(ELFSym::STB_LOCAL);
-      break;
-    }
+  return ELFSym::STB_GLOBAL;
+}
 
-    // Set the idx of the .bss section
-    BSSSym.SectionIdx = BSSSection.SectionIdx;
-    if (!GV->hasPrivateLinkage())
-      SymbolList.push_back(BSSSym);
+// getGlobalELFType - Returns the ELF specific type for a global
+unsigned ELFWriter::getGlobalELFType(const GlobalValue *GV) {
+  if (GV->isDeclaration())
+    return ELFSym::STT_NOTYPE;
 
-    // Reserve space in the .bss section for this symbol.
-    BSSSection.Size += Size;
-    return;
-  }
+  if (isa<Function>(GV))
+    return ELFSym::STT_FUNC;
 
-  /// Emit the Global symbol to the right ELF section
-  ELFSym GblSym(GV);
-  GblSym.Size = Size;
-  GblSym.SetType(ELFSym::STT_OBJECT);
-  GblSym.SetBind(ELFSym::STB_GLOBAL);
-  unsigned Flags = S->getFlags();
-  unsigned SectType = ELFSection::SHT_PROGBITS;
-  unsigned SHdrFlags = ELFSection::SHF_ALLOC;
+  return ELFSym::STT_OBJECT;
+}
+
+// getElfSectionFlags - Get the ELF Section Header flags based
+// on the flags defined in ELFTargetAsmInfo.
+unsigned ELFWriter::getElfSectionFlags(unsigned Flags) {
+  unsigned ElfSectionFlags = ELFSection::SHF_ALLOC;
 
   if (Flags & SectionFlags::Code)
-    SHdrFlags |= ELFSection::SHF_EXECINSTR;
+    ElfSectionFlags |= ELFSection::SHF_EXECINSTR;
   if (Flags & SectionFlags::Writeable)
-    SHdrFlags |= ELFSection::SHF_WRITE;
+    ElfSectionFlags |= ELFSection::SHF_WRITE;
   if (Flags & SectionFlags::Mergeable)
-    SHdrFlags |= ELFSection::SHF_MERGE;
+    ElfSectionFlags |= ELFSection::SHF_MERGE;
   if (Flags & SectionFlags::TLS)
-    SHdrFlags |= ELFSection::SHF_TLS;
+    ElfSectionFlags |= ELFSection::SHF_TLS;
   if (Flags & SectionFlags::Strings)
-    SHdrFlags |= ELFSection::SHF_STRINGS;
-
-  // Remove tab from section name prefix
-  std::string SectionName(S->getName());
-  size_t Pos = SectionName.find("\t");
-  if (Pos != std::string::npos)
-    SectionName.erase(Pos, 1);
-
-  // The section alignment should be bound to the element with
-  // the largest alignment
-  ELFSection &ElfS = getSection(SectionName, SectType, SHdrFlags);
-  GblSym.SectionIdx = ElfS.SectionIdx;
-  if (Align > ElfS.Align)
-    ElfS.Align = Align;
-
-  // S.Value should contain the symbol index inside the section,
-  // and all symbols should start on their required alignment boundary
-  GblSym.Value = (ElfS.size() + (Align-1)) & (-Align);
-  ElfS.emitAlignment(Align);
-
-  // Emit the constant symbol to its section
-  EmitGlobalConstant(CV, ElfS);
-  SymbolList.push_back(GblSym);
+    ElfSectionFlags |= ELFSection::SHF_STRINGS;
+
+  return ElfSectionFlags;
+}
+
+// isELFUndefSym - the symbol has no section and must be placed in
+// the symbol table with a reference to the null section.
+static bool isELFUndefSym(const GlobalValue *GV) {
+  return GV->isDeclaration();
+}
+
+// isELFBssSym - for an undef or null value, the symbol must go to a bss
+// section if it's not weak for linker, otherwise it's a common sym.
+static bool isELFBssSym(const GlobalValue *GV) {
+  return (!GV->isDeclaration() &&
+          (GV->isNullValue() || isa<UndefValue>(GV)) &&
+          !GV->isWeakForLinker());
+}
+
+// isELFCommonSym - for an undef or null value, the symbol must go to a
+// common section if it's weak for linker, otherwise bss.
+static bool isELFCommonSym(const GlobalValue *GV) {
+  return (!GV->isDeclaration() &&
+          (GV->isNullValue() || isa<UndefValue>(GV))
+           && GV->isWeakForLinker());
+}
+
+// isELFDataSym - if the symbol is an initialized but no null constant
+// it must go to some kind of data section gathered from TAI
+static bool isELFDataSym(const GlobalValue *GV) {
+  return (!GV->isDeclaration() &&
+          !(GV->isNullValue() || isa<UndefValue>(GV)));
+}
+
+// EmitGlobal - Choose the right section for global and emit it
+void ELFWriter::EmitGlobal(const GlobalValue *GV) {
+
+  // Handle ELF Bind, Visibility and Type for the current symbol
+  unsigned SymBind = getGlobalELFBinding(GV);
+  ELFSym *GblSym = new ELFSym(GV);
+  GblSym->setBind(SymBind);
+  GblSym->setVisibility(getGlobalELFVisibility(GV));
+  GblSym->setType(getGlobalELFType(GV));
+
+  if (isELFUndefSym(GV)) {
+    GblSym->SectionIdx = ELFSection::SHN_UNDEF;
+  } else {
+    assert(isa<GlobalVariable>(GV) && "GV not a global variable!");
+    const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
+
+    // Get ELF section from TAI
+    const Section *S = TAI->SectionForGlobal(GV);
+    unsigned SectionFlags = getElfSectionFlags(S->getFlags());
+
+    // The symbol align should update the section alignment if needed
+    const TargetData *TD = TM.getTargetData();
+    unsigned Align = TD->getPreferredAlignment(GVar);
+    unsigned Size = TD->getTypeAllocSize(GVar->getInitializer()->getType());
+    GblSym->Size = Size;
+
+    if (isELFCommonSym(GV)) {
+      GblSym->SectionIdx = ELFSection::SHN_COMMON;
+      getSection(S->getName(), ELFSection::SHT_NOBITS, SectionFlags, 1);
+
+      // A new linkonce section is created for each global in the
+      // common section, the default alignment is 1 and the symbol
+      // value contains its alignment.
+      GblSym->Value = Align;
+
+    } else if (isELFBssSym(GV)) {
+      ELFSection &ES =
+        getSection(S->getName(), ELFSection::SHT_NOBITS, SectionFlags);
+      GblSym->SectionIdx = ES.SectionIdx;
+
+      // Update the size with alignment and the next object can
+      // start in the right offset in the section
+      if (Align) ES.Size = (ES.Size + Align-1) & ~(Align-1);
+      ES.Align = std::max(ES.Align, Align);
+
+      // GblSym->Value should contain the virtual offset inside the section.
+      // Virtual because the BSS space is not allocated on ELF objects
+      GblSym->Value = ES.Size;
+      ES.Size += Size;
+
+    } else if (isELFDataSym(GV)) {
+      ELFSection &ES =
+        getSection(S->getName(), ELFSection::SHT_PROGBITS, SectionFlags);
+      GblSym->SectionIdx = ES.SectionIdx;
+
+      // GblSym->Value should contain the symbol offset inside the section,
+      // and all symbols should start on their required alignment boundary
+      ES.Align = std::max(ES.Align, Align);
+      GblSym->Value = (ES.size() + (Align-1)) & (-Align);
+      ES.emitAlignment(ES.Align);
+
+      // Emit the global to the data section 'ES'
+      EmitGlobalConstant(GVar->getInitializer(), ES);
+    }
+  }
+
+  if (!GV->hasPrivateLinkage())
+    SymbolList.push_back(GblSym);
 }
 
 void ELFWriter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
@@ -306,6 +337,7 @@ void ELFWriter::EmitGlobalConstant(const Constant *CV, ELFSection &GblS) {
   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
     if (CVA->isString()) {
       std::string GblStr = CVA->getAsString();
+      GblStr.resize(GblStr.size()-1);
       GblS.emitString(GblStr);
     } else { // Not a string.  Print the values in successive locations
       for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
@@ -322,9 +354,9 @@ void ELFWriter::EmitGlobalConstant(const Constant *CV, ELFSection &GblS) {
     else if (CFP->getType() == Type::FloatTy)
       GblS.emitWord32(Val);
     else if (CFP->getType() == Type::X86_FP80Ty) {
-      assert(0 && "X86_FP80Ty global emission not implemented");
+      llvm_unreachable("X86_FP80Ty global emission not implemented");
     } else if (CFP->getType() == Type::PPC_FP128Ty)
-      assert(0 && "PPC_FP128Ty global emission not implemented");
+      llvm_unreachable("PPC_FP128Ty global emission not implemented");
     return;
   } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
     if (Size == 4)
@@ -332,7 +364,7 @@ void ELFWriter::EmitGlobalConstant(const Constant *CV, ELFSection &GblS) {
     else if (Size == 8)
       GblS.emitWord64(CI->getZExtValue());
     else
-      assert(0 && "LargeInt global emission not implemented");
+      llvm_unreachable("LargeInt global emission not implemented");
     return;
   } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
     const VectorType *PTy = CP->getType();
@@ -340,28 +372,18 @@ void ELFWriter::EmitGlobalConstant(const Constant *CV, ELFSection &GblS) {
       EmitGlobalConstant(CP->getOperand(I), GblS);
     return;
   }
-  assert(0 && "unknown global constant");
+  llvm_unreachable("unknown global constant");
 }
 
 
 bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
-  // Nothing to do here, this is all done through the MCE object above.
+  // Nothing to do here, this is all done through the ElfCE object above.
   return false;
 }
 
 /// doFinalization - Now that the module has been completely processed, emit
 /// the ELF file to 'O'.
 bool ELFWriter::doFinalization(Module &M) {
-  /// FIXME: This should be removed when moving to ObjectCodeEmiter. Since the
-  /// current ELFCodeEmiter uses CurrBuff, ... it doesn't update S.Data
-  /// vector size for .text sections, so this is a quick dirty fix
-  ELFSection &TS = getTextSection();
-  if (TS.Size) {
-    BinaryData &BD = TS.getData();
-    for (unsigned e=0; e<TS.Size; ++e)
-      BD.push_back(BD[e]);
-  }
-
   // Emit .data section placeholder
   getDataSection();
 
@@ -370,13 +392,44 @@ bool ELFWriter::doFinalization(Module &M) {
 
   // Build and emit data, bss and "common" sections.
   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
-       I != E; ++I)
+       I != E; ++I) {
     EmitGlobal(I);
+    GblSymLookup[I] = 0;
+  }
+
+  // Emit all pending globals
+  // TODO: this should be done only for referenced symbols
+  for (SetVector<GlobalValue*>::const_iterator I = PendingGlobals.begin(),
+       E = PendingGlobals.end(); I != E; ++I) {
+
+    // No need to emit the symbol again
+    if (GblSymLookup.find(*I) != GblSymLookup.end())
+      continue;
+
+    EmitGlobal(*I);
+    GblSymLookup[*I] = 0;
+  }
 
   // Emit non-executable stack note
   if (TAI->getNonexecutableStackDirective())
     getNonExecStackSection();
 
+  // Emit a symbol for each section created until now, skip null section
+  for (unsigned i = 1, e = SectionList.size(); i < e; ++i) {
+    ELFSection &ES = *SectionList[i];
+    ELFSym *SectionSym = new ELFSym(0);
+    SectionSym->SectionIdx = ES.SectionIdx;
+    SectionSym->Size = 0;
+    SectionSym->setBind(ELFSym::STB_LOCAL);
+    SectionSym->setType(ELFSym::STT_SECTION);
+    SectionSym->setVisibility(ELFSym::STV_DEFAULT);
+    SymbolList.push_back(SectionSym);
+    ES.Sym = SymbolList.back();
+  }
+
+  // Emit string table
+  EmitStringTable();
+
   // Emit the symbol table now, if non-empty.
   EmitSymbolTable();
 
@@ -390,6 +443,7 @@ bool ELFWriter::doFinalization(Module &M) {
   OutputSectionsAndSectionTable();
 
   // We are done with the abstract symbols.
+  SymbolList.clear();
   SectionList.clear();
   NumSections = 0;
 
@@ -400,6 +454,73 @@ bool ELFWriter::doFinalization(Module &M) {
 
 /// EmitRelocations - Emit relocations
 void ELFWriter::EmitRelocations() {
+
+  // Create Relocation sections for each section which needs it.
+  for (unsigned i=0, e=SectionList.size(); i != e; ++i) {
+    ELFSection &S = *SectionList[i];
+
+    // This section does not have relocations
+    if (!S.hasRelocations()) continue;
+
+    // Get the relocation section for section 'S'
+    bool HasRelA = TEW->hasRelocationAddend();
+    ELFSection &RelSec = getRelocSection(S.getName(), HasRelA,
+                                         TEW->getPrefELFAlignment());
+
+    // 'Link' - Section hdr idx of the associated symbol table
+    // 'Info' - Section hdr idx of the section to which the relocation applies
+    ELFSection &SymTab = getSymbolTableSection();
+    RelSec.Link = SymTab.SectionIdx;
+    RelSec.Info = S.SectionIdx;
+    RelSec.EntSize = TEW->getRelocationEntrySize();
+
+    // Get the relocations from Section
+    std::vector<MachineRelocation> Relos = S.getRelocations();
+    for (std::vector<MachineRelocation>::iterator MRI = Relos.begin(),
+         MRE = Relos.end(); MRI != MRE; ++MRI) {
+      MachineRelocation &MR = *MRI;
+
+      // Offset from the start of the section containing the symbol
+      unsigned Offset = MR.getMachineCodeOffset();
+
+      // Symbol index in the symbol table
+      unsigned SymIdx = 0;
+
+      // Target specific ELF relocation type
+      unsigned RelType = TEW->getRelocationType(MR.getRelocationType());
+
+      // Constant addend used to compute the value to be stored
+      // into the relocatable field
+      int64_t Addend = 0;
+
+      // There are several machine relocations types, and each one of
+      // them needs a different approach to retrieve the symbol table index.
+      if (MR.isGlobalValue()) {
+        const GlobalValue *G = MR.getGlobalValue();
+        SymIdx = GblSymLookup[G];
+        Addend = TEW->getAddendForRelTy(RelType);
+      } else {
+        // Get the symbol index for the section symbol referenced
+        // by the relocation
+        unsigned SectionIdx = MR.getConstantVal();
+        SymIdx = SectionList[SectionIdx]->Sym->SymTabIdx;
+        Addend = (uint64_t)MR.getResultPointer();
+      }
+
+      // Get the relocation entry and emit to the relocation section
+      ELFRelocation Rel(Offset, SymIdx, RelType, HasRelA, Addend);
+      EmitRelocation(RelSec, Rel, HasRelA);
+    }
+  }
+}
+
+/// EmitRelocation - Write relocation 'Rel' to the relocation section 'Rel'
+void ELFWriter::EmitRelocation(BinaryObject &RelSec, ELFRelocation &Rel,
+                               bool HasRelA) {
+  RelSec.emitWord(Rel.getOffset());
+  RelSec.emitWord(Rel.getInfo(is64Bit));
+  if (HasRelA)
+    RelSec.emitWord(Rel.getAddend());
 }
 
 /// EmitSymbol - Write symbol 'Sym' to the symbol table 'SymbolTable'
@@ -423,7 +544,7 @@ void ELFWriter::EmitSymbol(BinaryObject &SymbolTable, ELFSym &Sym) {
 
 /// EmitSectionHeader - Write section 'Section' header in 'SHdrTab'
 /// Section Header Table
-void ELFWriter::EmitSectionHeader(BinaryObject &SHdrTab, 
+void ELFWriter::EmitSectionHeader(BinaryObject &SHdrTab,
                                   const ELFSection &SHdr) {
   SHdrTab.emitWord32(SHdr.NameIdx);
   SHdrTab.emitWord32(SHdr.Type);
@@ -448,28 +569,28 @@ void ELFWriter::EmitSectionHeader(BinaryObject &SHdrTab,
   }
 }
 
-/// EmitSymbolTable - If the current symbol table is non-empty, emit the string
-/// table for it and then the symbol table itself.
-void ELFWriter::EmitSymbolTable() {
-  if (SymbolList.size() == 1) return;  // Only the null entry.
-
-  // FIXME: compact all local symbols to the start of the symtab.
-  unsigned FirstNonLocalSymbol = 1;
-
+/// EmitStringTable - If the current symbol table is non-empty, emit the string
+/// table for it
+void ELFWriter::EmitStringTable() {
+  if (!SymbolList.size()) return;  // Empty symbol table.
   ELFSection &StrTab = getStringTableSection();
 
   // Set the zero'th symbol to a null byte, as required.
   StrTab.emitByte(0);
 
+  // Walk on the symbol list and write symbol names into the string table.
   unsigned Index = 1;
-  for (unsigned i = 1, e = SymbolList.size(); i != e; ++i) {
+  for (ELFSymIter I=SymbolList.begin(), E=SymbolList.end(); I != E; ++I) {
+    ELFSym &Sym = *(*I);
+
     // Use the name mangler to uniquify the LLVM symbol.
-    std::string Name = Mang->getValueName(SymbolList[i].GV);
+    std::string Name;
+    if (Sym.GV) Name.append(Mang->getMangledName(Sym.GV));
 
     if (Name.empty()) {
-      SymbolList[i].NameIdx = 0;
+      Sym.NameIdx = 0;
     } else {
-      SymbolList[i].NameIdx = Index;
+      Sym.NameIdx = Index;
       StrTab.emitString(Name);
 
       // Keep track of the number of bytes emitted to this section.
@@ -478,20 +599,73 @@ void ELFWriter::EmitSymbolTable() {
   }
   assert(Index == StrTab.size());
   StrTab.Size = Index;
+}
+
+// SortSymbols - On the symbol table local symbols must come before
+// all other symbols with non-local bindings. The return value is
+// the position of the first non local symbol.
+unsigned ELFWriter::SortSymbols() {
+  unsigned FirstNonLocalSymbol;
+  std::vector<ELFSym*> LocalSyms, OtherSyms;
+
+  for (ELFSymIter I=SymbolList.begin(), E=SymbolList.end(); I != E; ++I) {
+    if ((*I)->isLocalBind())
+      LocalSyms.push_back(*I);
+    else
+      OtherSyms.push_back(*I);
+  }
+  SymbolList.clear();
+  FirstNonLocalSymbol = LocalSyms.size();
+
+  for (unsigned i = 0; i < FirstNonLocalSymbol; ++i)
+    SymbolList.push_back(LocalSyms[i]);
+
+  for (ELFSymIter I=OtherSyms.begin(), E=OtherSyms.end(); I != E; ++I)
+    SymbolList.push_back(*I);
+
+  LocalSyms.clear();
+  OtherSyms.clear();
+
+  return FirstNonLocalSymbol;
+}
+
+/// EmitSymbolTable - Emit the symbol table itself.
+void ELFWriter::EmitSymbolTable() {
+  if (!SymbolList.size()) return;  // Empty symbol table.
 
   // Now that we have emitted the string table and know the offset into the
   // string table of each symbol, emit the symbol table itself.
   ELFSection &SymTab = getSymbolTableSection();
-  SymTab.Align = TEW->getSymTabAlignment();
-  SymTab.Link  = StrTab.SectionIdx;      // Section Index of .strtab.
-  SymTab.Info  = FirstNonLocalSymbol;    // First non-STB_LOCAL symbol.
+  SymTab.Align = TEW->getPrefELFAlignment();
+
+  // Section Index of .strtab.
+  SymTab.Link = getStringTableSection().SectionIdx;
 
   // Size of each symtab entry.
   SymTab.EntSize = TEW->getSymTabEntrySize();
 
-  for (unsigned i = 0, e = SymbolList.size(); i != e; ++i)
-    EmitSymbol(SymTab, SymbolList[i]);
+  // The first entry in the symtab is the null symbol
+  SymbolList.insert(SymbolList.begin(), new ELFSym(0));
+
+  // Reorder the symbol table with local symbols first!
+  unsigned FirstNonLocalSymbol = SortSymbols();
+
+  // Emit all the symbols to the symbol table.
+  for (unsigned i = 0, e = SymbolList.size(); i < e; ++i) {
+    ELFSym &Sym = *SymbolList[i];
 
+    // Emit symbol to the symbol table
+    EmitSymbol(SymTab, Sym);
+
+    // Record the symbol table index for each global value
+    if (Sym.GV) GblSymLookup[Sym.GV] = i;
+
+    // Keep track on the symbol index into the symbol table
+    Sym.SymTabIdx = i;
+  }
+
+  // One greater than the symbol table index of the last local symbol
+  SymTab.Info = FirstNonLocalSymbol;
   SymTab.Size = SymTab.size();
 }
 
@@ -500,7 +674,7 @@ void ELFWriter::EmitSymbolTable() {
 /// section names.
 void ELFWriter::EmitSectionTableStringTable() {
   // First step: add the section for the string table to the list of sections:
-  ELFSection &SHStrTab = getSection(".shstrtab", ELFSection::SHT_STRTAB, 0);
+  ELFSection &SHStrTab = getSectionHeaderStringTableSection();
 
   // Now that we know which section number is the .shstrtab section, update the
   // e_shstrndx entry in the ELF header.
@@ -510,15 +684,15 @@ void ELFWriter::EmitSectionTableStringTable() {
   // the string table.
   unsigned Index = 0;
 
-  for (std::list<ELFSection>::iterator I = SectionList.begin(),
-         E = SectionList.end(); I != E; ++I) {
+  for (ELFSectionIter I=SectionList.begin(), E=SectionList.end(); I != E; ++I) {
+    ELFSection &S = *(*I);
     // Set the index into the table.  Note if we have lots of entries with
     // common suffixes, we could memoize them here if we cared.
-    I->NameIdx = Index;
-    SHStrTab.emitString(I->getName());
+    S.NameIdx = Index;
+    SHStrTab.emitString(S.getName());
 
     // Keep track of the number of bytes emitted to this section.
-    Index += I->getName().size()+1;
+    Index += S.getName().size()+1;
   }
 
   // Set the size of .shstrtab now that we know what it is.
@@ -533,33 +707,28 @@ void ELFWriter::OutputSectionsAndSectionTable() {
   // Pass #1: Compute the file offset for each section.
   size_t FileOff = ElfHdr.size();   // File header first.
 
-  // Adjust alignment of all section if needed.
-  for (std::list<ELFSection>::iterator I = SectionList.begin(),
-         E = SectionList.end(); I != E; ++I) {
-
-    // Section idx 0 has 0 offset
-    if (!I->SectionIdx)
-      continue;
-
-    if (!I->size()) {
-      I->Offset = FileOff;
+  // Adjust alignment of all section if needed, skip the null section.
+  for (unsigned i=1, e=SectionList.size(); i < e; ++i) {
+    ELFSection &ES = *SectionList[i];
+    if (!ES.size()) {
+      ES.Offset = FileOff;
       continue;
     }
 
     // Update Section size
-    if (!I->Size)
-      I->Size = I->size();
+    if (!ES.Size)
+      ES.Size = ES.size();
 
     // Align FileOff to whatever the alignment restrictions of the section are.
-    if (I->Align)
-      FileOff = (FileOff+I->Align-1) & ~(I->Align-1);
+    if (ES.Align)
+      FileOff = (FileOff+ES.Align-1) & ~(ES.Align-1);
 
-    I->Offset = FileOff;
-    FileOff += I->Size;
+    ES.Offset = FileOff;
+    FileOff += ES.Size;
   }
 
   // Align Section Header.
-  unsigned TableAlign = is64Bit ? 8 : 4;
+  unsigned TableAlign = TEW->getPrefELFAlignment();
   FileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
 
   // Now that we know where all of the sections will be emitted, set the e_shnum
@@ -579,26 +748,24 @@ void ELFWriter::OutputSectionsAndSectionTable() {
   BinaryObject SHdrTable(isLittleEndian, is64Bit);
 
   // Emit all of sections to the file and build the section header table.
-  while (!SectionList.empty()) {
-    ELFSection &S = *SectionList.begin();
+  for (ELFSectionIter I=SectionList.begin(), E=SectionList.end(); I != E; ++I) {
+    ELFSection &S = *(*I);
     DOUT << "SectionIdx: " << S.SectionIdx << ", Name: " << S.getName()
          << ", Size: " << S.Size << ", Offset: " << S.Offset
          << ", SectionData Size: " << S.size() << "\n";
 
     // Align FileOff to whatever the alignment restrictions of the section are.
-    if (S.Align) {
-      for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
-        FileOff != NewFileOff; ++FileOff)
-        O << (char)0xAB;
-    }
-
     if (S.size()) {
+      if (S.Align)  {
+        for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
+             FileOff != NewFileOff; ++FileOff)
+          O << (char)0xAB;
+      }
       O.write((char *)&S.getData()[0], S.Size);
       FileOff += S.Size;
     }
 
     EmitSectionHeader(SHdrTable, S);
-    SectionList.pop_front();
   }
 
   // Align output for the section table.