Index: clang/include/clang/CodeGen/BackendUtil.h =================================================================== --- clang/include/clang/CodeGen/BackendUtil.h +++ clang/include/clang/CodeGen/BackendUtil.h @@ -49,6 +49,8 @@ llvm::Expected FindThinLTOModule(llvm::MemoryBufferRef MBRef); + llvm::BitcodeModule * + FindThinLTOModule(llvm::MutableArrayRef BMs); } #endif Index: clang/lib/CodeGen/BackendUtil.cpp =================================================================== --- clang/lib/CodeGen/BackendUtil.cpp +++ clang/lib/CodeGen/BackendUtil.cpp @@ -1025,16 +1025,22 @@ // The bitcode file may contain multiple modules, we want the one that is // marked as being the ThinLTO module. - for (BitcodeModule &BM : *BMsOrErr) { - Expected LTOInfo = BM.getLTOInfo(); - if (LTOInfo && LTOInfo->IsThinLTO) - return BM; - } + if (const BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr)) + return *Bm; return make_error("Could not find module summary", inconvertibleErrorCode()); } +BitcodeModule *clang::FindThinLTOModule(MutableArrayRef BMs) { + for (BitcodeModule &BM : BMs) { + Expected LTOInfo = BM.getLTOInfo(); + if (LTOInfo && LTOInfo->IsThinLTO) + return &BM; + } + return nullptr; +} + static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M, const HeaderSearchOptions &HeaderOpts, const CodeGenOptions &CGOpts, Index: clang/lib/CodeGen/CodeGenAction.cpp =================================================================== --- clang/lib/CodeGen/CodeGenAction.cpp +++ clang/lib/CodeGen/CodeGenAction.cpp @@ -947,12 +947,18 @@ return {}; }; - Expected BMOrErr = FindThinLTOModule(MBRef); - if (!BMOrErr) - return DiagErrors(BMOrErr.takeError()); - + Expected> BMsOrErr = getBitcodeModuleList(MBRef); + if (!BMsOrErr) + return DiagErrors(BMsOrErr.takeError()); + BitcodeModule *Bm = FindThinLTOModule(*BMsOrErr); + // We have nothing to do if the file contains no ThinLTO module. This is + // possible if ThinLTO compilation was not able to split module. Content of + // the file was already processed by indexing and will be passed to the + // linker using merged object file. + if (!Bm) + return {}; Expected> MOrErr = - BMOrErr->parseModule(*VMContext); + Bm->parseModule(*VMContext); if (!MOrErr) return DiagErrors(MOrErr.takeError()); return std::move(*MOrErr); Index: clang/test/CodeGen/thinlto_backend.ll =================================================================== --- clang/test/CodeGen/thinlto_backend.ll +++ clang/test/CodeGen/thinlto_backend.ll @@ -20,6 +20,11 @@ ; CHECK-OBJ-IGNORE-EMPTY: T f1 ; CHECK-OBJ-IGNORE-EMPTY: U f2 +; Ensure we don't fail with index and non-ThinLTO object file, and run +; non-ThinLTO compilation which +; RUN: opt -o %t5.o %s +; RUN: %clang -target x86_64-unknown-linux-gnu -O2 -o %t4.o -x ir %t5.o -c -fthinlto-index=%t.thinlto.bc + ; Ensure f2 was imported ; RUN: %clang -target x86_64-unknown-linux-gnu -O2 -o %t3.o -x ir %t1.o -c -fthinlto-index=%t.thinlto.bc ; RUN: llvm-nm %t3.o | FileCheck --check-prefix=CHECK-OBJ %s