Put comment printing under asm-verbose.
[oota-llvm.git] / lib / CodeGen / ELFWriter.cpp
index a26f93bb7d01ed63d313ae9e1c1de67d2dda8bf8..8cbaf6f13bd6ebd651108273441bc41515d5280f 100644 (file)
@@ -145,11 +145,44 @@ bool ELFWriter::doInitialization(Module &M) {
   return false;
 }
 
+// Get jump table section on the section name returned by TAI
+ELFSection &ELFWriter::getJumpTableSection() {
+  unsigned Align = TM.getTargetData()->getPointerABIAlignment();
+  return getSection(TAI->getJumpTableDataSection(),
+                    ELFSection::SHT_PROGBITS,
+                    ELFSection::SHF_ALLOC, Align);
+}
+
+// Get a constant pool section based on the section name returned by TAI
+ELFSection &ELFWriter::getConstantPoolSection(MachineConstantPoolEntry &CPE) {
+  uint64_t Size = TM.getTargetData()->getTypeAllocSize(CPE.getType());
+  
+  std::string CstPoolName =
+    TAI->getSectionForMergableConstant(Size,CPE.getRelocationInfo())->getName();
+  return getSection(CstPoolName,
+                    ELFSection::SHT_PROGBITS,
+                    ELFSection::SHF_MERGE | ELFSection::SHF_ALLOC,
+                    CPE.getAlignment());
+}
+
+// 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");
+  if (TEW->hasRelocationAddend())
+    RelSName.append("a");
+  RelSName.append(S.getName());
+
+  return getSection(RelSName, SectionHeaderTy, 0, TEW->getPrefELFAlignment());
+}
+
 // getGlobalELFVisibility - Returns the ELF specific visibility type
 unsigned ELFWriter::getGlobalELFVisibility(const GlobalValue *GV) {
   switch (GV->getVisibility()) {
   default:
-    LLVM_UNREACHABLE("unknown visibility type");
+    llvm_unreachable("unknown visibility type");
   case GlobalValue::DefaultVisibility:
     return ELFSym::STV_DEFAULT;
   case GlobalValue::HiddenVisibility:
@@ -209,39 +242,40 @@ static bool isELFUndefSym(const GlobalValue *GV) {
 
 // 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());
+static bool isELFBssSym(const GlobalVariable *GV) {
+  const Constant *CV = GV->getInitializer();
+  return ((CV->isNullValue() || isa<UndefValue>(CV)) && !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());
+static bool isELFCommonSym(const GlobalVariable *GV) {
+  const Constant *CV = GV->getInitializer();
+  return ((CV->isNullValue() || isa<UndefValue>(CV)) && 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)));
+static bool isELFDataSym(const Constant *CV) {
+  return (!(CV->isNullValue() || isa<UndefValue>(CV)));
 }
 
 // EmitGlobal - Choose the right section for global and emit it
 void ELFWriter::EmitGlobal(const GlobalValue *GV) {
 
+  // Check if the referenced symbol is already emitted
+  if (GblSymLookup.find(GV) != GblSymLookup.end())
+    return;
+
   // Handle ELF Bind, Visibility and Type for the current symbol
   unsigned SymBind = getGlobalELFBinding(GV);
-  ELFSym GblSym(GV);
-  GblSym.setBind(SymBind);
-  GblSym.setVisibility(getGlobalELFVisibility(GV));
-  GblSym.setType(getGlobalELFType(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;
+    GblSym->SectionIdx = ELFSection::SHN_UNDEF;
   } else {
     assert(isa<GlobalVariable>(GV) && "GV not a global variable!");
     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
@@ -254,41 +288,41 @@ void ELFWriter::EmitGlobal(const GlobalValue *GV) {
     const TargetData *TD = TM.getTargetData();
     unsigned Align = TD->getPreferredAlignment(GVar);
     unsigned Size = TD->getTypeAllocSize(GVar->getInitializer()->getType());
-    GblSym.Size = Size;
+    GblSym->Size = Size;
 
-    if (isELFCommonSym(GV)) {
-      GblSym.SectionIdx = ELFSection::SHN_COMMON;
+    if (isELFCommonSym(GVar)) {
+      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;
+      GblSym->Value = Align;
 
-    } else if (isELFBssSym(GV)) {
+    } else if (isELFBssSym(GVar)) {
       ELFSection &ES =
         getSection(S->getName(), ELFSection::SHT_NOBITS, SectionFlags);
-      GblSym.SectionIdx = ES.SectionIdx;
+      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.
+      // 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;
+      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->SectionIdx = ES.SectionIdx;
 
-      // GblSym.Value should contain the symbol offset inside the section,
+      // 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);
+      GblSym->Value = (ES.size() + (Align-1)) & (-Align);
       ES.emitAlignment(ES.Align);
 
       // Emit the global to the data section 'ES'
@@ -296,13 +330,16 @@ void ELFWriter::EmitGlobal(const GlobalValue *GV) {
     }
   }
 
-  // Local symbols should come first on the symbol table.
-  if (!GV->hasPrivateLinkage()) {
-    if (SymBind == ELFSym::STB_LOCAL)
-      SymbolList.push_front(GblSym);
-    else
-      SymbolList.push_back(GblSym);
+  // Private symbols must never go to the symbol table.
+  unsigned SymIdx = 0;
+  if (GV->hasPrivateLinkage()) {
+    PrivateSyms.push_back(GblSym);
+    SymIdx = PrivateSyms.size()-1;
+  } else {
+    SymbolList.push_back(GblSym);
   }
+
+  setGlobalSymLookup(GV, SymIdx);
 }
 
 void ELFWriter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
@@ -359,9 +396,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) {
-      LLVM_UNREACHABLE("X86_FP80Ty global emission not implemented");
+      llvm_unreachable("X86_FP80Ty global emission not implemented");
     } else if (CFP->getType() == Type::PPC_FP128Ty)
-      LLVM_UNREACHABLE("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)
@@ -369,15 +406,44 @@ void ELFWriter::EmitGlobalConstant(const Constant *CV, ELFSection &GblS) {
     else if (Size == 8)
       GblS.emitWord64(CI->getZExtValue());
     else
-      LLVM_UNREACHABLE("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();
     for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
       EmitGlobalConstant(CP->getOperand(I), GblS);
     return;
+  } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
+    // This is a constant address for a global variable or function and
+    // therefore must be referenced using a relocation entry.
+
+    // Check if the referenced symbol is already emitted
+    if (GblSymLookup.find(GV) == GblSymLookup.end())
+      EmitGlobal(GV);
+
+    // Create the relocation entry for the global value
+    MachineRelocation MR =
+      MachineRelocation::getGV(GblS.getCurrentPCOffset(),
+                               TEW->getAbsoluteLabelMachineRelTy(),
+                               const_cast<GlobalValue*>(GV));
+
+    // Fill the data entry with zeros
+    for (unsigned i=0; i < Size; ++i)
+      GblS.emitByte(0);
+
+    // Add the relocation entry for the current data section
+    GblS.addRelocation(MR);
+    return;
+  } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
+    if (CE->getOpcode() == Instruction::BitCast) {
+      EmitGlobalConstant(CE->getOperand(0), GblS);
+      return;
+    }
+    // See AsmPrinter::EmitConstantValueOnly for other ConstantExpr types
+    llvm_unreachable("Unsupported ConstantExpr type");
   }
-  LLVM_UNREACHABLE("unknown global constant");
+
+  llvm_unreachable("Unknown global constant type");
 }
 
 
@@ -397,45 +463,29 @@ 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;
-
+       E = PendingGlobals.end(); I != E; ++I)
     EmitGlobal(*I);
-    GblSymLookup[*I] = 0;
-  }
 
   // Emit non-executable stack note
   if (TAI->getNonexecutableStackDirective())
     getNonExecStackSection();
 
-  // Emit a symbol for each section created until now
-  for (std::map<std::string, ELFSection*>::iterator I = SectionLookup.begin(),
-       E = SectionLookup.end(); I != E; ++I) {
-    ELFSection *ES = I->second;
-
-    // Skip null section
-    if (ES->SectionIdx == 0) continue;
-
-    ELFSym SectionSym(0);
-    SectionSym.SectionIdx = ES->SectionIdx;
-    SectionSym.Size = 0;
-    SectionSym.setBind(ELFSym::STB_LOCAL);
-    SectionSym.setType(ELFSym::STT_SECTION);
-    SectionSym.setVisibility(ELFSym::STV_DEFAULT);
-
-    // Local symbols go in the list front
-    SymbolList.push_front(SectionSym);
+  // 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
@@ -454,6 +504,7 @@ bool ELFWriter::doFinalization(Module &M) {
   OutputSectionsAndSectionTable();
 
   // We are done with the abstract symbols.
+  SymbolList.clear();
   SectionList.clear();
   NumSections = 0;
 
@@ -462,45 +513,55 @@ bool ELFWriter::doFinalization(Module &M) {
   return false;
 }
 
+// RelocateField - Patch relocatable field with 'Offset' in 'BO'
+// using a 'Value' of known 'Size'
+void ELFWriter::RelocateField(BinaryObject &BO, uint32_t Offset,
+                              int64_t Value, unsigned Size) {
+  if (Size == 32)
+    BO.fixWord32(Value, Offset);
+  else if (Size == 64)
+    BO.fixWord64(Value, Offset);
+  else
+    llvm_unreachable("don't know howto patch relocatable field");
+}
+
 /// EmitRelocations - Emit relocations
 void ELFWriter::EmitRelocations() {
 
+  // True if the target uses the relocation entry to hold the addend,
+  // otherwise the addend is written directly to the relocatable field.
+  bool HasRelA = TEW->hasRelocationAddend();
+
   // Create Relocation sections for each section which needs it.
-  for (std::list<ELFSection>::iterator I = SectionList.begin(),
-       E = SectionList.end(); I != E; ++I) {
+  for (unsigned i=0, e=SectionList.size(); i != e; ++i) {
+    ELFSection &S = *SectionList[i];
 
     // This section does not have relocations
-    if (!I->hasRelocations()) continue;
-
-    // Get the relocation section for section 'I'
-    bool HasRelA = TEW->hasRelocationAddend();
-    ELFSection &RelSec = getRelocSection(I->getName(), HasRelA,
-                                         TEW->getPrefELFAlignment());
+    if (!S.hasRelocations()) continue;
+    ELFSection &RelSec = getRelocSection(S);
 
     // '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 = I->SectionIdx;
+    RelSec.Info = S.SectionIdx;
     RelSec.EntSize = TEW->getRelocationEntrySize();
 
     // Get the relocations from Section
-    std::vector<MachineRelocation> Relos = I->getRelocations();
+    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();
+      // Relocatable field offset from the section start
+      unsigned RelOffset = MR.getMachineCodeOffset();
 
       // Symbol index in the symbol table
       unsigned SymIdx = 0;
 
-      // Target specific ELF relocation type
+      // Target specific relocation field type and size
       unsigned RelType = TEW->getRelocationType(MR.getRelocationType());
-
-      // Constant addend used to compute the value to be stored
-      // into the relocatable field
+      unsigned RelTySize = TEW->getRelocationTySize(RelType);
       int64_t Addend = 0;
 
       // There are several machine relocations types, and each one of
@@ -508,22 +569,45 @@ void ELFWriter::EmitRelocations() {
       if (MR.isGlobalValue()) {
         const GlobalValue *G = MR.getGlobalValue();
         SymIdx = GblSymLookup[G];
-        Addend = TEW->getAddendForRelTy(RelType);
+        if (G->hasPrivateLinkage()) {
+          // If the target uses a section offset in the relocation:
+          // SymIdx + Addend = section sym for global + section offset
+          unsigned SectionIdx = PrivateSyms[SymIdx]->SectionIdx;
+          Addend = PrivateSyms[SymIdx]->Value;
+          SymIdx = SectionList[SectionIdx]->getSymbolTableIndex();
+        } else {
+          Addend = TEW->getDefaultAddendForRelTy(RelType);
+        }
       } else {
+        // Get the symbol index for the section symbol
         unsigned SectionIdx = MR.getConstantVal();
-        // TODO: use a map for this.
-        for (std::list<ELFSym>::iterator I = SymbolList.begin(),
-             E = SymbolList.end(); I != E; ++I)
-          if ((SectionIdx == I->SectionIdx) &&
-              (I->getType() == ELFSym::STT_SECTION)) {
-            SymIdx = I->SymTabIdx;
-            break;
-          }
+        SymIdx = SectionList[SectionIdx]->getSymbolTableIndex();
         Addend = (uint64_t)MR.getResultPointer();
+
+        // For pc relative relocations where symbols are defined in the same
+        // section they are referenced, ignore the relocation entry and patch
+        // the relocatable field with the symbol offset directly.
+        if (S.SectionIdx == SectionIdx && TEW->isPCRelativeRel(RelType)) {
+          int64_t Value = TEW->computeRelocation(Addend, RelOffset, RelType);
+          RelocateField(S, RelOffset, Value, RelTySize);
+          continue;
+        }
+
+        // Handle Jump Table Index relocation
+        if ((SectionIdx == getJumpTableSection().SectionIdx) &&
+            TEW->hasCustomJumpTableIndexRelTy()) {
+          RelType = TEW->getJumpTableIndexRelTy();
+          RelTySize = TEW->getRelocationTySize(RelType);
+        }
       }
 
+      // The target without addend on the relocation symbol must be
+      // patched in the relocation place itself to contain the addend
+      if (!HasRelA)
+        RelocateField(S, RelOffset, Addend, RelTySize);
+
       // Get the relocation entry and emit to the relocation section
-      ELFRelocation Rel(Offset, SymIdx, RelType, HasRelA, Addend);
+      ELFRelocation Rel(RelOffset, SymIdx, RelType, HasRelA, Addend);
       EmitRelocation(RelSec, Rel, HasRelA);
     }
   }
@@ -593,20 +677,19 @@ void ELFWriter::EmitStringTable() {
   // 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.
+  // Walk on the symbol list and write symbol names into the string table.
   unsigned Index = 1;
-  for (std::list<ELFSym>::iterator I = SymbolList.begin(),
-       E = SymbolList.end(); 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;
-    if (I->GV) Name.append(Mang->getValueName(I->GV));
+    if (Sym.GV) Name.append(Mang->getMangledName(Sym.GV));
 
     if (Name.empty()) {
-      I->NameIdx = 0;
+      Sym.NameIdx = 0;
     } else {
-      I->NameIdx = Index;
+      Sym.NameIdx = Index;
       StrTab.emitString(Name);
 
       // Keep track of the number of bytes emitted to this section.
@@ -617,11 +700,38 @@ void ELFWriter::EmitStringTable() {
   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.
 
-  unsigned FirstNonLocalSymbol = 1;
   // 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();
@@ -634,29 +744,26 @@ void ELFWriter::EmitSymbolTable() {
   SymTab.EntSize = TEW->getSymTabEntrySize();
 
   // The first entry in the symtab is the null symbol
-  ELFSym NullSym = ELFSym(0);
-  EmitSymbol(SymTab, NullSym);
+  SymbolList.insert(SymbolList.begin(), new ELFSym(0));
 
-  // Emit all the symbols to the symbol table. Skip the null
-  // symbol, cause it's emitted already
-  unsigned Index = 1;
-  for (std::list<ELFSym>::iterator I = SymbolList.begin(),
-       E = SymbolList.end(); I != E; ++I, ++Index) {
-    // Keep track of the first non-local symbol
-    if (I->getBind() == ELFSym::STB_LOCAL)
-      FirstNonLocalSymbol++;
+  // 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, *I);
+    EmitSymbol(SymTab, Sym);
 
     // Record the symbol table index for each global value
-    if (I->GV)
-      GblSymLookup[I->GV] = Index;
+    if (Sym.GV) setGlobalSymLookup(Sym.GV, i);
 
     // Keep track on the symbol index into the symbol table
-    I->SymTabIdx = Index;
+    Sym.SymTabIdx = i;
   }
 
+  // One greater than the symbol table index of the last local symbol
   SymTab.Info = FirstNonLocalSymbol;
   SymTab.Size = SymTab.size();
 }
@@ -676,15 +783,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.
@@ -699,29 +806,24 @@ 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.
@@ -745,8 +847,8 @@ 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";
@@ -763,7 +865,6 @@ void ELFWriter::OutputSectionsAndSectionTable() {
     }
 
     EmitSectionHeader(SHdrTable, S);
-    SectionList.pop_front();
   }
 
   // Align output for the section table.