Index: llvm/trunk/include/llvm/LTO/LTOCodeGenerator.h =================================================================== --- llvm/trunk/include/llvm/LTO/LTOCodeGenerator.h +++ llvm/trunk/include/llvm/LTO/LTOCodeGenerator.h @@ -148,6 +148,8 @@ LLVMContext &getContext() { return Context; } + void resetMergedModule() { MergedModule.reset(); } + private: void initializeLTOPasses(); Index: llvm/trunk/tools/lto/lto.cpp =================================================================== --- llvm/trunk/tools/lto/lto.cpp +++ llvm/trunk/tools/lto/lto.cpp @@ -124,6 +124,10 @@ : LTOCodeGenerator(*Context), OwnedContext(std::move(Context)) { setDiagnosticHandler(handleLibLTODiagnostic, nullptr); } + // Reset the module first in case MergedModule is created in OwnedContext. + // Module must be destructed before its context gets destructed. + ~LibLTOCodeGenerator() { resetMergedModule(); } + std::unique_ptr NativeObjectFile; std::unique_ptr OwnedContext; };