Index: ELF/Writer.cpp =================================================================== --- ELF/Writer.cpp +++ ELF/Writer.cpp @@ -1180,22 +1180,23 @@ if (!SS->empty() || !OS) continue; - std::vector::iterator Empty = OS->Commands.end(); - for (auto I = OS->Commands.begin(), E = OS->Commands.end(); I != E; ++I) { - BaseCommand *B = *I; + // SS is an unused synthetic section. Remove it from output section command. + for (BaseCommand *B : OS->Commands) { if (auto *ISD = dyn_cast(B)) { - llvm::erase_if(ISD->Sections, - [=](InputSection *IS) { return IS == SS; }); - if (ISD->Sections.empty()) - Empty = I; + auto It = llvm::find(ISD->Sections, SS); + if (It == ISD->Sections.end()) + continue; + ISD->Sections.erase(It); + break; } } - if (Empty != OS->Commands.end()) - OS->Commands.erase(Empty); - // If there are no other sections in the output section, remove it from the - // output. - if (OS->Commands.empty()) + // If SS was the only section content, remove the entire output section. + bool IsEmpty = llvm::all_of(OS->Commands, [](BaseCommand *B) { + auto *ISD = dyn_cast(B); + return ISD && ISD->Sections.empty(); + }); + if (IsEmpty) OS->Live = false; } } Index: test/ELF/linkerscript/unused-synthetic.s =================================================================== --- test/ELF/linkerscript/unused-synthetic.s +++ test/ELF/linkerscript/unused-synthetic.s @@ -1,7 +1,7 @@ # REQUIRES: x86 # RUN: llvm-mc -filetype=obj -triple=x86_64-unknown-linux %s -o %t.o # RUN: echo "SECTIONS { \ -# RUN: .got : { *(.got) } \ +# RUN: .got : { *(.got) *(.got) } \ # RUN: .plt : { *(.plt) } \ # RUN: .text : { *(.text) } \ # RUN: }" > %t.script