Move broken HasCommonSymbols to ELFWriter.cpp.
[oota-llvm.git] / lib / CodeGen / ELFWriter.cpp
index ff41338ce9fafa34342551840d94700b27e31a4c..0fd1e8e83bd7a772cc8a3ae6777b1fae04708f57 100644 (file)
 #include "llvm/PassManager.h"
 #include "llvm/DerivedTypes.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/MC/MCContext.h"
-#include "llvm/MC/MCSection.h"
+#include "llvm/MC/MCSectionELF.h"
+#include "llvm/MC/MCAsmInfo.h"
+#include "llvm/Target/Mangler.h"
 #include "llvm/Target/TargetAsmInfo.h"
 #include "llvm/Target/TargetData.h"
 #include "llvm/Target/TargetELFWriterInfo.h"
 #include "llvm/Target/TargetLowering.h"
 #include "llvm/Target/TargetLoweringObjectFile.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 "llvm/Support/ErrorHandling.h"
-
+#include "llvm/Support/raw_ostream.h"
+#include "llvm/ADT/SmallString.h"
 using namespace llvm;
 
 char ELFWriter::ID = 0;
 
-/// 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->getObjectCodeEmitter();
-}
-
 //===----------------------------------------------------------------------===//
 //                          ELFWriter Implementation
 //===----------------------------------------------------------------------===//
 
 ELFWriter::ELFWriter(raw_ostream &o, TargetMachine &tm)
-  : MachineFunctionPass(&ID), O(o), TM(tm),
-    OutContext(*new MCContext()),
+  : MachineFunctionPass(ID), O(o), TM(tm),
+    OutContext(*new MCContext(*TM.getMCAsmInfo(), new TargetAsmInfo(tm))),
     TLOF(TM.getTargetLowering()->getObjFileLowering()),
     is64Bit(TM.getTargetData()->getPointerSizeInBits() == 64),
     isLittleEndian(TM.getTargetData()->isLittleEndian()),
     ElfHdr(isLittleEndian, is64Bit) {
 
-  TAI = TM.getTargetAsmInfo();
+  MAI = TM.getMCAsmInfo();
   TEW = TM.getELFWriterInfo();
 
   // Create the object code emitter object for this target.
@@ -94,6 +84,24 @@ ELFWriter::ELFWriter(raw_ostream &o, TargetMachine &tm)
 ELFWriter::~ELFWriter() {
   delete ElfCE;
   delete &OutContext;
+
+  while(!SymbolList.empty()) {
+    delete SymbolList.back(); 
+    SymbolList.pop_back();
+  }
+
+  while(!PrivateSyms.empty()) {
+    delete PrivateSyms.back(); 
+    PrivateSyms.pop_back();
+  }
+
+  while(!SectionList.empty()) {
+    delete SectionList.back(); 
+    SectionList.pop_back();
+  }
+
+  // Release the name mangler object.
+  delete Mang; Mang = 0;
 }
 
 // doInitialization - Emit the file header and all of the global variables for
@@ -102,7 +110,7 @@ bool ELFWriter::doInitialization(Module &M) {
   // Initialize TargetLoweringObjectFile.
   const_cast<TargetLoweringObjectFile&>(TLOF).Initialize(OutContext, TM);
   
-  Mang = new Mangler(M);
+  Mang = new Mangler(OutContext, *TM.getTargetData());
 
   // ELF Header
   // ----------
@@ -122,12 +130,12 @@ bool ELFWriter::doInitialization(Module &M) {
 
   ElfHdr.emitByte(TEW->getEIClass()); // e_ident[EI_CLASS]
   ElfHdr.emitByte(TEW->getEIData());  // e_ident[EI_DATA]
-  ElfHdr.emitByte(EV_CURRENT);        // e_ident[EI_VERSION]
+  ElfHdr.emitByte(ELF::EV_CURRENT);   // e_ident[EI_VERSION]
   ElfHdr.emitAlignment(16);           // e_ident[EI_NIDENT-EI_PAD]
 
-  ElfHdr.emitWord16(ET_REL);             // e_type
+  ElfHdr.emitWord16(ELF::ET_REL);        // e_type
   ElfHdr.emitWord16(TEW->getEMachine()); // e_machine = target
-  ElfHdr.emitWord32(EV_CURRENT);         // e_version
+  ElfHdr.emitWord32(ELF::EV_CURRENT);    // e_version
   ElfHdr.emitWord(0);                    // e_entry, no entry point in .o file
   ElfHdr.emitWord(0);                    // e_phoff, no program header for .o
   ELFHdr_e_shoff_Offset = ElfHdr.size();
@@ -159,51 +167,60 @@ bool ELFWriter::doInitialization(Module &M) {
   return false;
 }
 
-// addGlobalSymbol - Add a global to be processed and to the global symbol 
-// lookup, use a zero index because the table index will be determined later.
-void ELFWriter::addGlobalSymbol(const GlobalValue *GV, 
-                                bool AddToLookup /* = false */) {
+// AddPendingGlobalSymbol - Add a global to be processed and to
+// the global symbol lookup, use a zero index because the table
+// index will be determined later.
+void ELFWriter::AddPendingGlobalSymbol(const GlobalValue *GV, 
+                                       bool AddToLookup /* = false */) {
   PendingGlobals.insert(GV);
   if (AddToLookup) 
     GblSymLookup[GV] = 0;
 }
 
-// addExternalSymbol - Add the external to be processed and to the
-// external symbol lookup, use a zero index because the symbol
-// table index will be determined later
-void ELFWriter::addExternalSymbol(const char *External) {
+// AddPendingExternalSymbol - Add the external to be processed
+// and to the external symbol lookup, use a zero index because
+// the symbol table index will be determined later.
+void ELFWriter::AddPendingExternalSymbol(const char *External) {
   PendingExternals.insert(External);
   ExtSymLookup[External] = 0;
 }
 
+ELFSection &ELFWriter::getDataSection() {
+  const MCSectionELF *Data = (const MCSectionELF *)TLOF.getDataSection();
+  return getSection(Data->getSectionName(), Data->getType(), 
+                    Data->getFlags(), 4);
+}
+
+ELFSection &ELFWriter::getBSSSection() {
+  const MCSectionELF *BSS = (const MCSectionELF *)TLOF.getBSSSection();
+  return getSection(BSS->getSectionName(), BSS->getType(), BSS->getFlags(), 4);
+}
+
 // getCtorSection - Get the static constructor section
 ELFSection &ELFWriter::getCtorSection() {
-  const MCSection *Ctor = TLOF.getStaticCtorSection();
-  return getSection(((MCSectionELF*)Ctor)->getName(), ELFSection::SHT_PROGBITS, 
-                    getElfSectionFlags(Ctor->getKind()));
+  const MCSectionELF *Ctor = (const MCSectionELF *)TLOF.getStaticCtorSection();
+  return getSection(Ctor->getSectionName(), Ctor->getType(), Ctor->getFlags()); 
 }
 
 // getDtorSection - Get the static destructor section
 ELFSection &ELFWriter::getDtorSection() {
-  const MCSection *Dtor = TLOF.getStaticDtorSection();
-  return getSection(((MCSectionELF*)Dtor)->getName(), ELFSection::SHT_PROGBITS, 
-                    getElfSectionFlags(Dtor->getKind()));
+  const MCSectionELF *Dtor = (const MCSectionELF *)TLOF.getStaticDtorSection();
+  return getSection(Dtor->getSectionName(), Dtor->getType(), Dtor->getFlags());
 }
 
 // getTextSection - Get the text section for the specified function
-ELFSection &ELFWriter::getTextSection(Function *F) {
-  const MCSection *Text = TLOF.SectionForGlobal(F, Mang, TM);
-  return getSection(((MCSectionELF*)Text)->getName(), ELFSection::SHT_PROGBITS,
-                    getElfSectionFlags(Text->getKind()));
+ELFSection &ELFWriter::getTextSection(const Function *F) {
+  const MCSectionELF *Text = 
+    (const MCSectionELF *)TLOF.SectionForGlobal(F, Mang, TM);
+  return getSection(Text->getSectionName(), Text->getType(), Text->getFlags());
 }
 
 // getJumpTableSection - Get a read only section for constants when 
 // emitting jump tables. TODO: add PIC support
 ELFSection &ELFWriter::getJumpTableSection() {
-  const MCSection *JT = TLOF.getSectionForConstant(SectionKind::getReadOnly());
-  return getSection(((MCSectionELF*)JT)->getName(), 
-                    ELFSection::SHT_PROGBITS,
-                    getElfSectionFlags(JT->getKind()), 
+  const MCSectionELF *JT = 
+    (const MCSectionELF *)TLOF.getSectionForConstant(SectionKind::getReadOnly());
+  return getSection(JT->getSectionName(), JT->getType(), JT->getFlags(),
                     TM.getTargetData()->getPointerABIAlignment());
 }
 
@@ -226,24 +243,24 @@ ELFSection &ELFWriter::getConstantPoolSection(MachineConstantPoolEntry &CPE) {
     }
   }
 
-  const MCSection *CPSect = TLOF.getSectionForConstant(Kind);
-  return getSection(((MCSectionELF*)CPSect)->getName(),
-                    ELFSection::SHT_PROGBITS,
-                    getElfSectionFlags(Kind),
-                    CPE.getAlignment());
+  const MCSectionELF *CPSect = 
+    (const MCSectionELF *)TLOF.getSectionForConstant(Kind);
+  return getSection(CPSect->getSectionName(), CPSect->getType(), 
+                    CPSect->getFlags(), CPE.getAlignment());
 }
 
 // getRelocSection - Return the relocation section of section 'S'. 'RelA' 
 // is true if the relocation section contains entries with addends.
 ELFSection &ELFWriter::getRelocSection(ELFSection &S) {
-  unsigned SectionHeaderTy = TEW->hasRelocationAddend() ?
-                              ELFSection::SHT_RELA : ELFSection::SHT_REL;
-  std::string RelSName(".rel");
+  unsigned SectionType = TEW->hasRelocationAddend() ?
+                ELF::SHT_RELA : ELF::SHT_REL;
+
+  std::string SectionName(".rel");
   if (TEW->hasRelocationAddend())
-    RelSName.append("a");
-  RelSName.append(S.getName());
+    SectionName.append("a");
+  SectionName.append(S.getName());
 
-  return getSection(RelSName, SectionHeaderTy, 0, TEW->getPrefELFAlignment());
+  return getSection(SectionName, SectionType, 0, TEW->getPrefELFAlignment());
 }
 
 // getGlobalELFVisibility - Returns the ELF specific visibility type
@@ -252,11 +269,11 @@ unsigned ELFWriter::getGlobalELFVisibility(const GlobalValue *GV) {
   default:
     llvm_unreachable("unknown visibility type");
   case GlobalValue::DefaultVisibility:
-    return ELFSym::STV_DEFAULT;
+    return ELF::STV_DEFAULT;
   case GlobalValue::HiddenVisibility:
-    return ELFSym::STV_HIDDEN;
+    return ELF::STV_HIDDEN;
   case GlobalValue::ProtectedVisibility:
-    return ELFSym::STV_PROTECTED;
+    return ELF::STV_PROTECTED;
   }
   return 0;
 }
@@ -264,74 +281,64 @@ unsigned ELFWriter::getGlobalELFVisibility(const GlobalValue *GV) {
 // getGlobalELFBinding - Returns the ELF specific binding type
 unsigned ELFWriter::getGlobalELFBinding(const GlobalValue *GV) {
   if (GV->hasInternalLinkage())
-    return ELFSym::STB_LOCAL;
+    return ELF::STB_LOCAL;
 
   if (GV->isWeakForLinker() && !GV->hasCommonLinkage())
-    return ELFSym::STB_WEAK;
+    return ELF::STB_WEAK;
 
-  return ELFSym::STB_GLOBAL;
+  return ELF::STB_GLOBAL;
 }
 
 // getGlobalELFType - Returns the ELF specific type for a global
 unsigned ELFWriter::getGlobalELFType(const GlobalValue *GV) {
   if (GV->isDeclaration())
-    return ELFSym::STT_NOTYPE;
+    return ELF::STT_NOTYPE;
 
   if (isa<Function>(GV))
-    return ELFSym::STT_FUNC;
+    return ELF::STT_FUNC;
 
-  return ELFSym::STT_OBJECT;
+  return ELF::STT_OBJECT;
 }
 
-// getElfSectionFlags - Get the ELF Section Header flags based
-// on the flags defined in SectionKind.h.
-unsigned ELFWriter::getElfSectionFlags(SectionKind Kind, bool IsAlloc) {
-  unsigned ElfSectionFlags = 0;
-  
-  if (IsAlloc)
-    ElfSectionFlags |= ELFSection::SHF_ALLOC;
-  if (Kind.isText())
-    ElfSectionFlags |= ELFSection::SHF_EXECINSTR;
-  if (Kind.isWriteable())
-    ElfSectionFlags |= ELFSection::SHF_WRITE;
-  if (Kind.isMergeableConst() || Kind.isMergeableCString())
-    ElfSectionFlags |= ELFSection::SHF_MERGE;
-  if (Kind.isThreadLocal())
-    ElfSectionFlags |= ELFSection::SHF_TLS;
-  if (Kind.isMergeableCString())
-    ElfSectionFlags |= ELFSection::SHF_STRINGS;
-
-  return ElfSectionFlags;
+// IsELFUndefSym - True if the global value must be marked as a symbol
+// which points to a SHN_UNDEF section. This means that the symbol has
+// no definition on the module.
+static bool IsELFUndefSym(const GlobalValue *GV) {
+  return GV->isDeclaration() || (isa<Function>(GV));
 }
 
-// isUndefOrNull - The constant is either a null initialized value or an
-// undefined one.
-static bool isUndefOrNull(const Constant *CV) {
-  return (CV->isNullValue() || isa<UndefValue>(CV));
-}
+// AddToSymbolList - Update the symbol lookup and If the symbol is 
+// private add it to PrivateSyms list, otherwise to SymbolList. 
+void ELFWriter::AddToSymbolList(ELFSym *GblSym) {
+  assert(GblSym->isGlobalValue() && "Symbol must be a global value");
 
-// 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) {
-  // Functions which make up until this point references are an undef symbol
-  return GV->isDeclaration() || (isa<Function>(GV));
+  const GlobalValue *GV = GblSym->getGlobalValue(); 
+  if (GV->hasPrivateLinkage()) {
+    // For a private symbols, keep track of the index inside 
+    // the private list since it will never go to the symbol 
+    // table and won't be patched up later.
+    PrivateSyms.push_back(GblSym);
+    GblSymLookup[GV] = PrivateSyms.size()-1;
+  } else {
+    // Non private symbol are left with zero indices until 
+    // they are patched up during the symbol table emition 
+    // (where the indicies are created).
+    SymbolList.push_back(GblSym);
+    GblSymLookup[GV] = 0;
+  }
 }
 
-// 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 GlobalVariable *GV, SectionKind Kind) {
-  const Constant *CV = GV->getInitializer();
+/// HasCommonSymbols - True if this section holds common symbols, this is
+/// indicated on the ELF object file by a symbol with SHN_COMMON section
+/// header index.
+static bool HasCommonSymbols(const MCSectionELF &S) {
+  // FIXME: this is wrong, a common symbol can be in .data for example.
+  if (StringRef(S.getSectionName()).startswith(".gnu.linkonce."))
+    return true;
 
-  return (!Kind.isMergeableCString() && 
-          isUndefOrNull(CV) && 
-          !GV->isWeakForLinker());
+  return false;
 }
 
-// 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 GlobalVariable *GV) {
-  return (isUndefOrNull(GV->getInitializer()) && GV->isWeakForLinker());
-}
 
 // EmitGlobal - Choose the right section for global and emit it
 void ELFWriter::EmitGlobal(const GlobalValue *GV) {
@@ -343,13 +350,12 @@ void ELFWriter::EmitGlobal(const GlobalValue *GV) {
   // Handle ELF Bind, Visibility and Type for the current symbol
   unsigned SymBind = getGlobalELFBinding(GV);
   unsigned SymType = getGlobalELFType(GV);
+  bool IsUndefSym = IsELFUndefSym(GV);
 
-  // All undef symbols have the same binding, type and visibily and
-  // are classified regardless of their type.
-  ELFSym *GblSym = isELFUndefSym(GV) ? ELFSym::getUndefGV(GV, SymBind)
+  ELFSym *GblSym = IsUndefSym ? ELFSym::getUndefGV(GV, SymBind)
     : ELFSym::getGV(GV, SymBind, SymType, getGlobalELFVisibility(GV));
 
-  if (!isELFUndefSym(GV)) {
+  if (!IsUndefSym) {
     assert(isa<GlobalVariable>(GV) && "GV not a global variable!");
     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
 
@@ -358,9 +364,11 @@ void ELFWriter::EmitGlobal(const GlobalValue *GV) {
       return;
 
     // Get the ELF section where this global belongs from TLOF
-    const MCSection *S = TLOF.SectionForGlobal(GV, Mang, TM);
-    SectionKind Kind = ((MCSectionELF*)S)->getKind();
-    unsigned SectionFlags = getElfSectionFlags(Kind);
+    const MCSectionELF *S = 
+      (const MCSectionELF *)TLOF.SectionForGlobal(GV, Mang, TM);
+    ELFSection &ES = 
+      getSection(S->getSectionName(), S->getType(), S->getFlags());
+    SectionKind Kind = S->getKind();
 
     // The symbol align should update the section alignment if needed
     const TargetData *TD = TM.getTargetData();
@@ -368,20 +376,16 @@ void ELFWriter::EmitGlobal(const GlobalValue *GV) {
     unsigned Size = TD->getTypeAllocSize(GVar->getInitializer()->getType());
     GblSym->Size = Size;
 
-    if (isELFCommonSym(GVar)) {
-      GblSym->SectionIdx = ELFSection::SHN_COMMON;
-      getSection(((MCSectionELF*)S)->getName(), 
-                 ELFSection::SHT_NOBITS, SectionFlags, 1);
+    if (HasCommonSymbols(*S)) { // Symbol must go to a common section
+      GblSym->SectionIdx = ELF::SHN_COMMON;
 
       // 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.
+      ES.Align = 1;
       GblSym->Value = Align;
 
-    } else if (isELFBssSym(GVar, Kind)) {
-      ELFSection &ES =
-        getSection(((MCSectionELF*)S)->getName(), ELFSection::SHT_NOBITS,
-                   SectionFlags);
+    } else if (Kind.isBSS() || Kind.isThreadBSS()) { // Symbol goes to BSS.
       GblSym->SectionIdx = ES.SectionIdx;
 
       // Update the size with alignment and the next object can
@@ -395,9 +399,6 @@ void ELFWriter::EmitGlobal(const GlobalValue *GV) {
       ES.Size += Size;
 
     } else { // The symbol must go to some kind of data section
-      ELFSection &ES =
-        getSection(((MCSectionELF*)S)->getName(), ELFSection::SHT_PROGBITS,
-                   SectionFlags);
       GblSym->SectionIdx = ES.SectionIdx;
 
       // GblSym->Value should contain the symbol offset inside the section,
@@ -411,18 +412,7 @@ void ELFWriter::EmitGlobal(const GlobalValue *GV) {
     }
   }
 
-  if (GV->hasPrivateLinkage()) {
-    // For a private symbols, keep track of the index inside the
-    // private list since it will never go to the symbol table and
-    // won't be patched up later.
-    PrivateSyms.push_back(GblSym);
-    GblSymLookup[GV] = PrivateSyms.size()-1;
-  } else {
-    // Non private symbol are left with zero indices until they are patched
-    // up during the symbol table emition (where the indicies are created).
-    SymbolList.push_back(GblSym);
-    GblSymLookup[GV] = 0;
-  }
+  AddToSymbolList(GblSym);
 }
 
 void ELFWriter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
@@ -470,15 +460,15 @@ void ELFWriter::EmitGlobalConstant(const Constant *CV, ELFSection &GblS) {
     return;
   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
     APInt Val = CFP->getValueAPF().bitcastToAPInt();
-    if (CFP->getType() == Type::DoubleTy)
+    if (CFP->getType()->isDoubleTy())
       GblS.emitWord64(Val.getZExtValue());
-    else if (CFP->getType() == Type::FloatTy)
+    else if (CFP->getType()->isFloatTy())
       GblS.emitWord32(Val.getZExtValue());
-    else if (CFP->getType() == Type::X86_FP80Ty) {
-      unsigned PadSize = TD->getTypeAllocSize(Type::X86_FP80Ty)-
-                         TD->getTypeStoreSize(Type::X86_FP80Ty);
+    else if (CFP->getType()->isX86_FP80Ty()) {
+      unsigned PadSize = TD->getTypeAllocSize(CFP->getType())-
+                         TD->getTypeStoreSize(CFP->getType());
       GblS.emitWordFP80(Val.getRawData(), PadSize);
-    } else if (CFP->getType() == Type::PPC_FP128Ty)
+    } else if (CFP->getType()->isPPC_FP128Ty())
       llvm_unreachable("PPC_FP128Ty global emission not implemented");
     return;
   } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
@@ -530,7 +520,7 @@ void ELFWriter::EmitGlobalConstant(const Constant *CV, ELFSection &GblS) {
   std::string msg;
   raw_string_ostream ErrorMsg(msg);
   ErrorMsg << "Constant unimp for type: " << *CV->getType();
-  llvm_report_error(ErrorMsg.str());
+  report_fatal_error(ErrorMsg.str());
 }
 
 // ResolveConstantExpr - Resolve the constant expression until it stop
@@ -556,7 +546,8 @@ CstExprResTy ELFWriter::ResolveConstantExpr(const Constant *CV) {
   }
   case Instruction::IntToPtr: {
     Constant *Op = CE->getOperand(0);
-    Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(), false/*ZExt*/);
+    Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
+                                      false/*ZExt*/);
     return ResolveConstantExpr(Op);
   }
   case Instruction::PtrToInt: {
@@ -594,10 +585,8 @@ CstExprResTy ELFWriter::ResolveConstantExpr(const Constant *CV) {
   }
   }
 
-  std::string msg(CE->getOpcodeName());
-  raw_string_ostream ErrorMsg(msg);
-  ErrorMsg << ": Unsupported ConstantExpr type";
-  llvm_report_error(ErrorMsg.str());
+  report_fatal_error(CE->getOpcodeName() +
+                     StringRef(": Unsupported ConstantExpr type"));
 
   return std::make_pair(CV, 0); // silence warning
 }
@@ -715,10 +704,6 @@ bool ELFWriter::doFinalization(Module &M) {
        I != E; ++I)
     SymbolList.push_back(ELFSym::getExtSym(*I));
 
-  // 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];
@@ -743,13 +728,6 @@ bool ELFWriter::doFinalization(Module &M) {
   // Dump the sections and section table to the .o file.
   OutputSectionsAndSectionTable();
 
-  // We are done with the abstract symbols.
-  SymbolList.clear();
-  SectionList.clear();
-  NumSections = 0;
-
-  // Release the name mangler object.
-  delete Mang; Mang = 0;
   return false;
 }
 
@@ -925,9 +903,11 @@ void ELFWriter::EmitStringTable(const std::string &ModuleName) {
     ELFSym &Sym = *(*I);
 
     std::string Name;
-    if (Sym.isGlobalValue())
-      Name.append(Mang->getMangledName(Sym.getGlobalValue()));
-    else if (Sym.isExternalSym())
+    if (Sym.isGlobalValue()) {
+      SmallString<40> NameStr;
+      Mang->getNameWithPrefix(NameStr, Sym.getGlobalValue(), false);
+      Name.append(NameStr.begin(), NameStr.end());
+    } else if (Sym.isExternalSym())
       Name.append(Sym.getExternalSymbol());
     else if (Sym.isFileType())
       Name.append(ModuleName);
@@ -1095,9 +1075,9 @@ void ELFWriter::OutputSectionsAndSectionTable() {
   // Emit all of sections to the file and build the section header table.
   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";
+    DEBUG(dbgs() << "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.size()) {