1 //===-LTOBackend.cpp - LLVM Link Time Optimizer Backend -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the "backend" phase of LTO, i.e. it performs
10 // optimization and code generation on a loaded module. It is generally used
11 // internally by the LTO class but can also be used independently, for example
12 // to implement a standalone ThinLTO backend.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/LTO/LTOBackend.h"
17 #include "llvm/Analysis/AliasAnalysis.h"
18 #include "llvm/Analysis/CGSCCPassManager.h"
19 #include "llvm/Analysis/TargetLibraryInfo.h"
20 #include "llvm/Analysis/TargetTransformInfo.h"
21 #include "llvm/Bitcode/BitcodeReader.h"
22 #include "llvm/Bitcode/BitcodeWriter.h"
23 #include "llvm/IR/LLVMRemarkStreamer.h"
24 #include "llvm/IR/LegacyPassManager.h"
25 #include "llvm/IR/PassManager.h"
26 #include "llvm/IR/Verifier.h"
27 #include "llvm/LTO/LTO.h"
28 #include "llvm/MC/SubtargetFeature.h"
29 #include "llvm/Object/ModuleSymbolTable.h"
30 #include "llvm/Passes/PassBuilder.h"
31 #include "llvm/Passes/StandardInstrumentations.h"
32 #include "llvm/Support/Error.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/Path.h"
36 #include "llvm/Support/Program.h"
37 #include "llvm/Support/SmallVectorMemoryBuffer.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Support/ThreadPool.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Transforms/IPO.h"
43 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
44 #include "llvm/Transforms/Scalar/LoopPassManager.h"
45 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
46 #include "llvm/Transforms/Utils/SplitModule.h"
47 
48 using namespace llvm;
49 using namespace lto;
50 
51 LLVM_ATTRIBUTE_NORETURN static void reportOpenError(StringRef Path, Twine Msg) {
52   errs() << "failed to open " << Path << ": " << Msg << '\n';
53   errs().flush();
54   exit(1);
55 }
56 
57 Error Config::addSaveTemps(std::string OutputFileName,
58                            bool UseInputModulePath) {
59   ShouldDiscardValueNames = false;
60 
61   std::error_code EC;
62   ResolutionFile = std::make_unique<raw_fd_ostream>(
63       OutputFileName + "resolution.txt", EC, sys::fs::OpenFlags::OF_Text);
64   if (EC)
65     return errorCodeToError(EC);
66 
67   auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
68     // Keep track of the hook provided by the linker, which also needs to run.
69     ModuleHookFn LinkerHook = Hook;
70     Hook = [=](unsigned Task, const Module &M) {
71       // If the linker's hook returned false, we need to pass that result
72       // through.
73       if (LinkerHook && !LinkerHook(Task, M))
74         return false;
75 
76       std::string PathPrefix;
77       // If this is the combined module (not a ThinLTO backend compile) or the
78       // user hasn't requested using the input module's path, emit to a file
79       // named from the provided OutputFileName with the Task ID appended.
80       if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
81         PathPrefix = OutputFileName;
82         if (Task != (unsigned)-1)
83           PathPrefix += utostr(Task) + ".";
84       } else
85         PathPrefix = M.getModuleIdentifier() + ".";
86       std::string Path = PathPrefix + PathSuffix + ".bc";
87       std::error_code EC;
88       raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::OF_None);
89       // Because -save-temps is a debugging feature, we report the error
90       // directly and exit.
91       if (EC)
92         reportOpenError(Path, EC.message());
93       WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false);
94       return true;
95     };
96   };
97 
98   setHook("0.preopt", PreOptModuleHook);
99   setHook("1.promote", PostPromoteModuleHook);
100   setHook("2.internalize", PostInternalizeModuleHook);
101   setHook("3.import", PostImportModuleHook);
102   setHook("4.opt", PostOptModuleHook);
103   setHook("5.precodegen", PreCodeGenModuleHook);
104 
105   CombinedIndexHook =
106       [=](const ModuleSummaryIndex &Index,
107           const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
108         std::string Path = OutputFileName + "index.bc";
109         std::error_code EC;
110         raw_fd_ostream OS(Path, EC, sys::fs::OpenFlags::OF_None);
111         // Because -save-temps is a debugging feature, we report the error
112         // directly and exit.
113         if (EC)
114           reportOpenError(Path, EC.message());
115         WriteIndexToFile(Index, OS);
116 
117         Path = OutputFileName + "index.dot";
118         raw_fd_ostream OSDot(Path, EC, sys::fs::OpenFlags::OF_None);
119         if (EC)
120           reportOpenError(Path, EC.message());
121         Index.exportToDot(OSDot, GUIDPreservedSymbols);
122         return true;
123       };
124 
125   return Error::success();
126 }
127 
128 namespace {
129 
130 std::unique_ptr<TargetMachine>
131 createTargetMachine(const Config &Conf, const Target *TheTarget, Module &M) {
132   StringRef TheTriple = M.getTargetTriple();
133   SubtargetFeatures Features;
134   Features.getDefaultSubtargetFeatures(Triple(TheTriple));
135   for (const std::string &A : Conf.MAttrs)
136     Features.AddFeature(A);
137 
138   Reloc::Model RelocModel;
139   if (Conf.RelocModel)
140     RelocModel = *Conf.RelocModel;
141   else
142     RelocModel =
143         M.getPICLevel() == PICLevel::NotPIC ? Reloc::Static : Reloc::PIC_;
144 
145   Optional<CodeModel::Model> CodeModel;
146   if (Conf.CodeModel)
147     CodeModel = *Conf.CodeModel;
148   else
149     CodeModel = M.getCodeModel();
150 
151   return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
152       TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel,
153       CodeModel, Conf.CGOptLevel));
154 }
155 
156 static void runNewPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM,
157                            unsigned OptLevel, bool IsThinLTO,
158                            ModuleSummaryIndex *ExportSummary,
159                            const ModuleSummaryIndex *ImportSummary) {
160   Optional<PGOOptions> PGOOpt;
161   if (!Conf.SampleProfile.empty())
162     PGOOpt = PGOOptions(Conf.SampleProfile, "", Conf.ProfileRemapping,
163                         PGOOptions::SampleUse, PGOOptions::NoCSAction, true);
164   else if (Conf.RunCSIRInstr) {
165     PGOOpt = PGOOptions("", Conf.CSIRProfile, Conf.ProfileRemapping,
166                         PGOOptions::IRUse, PGOOptions::CSIRInstr);
167   } else if (!Conf.CSIRProfile.empty()) {
168     PGOOpt = PGOOptions(Conf.CSIRProfile, "", Conf.ProfileRemapping,
169                         PGOOptions::IRUse, PGOOptions::CSIRUse);
170   }
171 
172   PassInstrumentationCallbacks PIC;
173   StandardInstrumentations SI;
174   SI.registerCallbacks(PIC);
175   PassBuilder PB(TM, Conf.PTO, PGOOpt, &PIC);
176   AAManager AA;
177 
178   // Parse a custom AA pipeline if asked to.
179   if (auto Err = PB.parseAAPipeline(AA, "default"))
180     report_fatal_error("Error parsing default AA pipeline");
181 
182   LoopAnalysisManager LAM(Conf.DebugPassManager);
183   FunctionAnalysisManager FAM(Conf.DebugPassManager);
184   CGSCCAnalysisManager CGAM(Conf.DebugPassManager);
185   ModuleAnalysisManager MAM(Conf.DebugPassManager);
186 
187   // Register the AA manager first so that our version is the one used.
188   FAM.registerPass([&] { return std::move(AA); });
189 
190   // Register all the basic analyses with the managers.
191   PB.registerModuleAnalyses(MAM);
192   PB.registerCGSCCAnalyses(CGAM);
193   PB.registerFunctionAnalyses(FAM);
194   PB.registerLoopAnalyses(LAM);
195   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
196 
197   ModulePassManager MPM(Conf.DebugPassManager);
198   // FIXME (davide): verify the input.
199 
200   PassBuilder::OptimizationLevel OL;
201 
202   switch (OptLevel) {
203   default:
204     llvm_unreachable("Invalid optimization level");
205   case 0:
206     OL = PassBuilder::OptimizationLevel::O0;
207     break;
208   case 1:
209     OL = PassBuilder::OptimizationLevel::O1;
210     break;
211   case 2:
212     OL = PassBuilder::OptimizationLevel::O2;
213     break;
214   case 3:
215     OL = PassBuilder::OptimizationLevel::O3;
216     break;
217   }
218 
219   if (IsThinLTO)
220     MPM = PB.buildThinLTODefaultPipeline(OL, Conf.DebugPassManager,
221                                          ImportSummary);
222   else
223     MPM = PB.buildLTODefaultPipeline(OL, Conf.DebugPassManager, ExportSummary);
224   MPM.run(Mod, MAM);
225 
226   // FIXME (davide): verify the output.
227 }
228 
229 static void runNewPMCustomPasses(Module &Mod, TargetMachine *TM,
230                                  std::string PipelineDesc,
231                                  std::string AAPipelineDesc,
232                                  bool DisableVerify) {
233   PassBuilder PB(TM);
234   AAManager AA;
235 
236   // Parse a custom AA pipeline if asked to.
237   if (!AAPipelineDesc.empty())
238     if (auto Err = PB.parseAAPipeline(AA, AAPipelineDesc))
239       report_fatal_error("unable to parse AA pipeline description '" +
240                          AAPipelineDesc + "': " + toString(std::move(Err)));
241 
242   LoopAnalysisManager LAM;
243   FunctionAnalysisManager FAM;
244   CGSCCAnalysisManager CGAM;
245   ModuleAnalysisManager MAM;
246 
247   // Register the AA manager first so that our version is the one used.
248   FAM.registerPass([&] { return std::move(AA); });
249 
250   // Register all the basic analyses with the managers.
251   PB.registerModuleAnalyses(MAM);
252   PB.registerCGSCCAnalyses(CGAM);
253   PB.registerFunctionAnalyses(FAM);
254   PB.registerLoopAnalyses(LAM);
255   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
256 
257   ModulePassManager MPM;
258 
259   // Always verify the input.
260   MPM.addPass(VerifierPass());
261 
262   // Now, add all the passes we've been requested to.
263   if (auto Err = PB.parsePassPipeline(MPM, PipelineDesc))
264     report_fatal_error("unable to parse pass pipeline description '" +
265                        PipelineDesc + "': " + toString(std::move(Err)));
266 
267   if (!DisableVerify)
268     MPM.addPass(VerifierPass());
269   MPM.run(Mod, MAM);
270 }
271 
272 static void runOldPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM,
273                            bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
274                            const ModuleSummaryIndex *ImportSummary) {
275   legacy::PassManager passes;
276   passes.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
277 
278   PassManagerBuilder PMB;
279   PMB.LibraryInfo = new TargetLibraryInfoImpl(Triple(TM->getTargetTriple()));
280   PMB.Inliner = createFunctionInliningPass();
281   PMB.ExportSummary = ExportSummary;
282   PMB.ImportSummary = ImportSummary;
283   // Unconditionally verify input since it is not verified before this
284   // point and has unknown origin.
285   PMB.VerifyInput = true;
286   PMB.VerifyOutput = !Conf.DisableVerify;
287   PMB.LoopVectorize = true;
288   PMB.SLPVectorize = true;
289   PMB.OptLevel = Conf.OptLevel;
290   PMB.PGOSampleUse = Conf.SampleProfile;
291   PMB.EnablePGOCSInstrGen = Conf.RunCSIRInstr;
292   if (!Conf.RunCSIRInstr && !Conf.CSIRProfile.empty()) {
293     PMB.EnablePGOCSInstrUse = true;
294     PMB.PGOInstrUse = Conf.CSIRProfile;
295   }
296   if (IsThinLTO)
297     PMB.populateThinLTOPassManager(passes);
298   else
299     PMB.populateLTOPassManager(passes);
300   passes.run(Mod);
301 }
302 
303 bool opt(const Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
304          bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
305          const ModuleSummaryIndex *ImportSummary) {
306   // FIXME: Plumb the combined index into the new pass manager.
307   if (!Conf.OptPipeline.empty())
308     runNewPMCustomPasses(Mod, TM, Conf.OptPipeline, Conf.AAPipeline,
309                          Conf.DisableVerify);
310   else if (Conf.UseNewPM)
311     runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO, ExportSummary,
312                    ImportSummary);
313   else
314     runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
315   return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
316 }
317 
318 static cl::opt<bool> EmbedBitcode(
319     "lto-embed-bitcode", cl::init(false),
320     cl::desc("Embed LLVM bitcode in object files produced by LTO"));
321 
322 static void EmitBitcodeSection(Module &M, const Config &Conf) {
323   if (!EmbedBitcode)
324     return;
325   SmallVector<char, 0> Buffer;
326   raw_svector_ostream OS(Buffer);
327   WriteBitcodeToFile(M, OS);
328 
329   std::unique_ptr<MemoryBuffer> Buf(
330       new SmallVectorMemoryBuffer(std::move(Buffer)));
331   llvm::EmbedBitcodeInModule(M, Buf->getMemBufferRef(), /*EmbedBitcode*/ true,
332                              /*EmbedMarker*/ false, /*CmdArgs*/ nullptr);
333 }
334 
335 void codegen(const Config &Conf, TargetMachine *TM, AddStreamFn AddStream,
336              unsigned Task, Module &Mod) {
337   if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
338     return;
339 
340   EmitBitcodeSection(Mod, Conf);
341 
342   std::unique_ptr<ToolOutputFile> DwoOut;
343   SmallString<1024> DwoFile(Conf.SplitDwarfOutput);
344   if (!Conf.DwoDir.empty()) {
345     std::error_code EC;
346     if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
347       report_fatal_error("Failed to create directory " + Conf.DwoDir + ": " +
348                          EC.message());
349 
350     DwoFile = Conf.DwoDir;
351     sys::path::append(DwoFile, std::to_string(Task) + ".dwo");
352     TM->Options.MCOptions.SplitDwarfFile = std::string(DwoFile);
353   } else
354     TM->Options.MCOptions.SplitDwarfFile = Conf.SplitDwarfFile;
355 
356   if (!DwoFile.empty()) {
357     std::error_code EC;
358     DwoOut = std::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::OF_None);
359     if (EC)
360       report_fatal_error("Failed to open " + DwoFile + ": " + EC.message());
361   }
362 
363   auto Stream = AddStream(Task);
364   legacy::PassManager CodeGenPasses;
365   if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
366                               DwoOut ? &DwoOut->os() : nullptr,
367                               Conf.CGFileType))
368     report_fatal_error("Failed to setup codegen");
369   CodeGenPasses.run(Mod);
370 
371   if (DwoOut)
372     DwoOut->keep();
373 }
374 
375 void splitCodeGen(const Config &C, TargetMachine *TM, AddStreamFn AddStream,
376                   unsigned ParallelCodeGenParallelismLevel,
377                   std::unique_ptr<Module> Mod) {
378   ThreadPool CodegenThreadPool(
379       heavyweight_hardware_concurrency(ParallelCodeGenParallelismLevel));
380   unsigned ThreadCount = 0;
381   const Target *T = &TM->getTarget();
382 
383   SplitModule(
384       std::move(Mod), ParallelCodeGenParallelismLevel,
385       [&](std::unique_ptr<Module> MPart) {
386         // We want to clone the module in a new context to multi-thread the
387         // codegen. We do it by serializing partition modules to bitcode
388         // (while still on the main thread, in order to avoid data races) and
389         // spinning up new threads which deserialize the partitions into
390         // separate contexts.
391         // FIXME: Provide a more direct way to do this in LLVM.
392         SmallString<0> BC;
393         raw_svector_ostream BCOS(BC);
394         WriteBitcodeToFile(*MPart, BCOS);
395 
396         // Enqueue the task
397         CodegenThreadPool.async(
398             [&](const SmallString<0> &BC, unsigned ThreadId) {
399               LTOLLVMContext Ctx(C);
400               Expected<std::unique_ptr<Module>> MOrErr = parseBitcodeFile(
401                   MemoryBufferRef(StringRef(BC.data(), BC.size()), "ld-temp.o"),
402                   Ctx);
403               if (!MOrErr)
404                 report_fatal_error("Failed to read bitcode");
405               std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
406 
407               std::unique_ptr<TargetMachine> TM =
408                   createTargetMachine(C, T, *MPartInCtx);
409 
410               codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
411             },
412             // Pass BC using std::move to ensure that it get moved rather than
413             // copied into the thread's context.
414             std::move(BC), ThreadCount++);
415       },
416       false);
417 
418   // Because the inner lambda (which runs in a worker thread) captures our local
419   // variables, we need to wait for the worker threads to terminate before we
420   // can leave the function scope.
421   CodegenThreadPool.wait();
422 }
423 
424 Expected<const Target *> initAndLookupTarget(const Config &C, Module &Mod) {
425   if (!C.OverrideTriple.empty())
426     Mod.setTargetTriple(C.OverrideTriple);
427   else if (Mod.getTargetTriple().empty())
428     Mod.setTargetTriple(C.DefaultTriple);
429 
430   std::string Msg;
431   const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
432   if (!T)
433     return make_error<StringError>(Msg, inconvertibleErrorCode());
434   return T;
435 }
436 }
437 
438 Error lto::finalizeOptimizationRemarks(
439     std::unique_ptr<ToolOutputFile> DiagOutputFile) {
440   // Make sure we flush the diagnostic remarks file in case the linker doesn't
441   // call the global destructors before exiting.
442   if (!DiagOutputFile)
443     return Error::success();
444   DiagOutputFile->keep();
445   DiagOutputFile->os().flush();
446   return Error::success();
447 }
448 
449 Error lto::backend(const Config &C, AddStreamFn AddStream,
450                    unsigned ParallelCodeGenParallelismLevel,
451                    std::unique_ptr<Module> Mod,
452                    ModuleSummaryIndex &CombinedIndex) {
453   Expected<const Target *> TOrErr = initAndLookupTarget(C, *Mod);
454   if (!TOrErr)
455     return TOrErr.takeError();
456 
457   std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, *Mod);
458 
459   if (!C.CodeGenOnly) {
460     if (!opt(C, TM.get(), 0, *Mod, /*IsThinLTO=*/false,
461              /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr))
462       return Error::success();
463   }
464 
465   if (ParallelCodeGenParallelismLevel == 1) {
466     codegen(C, TM.get(), AddStream, 0, *Mod);
467   } else {
468     splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
469                  std::move(Mod));
470   }
471   return Error::success();
472 }
473 
474 static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
475                             const ModuleSummaryIndex &Index) {
476   std::vector<GlobalValue*> DeadGVs;
477   for (auto &GV : Mod.global_values())
478     if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
479       if (!Index.isGlobalValueLive(GVS)) {
480         DeadGVs.push_back(&GV);
481         convertToDeclaration(GV);
482       }
483 
484   // Now that all dead bodies have been dropped, delete the actual objects
485   // themselves when possible.
486   for (GlobalValue *GV : DeadGVs) {
487     GV->removeDeadConstantUsers();
488     // Might reference something defined in native object (i.e. dropped a
489     // non-prevailing IR def, but we need to keep the declaration).
490     if (GV->use_empty())
491       GV->eraseFromParent();
492   }
493 }
494 
495 Error lto::thinBackend(const Config &Conf, unsigned Task, AddStreamFn AddStream,
496                        Module &Mod, const ModuleSummaryIndex &CombinedIndex,
497                        const FunctionImporter::ImportMapTy &ImportList,
498                        const GVSummaryMapTy &DefinedGlobals,
499                        MapVector<StringRef, BitcodeModule> &ModuleMap) {
500   Expected<const Target *> TOrErr = initAndLookupTarget(Conf, Mod);
501   if (!TOrErr)
502     return TOrErr.takeError();
503 
504   std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
505 
506   // Setup optimization remarks.
507   auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
508       Mod.getContext(), Conf.RemarksFilename, Conf.RemarksPasses,
509       Conf.RemarksFormat, Conf.RemarksWithHotness, Task);
510   if (!DiagFileOrErr)
511     return DiagFileOrErr.takeError();
512   auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
513 
514   if (Conf.CodeGenOnly) {
515     codegen(Conf, TM.get(), AddStream, Task, Mod);
516     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
517   }
518 
519   if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
520     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
521 
522   renameModuleForThinLTO(Mod, CombinedIndex);
523 
524   dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
525 
526   thinLTOResolvePrevailingInModule(Mod, DefinedGlobals);
527 
528   if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
529     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
530 
531   if (!DefinedGlobals.empty())
532     thinLTOInternalizeModule(Mod, DefinedGlobals);
533 
534   if (Conf.PostInternalizeModuleHook &&
535       !Conf.PostInternalizeModuleHook(Task, Mod))
536     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
537 
538   auto ModuleLoader = [&](StringRef Identifier) {
539     assert(Mod.getContext().isODRUniquingDebugTypes() &&
540            "ODR Type uniquing should be enabled on the context");
541     auto I = ModuleMap.find(Identifier);
542     assert(I != ModuleMap.end());
543     return I->second.getLazyModule(Mod.getContext(),
544                                    /*ShouldLazyLoadMetadata=*/true,
545                                    /*IsImporting*/ true);
546   };
547 
548   FunctionImporter Importer(CombinedIndex, ModuleLoader);
549   if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
550     return Err;
551 
552   if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
553     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
554 
555   if (!opt(Conf, TM.get(), Task, Mod, /*IsThinLTO=*/true,
556            /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex))
557     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
558 
559   codegen(Conf, TM.get(), AddStream, Task, Mod);
560   return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
561 }
562