1 //===-ThinLTOCodeGenerator.cpp - LLVM Link Time Optimizer -----------------===//
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 Thin Link Time Optimization library. This library is
10 // intended to be used by linker to optimize code at link time.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/LTO/legacy/ThinLTOCodeGenerator.h"
15 #include "llvm/Support/CommandLine.h"
16 
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
20 #include "llvm/Analysis/ProfileSummaryInfo.h"
21 #include "llvm/Analysis/TargetLibraryInfo.h"
22 #include "llvm/Analysis/TargetTransformInfo.h"
23 #include "llvm/Bitcode/BitcodeReader.h"
24 #include "llvm/Bitcode/BitcodeWriter.h"
25 #include "llvm/Bitcode/BitcodeWriterPass.h"
26 #include "llvm/Config/llvm-config.h"
27 #include "llvm/IR/DebugInfo.h"
28 #include "llvm/IR/DiagnosticPrinter.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/LLVMRemarkStreamer.h"
31 #include "llvm/IR/LegacyPassManager.h"
32 #include "llvm/IR/Mangler.h"
33 #include "llvm/IR/PassTimingInfo.h"
34 #include "llvm/IR/Verifier.h"
35 #include "llvm/IRReader/IRReader.h"
36 #include "llvm/LTO/LTO.h"
37 #include "llvm/LTO/SummaryBasedOptimizations.h"
38 #include "llvm/MC/SubtargetFeature.h"
39 #include "llvm/Object/IRObjectFile.h"
40 #include "llvm/Support/CachePruning.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/Error.h"
43 #include "llvm/Support/FileUtilities.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/SHA1.h"
46 #include "llvm/Support/SmallVectorMemoryBuffer.h"
47 #include "llvm/Support/TargetRegistry.h"
48 #include "llvm/Support/ThreadPool.h"
49 #include "llvm/Support/Threading.h"
50 #include "llvm/Support/ToolOutputFile.h"
51 #include "llvm/Target/TargetMachine.h"
52 #include "llvm/Transforms/IPO.h"
53 #include "llvm/Transforms/IPO/FunctionImport.h"
54 #include "llvm/Transforms/IPO/Internalize.h"
55 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
56 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
57 #include "llvm/Transforms/ObjCARC.h"
58 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
59 
60 #include <numeric>
61 
62 #if !defined(_MSC_VER) && !defined(__MINGW32__)
63 #include <unistd.h>
64 #else
65 #include <io.h>
66 #endif
67 
68 using namespace llvm;
69 
70 #define DEBUG_TYPE "thinlto"
71 
72 namespace llvm {
73 // Flags -discard-value-names, defined in LTOCodeGenerator.cpp
74 extern cl::opt<bool> LTODiscardValueNames;
75 extern cl::opt<std::string> RemarksFilename;
76 extern cl::opt<std::string> RemarksPasses;
77 extern cl::opt<bool> RemarksWithHotness;
78 extern cl::opt<std::string> RemarksFormat;
79 }
80 
81 namespace {
82 
83 // Default to using one job per hardware core in the system
84 static cl::opt<int> ThreadCount("threads", cl::init(0));
85 
86 // Simple helper to save temporary files for debug.
87 static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
88                             unsigned count, StringRef Suffix) {
89   if (TempDir.empty())
90     return;
91   // User asked to save temps, let dump the bitcode file after import.
92   std::string SaveTempPath = (TempDir + llvm::Twine(count) + Suffix).str();
93   std::error_code EC;
94   raw_fd_ostream OS(SaveTempPath, EC, sys::fs::OF_None);
95   if (EC)
96     report_fatal_error(Twine("Failed to open ") + SaveTempPath +
97                        " to save optimized bitcode\n");
98   WriteBitcodeToFile(TheModule, OS, /* ShouldPreserveUseListOrder */ true);
99 }
100 
101 static const GlobalValueSummary *
102 getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
103   // If there is any strong definition anywhere, get it.
104   auto StrongDefForLinker = llvm::find_if(
105       GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
106         auto Linkage = Summary->linkage();
107         return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
108                !GlobalValue::isWeakForLinker(Linkage);
109       });
110   if (StrongDefForLinker != GVSummaryList.end())
111     return StrongDefForLinker->get();
112   // Get the first *linker visible* definition for this global in the summary
113   // list.
114   auto FirstDefForLinker = llvm::find_if(
115       GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
116         auto Linkage = Summary->linkage();
117         return !GlobalValue::isAvailableExternallyLinkage(Linkage);
118       });
119   // Extern templates can be emitted as available_externally.
120   if (FirstDefForLinker == GVSummaryList.end())
121     return nullptr;
122   return FirstDefForLinker->get();
123 }
124 
125 // Populate map of GUID to the prevailing copy for any multiply defined
126 // symbols. Currently assume first copy is prevailing, or any strong
127 // definition. Can be refined with Linker information in the future.
128 static void computePrevailingCopies(
129     const ModuleSummaryIndex &Index,
130     DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
131   auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
132     return GVSummaryList.size() > 1;
133   };
134 
135   for (auto &I : Index) {
136     if (HasMultipleCopies(I.second.SummaryList))
137       PrevailingCopy[I.first] =
138           getFirstDefinitionForLinker(I.second.SummaryList);
139   }
140 }
141 
142 static StringMap<lto::InputFile *>
143 generateModuleMap(std::vector<std::unique_ptr<lto::InputFile>> &Modules) {
144   StringMap<lto::InputFile *> ModuleMap;
145   for (auto &M : Modules) {
146     assert(ModuleMap.find(M->getName()) == ModuleMap.end() &&
147            "Expect unique Buffer Identifier");
148     ModuleMap[M->getName()] = M.get();
149   }
150   return ModuleMap;
151 }
152 
153 static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
154   if (renameModuleForThinLTO(TheModule, Index))
155     report_fatal_error("renameModuleForThinLTO failed");
156 }
157 
158 namespace {
159 class ThinLTODiagnosticInfo : public DiagnosticInfo {
160   const Twine &Msg;
161 public:
162   ThinLTODiagnosticInfo(const Twine &DiagMsg,
163                         DiagnosticSeverity Severity = DS_Error)
164       : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
165   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
166 };
167 }
168 
169 /// Verify the module and strip broken debug info.
170 static void verifyLoadedModule(Module &TheModule) {
171   bool BrokenDebugInfo = false;
172   if (verifyModule(TheModule, &dbgs(), &BrokenDebugInfo))
173     report_fatal_error("Broken module found, compilation aborted!");
174   if (BrokenDebugInfo) {
175     TheModule.getContext().diagnose(ThinLTODiagnosticInfo(
176         "Invalid debug info found, debug info will be stripped", DS_Warning));
177     StripDebugInfo(TheModule);
178   }
179 }
180 
181 static std::unique_ptr<Module> loadModuleFromInput(lto::InputFile *Input,
182                                                    LLVMContext &Context,
183                                                    bool Lazy,
184                                                    bool IsImporting) {
185   auto &Mod = Input->getSingleBitcodeModule();
186   SMDiagnostic Err;
187   Expected<std::unique_ptr<Module>> ModuleOrErr =
188       Lazy ? Mod.getLazyModule(Context,
189                                /* ShouldLazyLoadMetadata */ true, IsImporting)
190            : Mod.parseModule(Context);
191   if (!ModuleOrErr) {
192     handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
193       SMDiagnostic Err = SMDiagnostic(Mod.getModuleIdentifier(),
194                                       SourceMgr::DK_Error, EIB.message());
195       Err.print("ThinLTO", errs());
196     });
197     report_fatal_error("Can't load module, abort.");
198   }
199   if (!Lazy)
200     verifyLoadedModule(*ModuleOrErr.get());
201   return std::move(*ModuleOrErr);
202 }
203 
204 static void
205 crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
206                       StringMap<lto::InputFile*> &ModuleMap,
207                       const FunctionImporter::ImportMapTy &ImportList) {
208   auto Loader = [&](StringRef Identifier) {
209     auto &Input = ModuleMap[Identifier];
210     return loadModuleFromInput(Input, TheModule.getContext(),
211                                /*Lazy=*/true, /*IsImporting*/ true);
212   };
213 
214   FunctionImporter Importer(Index, Loader);
215   Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
216   if (!Result) {
217     handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
218       SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(),
219                                       SourceMgr::DK_Error, EIB.message());
220       Err.print("ThinLTO", errs());
221     });
222     report_fatal_error("importFunctions failed");
223   }
224   // Verify again after cross-importing.
225   verifyLoadedModule(TheModule);
226 }
227 
228 static void optimizeModule(Module &TheModule, TargetMachine &TM,
229                            unsigned OptLevel, bool Freestanding,
230                            ModuleSummaryIndex *Index) {
231   // Populate the PassManager
232   PassManagerBuilder PMB;
233   PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
234   if (Freestanding)
235     PMB.LibraryInfo->disableAllFunctions();
236   PMB.Inliner = createFunctionInliningPass();
237   // FIXME: should get it from the bitcode?
238   PMB.OptLevel = OptLevel;
239   PMB.LoopVectorize = true;
240   PMB.SLPVectorize = true;
241   // Already did this in verifyLoadedModule().
242   PMB.VerifyInput = false;
243   PMB.VerifyOutput = false;
244   PMB.ImportSummary = Index;
245 
246   legacy::PassManager PM;
247 
248   // Add the TTI (required to inform the vectorizer about register size for
249   // instance)
250   PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
251 
252   // Add optimizations
253   PMB.populateThinLTOPassManager(PM);
254 
255   PM.run(TheModule);
256 }
257 
258 static void
259 addUsedSymbolToPreservedGUID(const lto::InputFile &File,
260                              DenseSet<GlobalValue::GUID> &PreservedGUID) {
261   for (const auto &Sym : File.symbols()) {
262     if (Sym.isUsed())
263       PreservedGUID.insert(GlobalValue::getGUID(Sym.getIRName()));
264   }
265 }
266 
267 // Convert the PreservedSymbols map from "Name" based to "GUID" based.
268 static DenseSet<GlobalValue::GUID>
269 computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
270                             const Triple &TheTriple) {
271   DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
272   for (auto &Entry : PreservedSymbols) {
273     StringRef Name = Entry.first();
274     if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
275       Name = Name.drop_front();
276     GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
277   }
278   return GUIDPreservedSymbols;
279 }
280 
281 std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
282                                             TargetMachine &TM) {
283   SmallVector<char, 128> OutputBuffer;
284 
285   // CodeGen
286   {
287     raw_svector_ostream OS(OutputBuffer);
288     legacy::PassManager PM;
289 
290     // If the bitcode files contain ARC code and were compiled with optimization,
291     // the ObjCARCContractPass must be run, so do it unconditionally here.
292     PM.add(createObjCARCContractPass());
293 
294     // Setup the codegen now.
295     if (TM.addPassesToEmitFile(PM, OS, nullptr, CGFT_ObjectFile,
296                                /* DisableVerify */ true))
297       report_fatal_error("Failed to setup codegen");
298 
299     // Run codegen now. resulting binary is in OutputBuffer.
300     PM.run(TheModule);
301   }
302   return std::make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer));
303 }
304 
305 /// Manage caching for a single Module.
306 class ModuleCacheEntry {
307   SmallString<128> EntryPath;
308 
309 public:
310   // Create a cache entry. This compute a unique hash for the Module considering
311   // the current list of export/import, and offer an interface to query to
312   // access the content in the cache.
313   ModuleCacheEntry(
314       StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
315       const FunctionImporter::ImportMapTy &ImportList,
316       const FunctionImporter::ExportSetTy &ExportList,
317       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
318       const GVSummaryMapTy &DefinedGVSummaries, unsigned OptLevel,
319       bool Freestanding, const TargetMachineBuilder &TMBuilder) {
320     if (CachePath.empty())
321       return;
322 
323     if (!Index.modulePaths().count(ModuleID))
324       // The module does not have an entry, it can't have a hash at all
325       return;
326 
327     if (all_of(Index.getModuleHash(ModuleID),
328                [](uint32_t V) { return V == 0; }))
329       // No hash entry, no caching!
330       return;
331 
332     llvm::lto::Config Conf;
333     Conf.OptLevel = OptLevel;
334     Conf.Options = TMBuilder.Options;
335     Conf.CPU = TMBuilder.MCpu;
336     Conf.MAttrs.push_back(TMBuilder.MAttr);
337     Conf.RelocModel = TMBuilder.RelocModel;
338     Conf.CGOptLevel = TMBuilder.CGOptLevel;
339     Conf.Freestanding = Freestanding;
340     SmallString<40> Key;
341     computeLTOCacheKey(Key, Conf, Index, ModuleID, ImportList, ExportList,
342                        ResolvedODR, DefinedGVSummaries);
343 
344     // This choice of file name allows the cache to be pruned (see pruneCache()
345     // in include/llvm/Support/CachePruning.h).
346     sys::path::append(EntryPath, CachePath, "llvmcache-" + Key);
347   }
348 
349   // Access the path to this entry in the cache.
350   StringRef getEntryPath() { return EntryPath; }
351 
352   // Try loading the buffer for this cache entry.
353   ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
354     if (EntryPath.empty())
355       return std::error_code();
356     SmallString<64> ResultPath;
357     Expected<sys::fs::file_t> FDOrErr = sys::fs::openNativeFileForRead(
358         Twine(EntryPath), sys::fs::OF_UpdateAtime, &ResultPath);
359     if (!FDOrErr)
360       return errorToErrorCode(FDOrErr.takeError());
361     ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getOpenFile(
362         *FDOrErr, EntryPath, /*FileSize=*/-1, /*RequiresNullTerminator=*/false);
363     sys::fs::closeFile(*FDOrErr);
364     return MBOrErr;
365   }
366 
367   // Cache the Produced object file
368   void write(const MemoryBuffer &OutputBuffer) {
369     if (EntryPath.empty())
370       return;
371 
372     // Write to a temporary to avoid race condition
373     SmallString<128> TempFilename;
374     SmallString<128> CachePath(EntryPath);
375     llvm::sys::path::remove_filename(CachePath);
376     sys::path::append(TempFilename, CachePath, "Thin-%%%%%%.tmp.o");
377 
378     if (auto Err = handleErrors(
379             llvm::writeFileAtomically(TempFilename, EntryPath,
380                                       OutputBuffer.getBuffer()),
381             [](const llvm::AtomicFileWriteError &E) {
382               std::string ErrorMsgBuffer;
383               llvm::raw_string_ostream S(ErrorMsgBuffer);
384               E.log(S);
385 
386               if (E.Error ==
387                   llvm::atomic_write_error::failed_to_create_uniq_file) {
388                 errs() << "Error: " << ErrorMsgBuffer << "\n";
389                 report_fatal_error("ThinLTO: Can't get a temporary file");
390               }
391             })) {
392       // FIXME
393       consumeError(std::move(Err));
394     }
395   }
396 };
397 
398 static std::unique_ptr<MemoryBuffer>
399 ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
400                      StringMap<lto::InputFile *> &ModuleMap, TargetMachine &TM,
401                      const FunctionImporter::ImportMapTy &ImportList,
402                      const FunctionImporter::ExportSetTy &ExportList,
403                      const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
404                      const GVSummaryMapTy &DefinedGlobals,
405                      const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
406                      bool DisableCodeGen, StringRef SaveTempsDir,
407                      bool Freestanding, unsigned OptLevel, unsigned count) {
408 
409   // "Benchmark"-like optimization: single-source case
410   bool SingleModule = (ModuleMap.size() == 1);
411 
412   if (!SingleModule) {
413     promoteModule(TheModule, Index);
414 
415     // Apply summary-based prevailing-symbol resolution decisions.
416     thinLTOResolvePrevailingInModule(TheModule, DefinedGlobals);
417 
418     // Save temps: after promotion.
419     saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
420   }
421 
422   // Be friendly and don't nuke totally the module when the client didn't
423   // supply anything to preserve.
424   if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
425     // Apply summary-based internalization decisions.
426     thinLTOInternalizeModule(TheModule, DefinedGlobals);
427   }
428 
429   // Save internalized bitcode
430   saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
431 
432   if (!SingleModule) {
433     crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
434 
435     // Save temps: after cross-module import.
436     saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
437   }
438 
439   optimizeModule(TheModule, TM, OptLevel, Freestanding, &Index);
440 
441   saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
442 
443   if (DisableCodeGen) {
444     // Configured to stop before CodeGen, serialize the bitcode and return.
445     SmallVector<char, 128> OutputBuffer;
446     {
447       raw_svector_ostream OS(OutputBuffer);
448       ProfileSummaryInfo PSI(TheModule);
449       auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI);
450       WriteBitcodeToFile(TheModule, OS, true, &Index);
451     }
452     return std::make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer));
453   }
454 
455   return codegenModule(TheModule, TM);
456 }
457 
458 /// Resolve prevailing symbols. Record resolutions in the \p ResolvedODR map
459 /// for caching, and in the \p Index for application during the ThinLTO
460 /// backends. This is needed for correctness for exported symbols (ensure
461 /// at least one copy kept) and a compile-time optimization (to drop duplicate
462 /// copies when possible).
463 static void resolvePrevailingInIndex(
464     ModuleSummaryIndex &Index,
465     StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
466         &ResolvedODR,
467     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
468     const DenseMap<GlobalValue::GUID, const GlobalValueSummary *>
469         &PrevailingCopy) {
470 
471   auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
472     const auto &Prevailing = PrevailingCopy.find(GUID);
473     // Not in map means that there was only one copy, which must be prevailing.
474     if (Prevailing == PrevailingCopy.end())
475       return true;
476     return Prevailing->second == S;
477   };
478 
479   auto recordNewLinkage = [&](StringRef ModuleIdentifier,
480                               GlobalValue::GUID GUID,
481                               GlobalValue::LinkageTypes NewLinkage) {
482     ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
483   };
484 
485   thinLTOResolvePrevailingInIndex(Index, isPrevailing, recordNewLinkage,
486                                   GUIDPreservedSymbols);
487 }
488 
489 // Initialize the TargetMachine builder for a given Triple
490 static void initTMBuilder(TargetMachineBuilder &TMBuilder,
491                           const Triple &TheTriple) {
492   // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
493   // FIXME this looks pretty terrible...
494   if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
495     if (TheTriple.getArch() == llvm::Triple::x86_64)
496       TMBuilder.MCpu = "core2";
497     else if (TheTriple.getArch() == llvm::Triple::x86)
498       TMBuilder.MCpu = "yonah";
499     else if (TheTriple.getArch() == llvm::Triple::aarch64 ||
500              TheTriple.getArch() == llvm::Triple::aarch64_32)
501       TMBuilder.MCpu = "cyclone";
502   }
503   TMBuilder.TheTriple = std::move(TheTriple);
504 }
505 
506 } // end anonymous namespace
507 
508 void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
509   MemoryBufferRef Buffer(Data, Identifier);
510 
511   auto InputOrError = lto::InputFile::create(Buffer);
512   if (!InputOrError)
513     report_fatal_error("ThinLTO cannot create input file: " +
514                        toString(InputOrError.takeError()));
515 
516   auto TripleStr = (*InputOrError)->getTargetTriple();
517   Triple TheTriple(TripleStr);
518 
519   if (Modules.empty())
520     initTMBuilder(TMBuilder, Triple(TheTriple));
521   else if (TMBuilder.TheTriple != TheTriple) {
522     if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
523       report_fatal_error("ThinLTO modules with incompatible triples not "
524                          "supported");
525     initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple)));
526   }
527 
528   Modules.emplace_back(std::move(*InputOrError));
529 }
530 
531 void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
532   PreservedSymbols.insert(Name);
533 }
534 
535 void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
536   // FIXME: At the moment, we don't take advantage of this extra information,
537   // we're conservatively considering cross-references as preserved.
538   //  CrossReferencedSymbols.insert(Name);
539   PreservedSymbols.insert(Name);
540 }
541 
542 // TargetMachine factory
543 std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
544   std::string ErrMsg;
545   const Target *TheTarget =
546       TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
547   if (!TheTarget) {
548     report_fatal_error("Can't load target for this Triple: " + ErrMsg);
549   }
550 
551   // Use MAttr as the default set of features.
552   SubtargetFeatures Features(MAttr);
553   Features.getDefaultSubtargetFeatures(TheTriple);
554   std::string FeatureStr = Features.getString();
555 
556   return std::unique_ptr<TargetMachine>(
557       TheTarget->createTargetMachine(TheTriple.str(), MCpu, FeatureStr, Options,
558                                      RelocModel, None, CGOptLevel));
559 }
560 
561 /**
562  * Produce the combined summary index from all the bitcode files:
563  * "thin-link".
564  */
565 std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
566   std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
567       std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
568   uint64_t NextModuleId = 0;
569   for (auto &Mod : Modules) {
570     auto &M = Mod->getSingleBitcodeModule();
571     if (Error Err =
572             M.readSummary(*CombinedIndex, Mod->getName(), NextModuleId++)) {
573       // FIXME diagnose
574       logAllUnhandledErrors(
575           std::move(Err), errs(),
576           "error: can't create module summary index for buffer: ");
577       return nullptr;
578     }
579   }
580   return CombinedIndex;
581 }
582 
583 namespace {
584 struct IsExported {
585   const StringMap<FunctionImporter::ExportSetTy> &ExportLists;
586   const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols;
587 
588   IsExported(const StringMap<FunctionImporter::ExportSetTy> &ExportLists,
589              const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols)
590       : ExportLists(ExportLists), GUIDPreservedSymbols(GUIDPreservedSymbols) {}
591 
592   bool operator()(StringRef ModuleIdentifier, ValueInfo VI) const {
593     const auto &ExportList = ExportLists.find(ModuleIdentifier);
594     return (ExportList != ExportLists.end() && ExportList->second.count(VI)) ||
595            GUIDPreservedSymbols.count(VI.getGUID());
596   }
597 };
598 
599 struct IsPrevailing {
600   const DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy;
601   IsPrevailing(const DenseMap<GlobalValue::GUID, const GlobalValueSummary *>
602                    &PrevailingCopy)
603       : PrevailingCopy(PrevailingCopy) {}
604 
605   bool operator()(GlobalValue::GUID GUID, const GlobalValueSummary *S) const {
606     const auto &Prevailing = PrevailingCopy.find(GUID);
607     // Not in map means that there was only one copy, which must be prevailing.
608     if (Prevailing == PrevailingCopy.end())
609       return true;
610     return Prevailing->second == S;
611   };
612 };
613 } // namespace
614 
615 static void computeDeadSymbolsInIndex(
616     ModuleSummaryIndex &Index,
617     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
618   // We have no symbols resolution available. And can't do any better now in the
619   // case where the prevailing symbol is in a native object. It can be refined
620   // with linker information in the future.
621   auto isPrevailing = [&](GlobalValue::GUID G) {
622     return PrevailingType::Unknown;
623   };
624   computeDeadSymbolsWithConstProp(Index, GUIDPreservedSymbols, isPrevailing,
625                                   /* ImportEnabled = */ true);
626 }
627 
628 /**
629  * Perform promotion and renaming of exported internal functions.
630  * Index is updated to reflect linkage changes from weak resolution.
631  */
632 void ThinLTOCodeGenerator::promote(Module &TheModule, ModuleSummaryIndex &Index,
633                                    const lto::InputFile &File) {
634   auto ModuleCount = Index.modulePaths().size();
635   auto ModuleIdentifier = TheModule.getModuleIdentifier();
636 
637   // Collect for each module the list of function it defines (GUID -> Summary).
638   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
639   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
640 
641   // Convert the preserved symbols set from string to GUID
642   auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
643       PreservedSymbols, Triple(TheModule.getTargetTriple()));
644 
645   // Add used symbol to the preserved symbols.
646   addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
647 
648   // Compute "dead" symbols, we don't want to import/export these!
649   computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
650 
651   // Generate import/export list
652   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
653   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
654   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
655                            ExportLists);
656 
657   DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
658   computePrevailingCopies(Index, PrevailingCopy);
659 
660   // Resolve prevailing symbols
661   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
662   resolvePrevailingInIndex(Index, ResolvedODR, GUIDPreservedSymbols,
663                            PrevailingCopy);
664 
665   thinLTOResolvePrevailingInModule(
666       TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
667 
668   // Promote the exported values in the index, so that they are promoted
669   // in the module.
670   thinLTOInternalizeAndPromoteInIndex(
671       Index, IsExported(ExportLists, GUIDPreservedSymbols),
672       IsPrevailing(PrevailingCopy));
673 
674   promoteModule(TheModule, Index);
675 }
676 
677 /**
678  * Perform cross-module importing for the module identified by ModuleIdentifier.
679  */
680 void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
681                                              ModuleSummaryIndex &Index,
682                                              const lto::InputFile &File) {
683   auto ModuleMap = generateModuleMap(Modules);
684   auto ModuleCount = Index.modulePaths().size();
685 
686   // Collect for each module the list of function it defines (GUID -> Summary).
687   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
688   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
689 
690   // Convert the preserved symbols set from string to GUID
691   auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
692       PreservedSymbols, Triple(TheModule.getTargetTriple()));
693 
694   addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
695 
696   // Compute "dead" symbols, we don't want to import/export these!
697   computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
698 
699   // Generate import/export list
700   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
701   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
702   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
703                            ExportLists);
704   auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
705 
706   crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
707 }
708 
709 /**
710  * Compute the list of summaries needed for importing into module.
711  */
712 void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
713     Module &TheModule, ModuleSummaryIndex &Index,
714     std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex,
715     const lto::InputFile &File) {
716   auto ModuleCount = Index.modulePaths().size();
717   auto ModuleIdentifier = TheModule.getModuleIdentifier();
718 
719   // Collect for each module the list of function it defines (GUID -> Summary).
720   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
721   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
722 
723   // Convert the preserved symbols set from string to GUID
724   auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
725       PreservedSymbols, Triple(TheModule.getTargetTriple()));
726 
727   addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
728 
729   // Compute "dead" symbols, we don't want to import/export these!
730   computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
731 
732   // Generate import/export list
733   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
734   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
735   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
736                            ExportLists);
737 
738   llvm::gatherImportedSummariesForModule(
739       ModuleIdentifier, ModuleToDefinedGVSummaries,
740       ImportLists[ModuleIdentifier], ModuleToSummariesForIndex);
741 }
742 
743 /**
744  * Emit the list of files needed for importing into module.
745  */
746 void ThinLTOCodeGenerator::emitImports(Module &TheModule, StringRef OutputName,
747                                        ModuleSummaryIndex &Index,
748                                        const lto::InputFile &File) {
749   auto ModuleCount = Index.modulePaths().size();
750   auto ModuleIdentifier = TheModule.getModuleIdentifier();
751 
752   // Collect for each module the list of function it defines (GUID -> Summary).
753   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
754   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
755 
756   // Convert the preserved symbols set from string to GUID
757   auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
758       PreservedSymbols, Triple(TheModule.getTargetTriple()));
759 
760   addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
761 
762   // Compute "dead" symbols, we don't want to import/export these!
763   computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
764 
765   // Generate import/export list
766   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
767   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
768   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
769                            ExportLists);
770 
771   std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
772   llvm::gatherImportedSummariesForModule(
773       ModuleIdentifier, ModuleToDefinedGVSummaries,
774       ImportLists[ModuleIdentifier], ModuleToSummariesForIndex);
775 
776   std::error_code EC;
777   if ((EC = EmitImportsFiles(ModuleIdentifier, OutputName,
778                              ModuleToSummariesForIndex)))
779     report_fatal_error(Twine("Failed to open ") + OutputName +
780                        " to save imports lists\n");
781 }
782 
783 /**
784  * Perform internalization. Runs promote and internalization together.
785  * Index is updated to reflect linkage changes.
786  */
787 void ThinLTOCodeGenerator::internalize(Module &TheModule,
788                                        ModuleSummaryIndex &Index,
789                                        const lto::InputFile &File) {
790   initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
791   auto ModuleCount = Index.modulePaths().size();
792   auto ModuleIdentifier = TheModule.getModuleIdentifier();
793 
794   // Convert the preserved symbols set from string to GUID
795   auto GUIDPreservedSymbols =
796       computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
797 
798   addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
799 
800   // Collect for each module the list of function it defines (GUID -> Summary).
801   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
802   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
803 
804   // Compute "dead" symbols, we don't want to import/export these!
805   computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
806 
807   // Generate import/export list
808   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
809   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
810   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
811                            ExportLists);
812   auto &ExportList = ExportLists[ModuleIdentifier];
813 
814   // Be friendly and don't nuke totally the module when the client didn't
815   // supply anything to preserve.
816   if (ExportList.empty() && GUIDPreservedSymbols.empty())
817     return;
818 
819   DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
820   computePrevailingCopies(Index, PrevailingCopy);
821 
822   // Resolve prevailing symbols
823   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
824   resolvePrevailingInIndex(Index, ResolvedODR, GUIDPreservedSymbols,
825                            PrevailingCopy);
826 
827   // Promote the exported values in the index, so that they are promoted
828   // in the module.
829   thinLTOInternalizeAndPromoteInIndex(
830       Index, IsExported(ExportLists, GUIDPreservedSymbols),
831       IsPrevailing(PrevailingCopy));
832 
833   promoteModule(TheModule, Index);
834 
835   // Internalization
836   thinLTOResolvePrevailingInModule(
837       TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
838 
839   thinLTOInternalizeModule(TheModule,
840                            ModuleToDefinedGVSummaries[ModuleIdentifier]);
841 }
842 
843 /**
844  * Perform post-importing ThinLTO optimizations.
845  */
846 void ThinLTOCodeGenerator::optimize(Module &TheModule) {
847   initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
848 
849   // Optimize now
850   optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding,
851                  nullptr);
852 }
853 
854 /// Write out the generated object file, either from CacheEntryPath or from
855 /// OutputBuffer, preferring hard-link when possible.
856 /// Returns the path to the generated file in SavedObjectsDirectoryPath.
857 std::string
858 ThinLTOCodeGenerator::writeGeneratedObject(int count, StringRef CacheEntryPath,
859                                            const MemoryBuffer &OutputBuffer) {
860   auto ArchName = TMBuilder.TheTriple.getArchName();
861   SmallString<128> OutputPath(SavedObjectsDirectoryPath);
862   llvm::sys::path::append(OutputPath,
863                           Twine(count) + "." + ArchName + ".thinlto.o");
864   OutputPath.c_str(); // Ensure the string is null terminated.
865   if (sys::fs::exists(OutputPath))
866     sys::fs::remove(OutputPath);
867 
868   // We don't return a memory buffer to the linker, just a list of files.
869   if (!CacheEntryPath.empty()) {
870     // Cache is enabled, hard-link the entry (or copy if hard-link fails).
871     auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
872     if (!Err)
873       return std::string(OutputPath.str());
874     // Hard linking failed, try to copy.
875     Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
876     if (!Err)
877       return std::string(OutputPath.str());
878     // Copy failed (could be because the CacheEntry was removed from the cache
879     // in the meantime by another process), fall back and try to write down the
880     // buffer to the output.
881     errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
882            << "' to '" << OutputPath << "'\n";
883   }
884   // No cache entry, just write out the buffer.
885   std::error_code Err;
886   raw_fd_ostream OS(OutputPath, Err, sys::fs::OF_None);
887   if (Err)
888     report_fatal_error("Can't open output '" + OutputPath + "'\n");
889   OS << OutputBuffer.getBuffer();
890   return std::string(OutputPath.str());
891 }
892 
893 // Main entry point for the ThinLTO processing
894 void ThinLTOCodeGenerator::run() {
895   // Prepare the resulting object vector
896   assert(ProducedBinaries.empty() && "The generator should not be reused");
897   if (SavedObjectsDirectoryPath.empty())
898     ProducedBinaries.resize(Modules.size());
899   else {
900     sys::fs::create_directories(SavedObjectsDirectoryPath);
901     bool IsDir;
902     sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
903     if (!IsDir)
904       report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'");
905     ProducedBinaryFiles.resize(Modules.size());
906   }
907 
908   if (CodeGenOnly) {
909     // Perform only parallel codegen and return.
910     ThreadPool Pool;
911     int count = 0;
912     for (auto &Mod : Modules) {
913       Pool.async([&](int count) {
914         LLVMContext Context;
915         Context.setDiscardValueNames(LTODiscardValueNames);
916 
917         // Parse module now
918         auto TheModule = loadModuleFromInput(Mod.get(), Context, false,
919                                              /*IsImporting*/ false);
920 
921         // CodeGen
922         auto OutputBuffer = codegenModule(*TheModule, *TMBuilder.create());
923         if (SavedObjectsDirectoryPath.empty())
924           ProducedBinaries[count] = std::move(OutputBuffer);
925         else
926           ProducedBinaryFiles[count] =
927               writeGeneratedObject(count, "", *OutputBuffer);
928       }, count++);
929     }
930 
931     return;
932   }
933 
934   // Sequential linking phase
935   auto Index = linkCombinedIndex();
936 
937   // Save temps: index.
938   if (!SaveTempsDir.empty()) {
939     auto SaveTempPath = SaveTempsDir + "index.bc";
940     std::error_code EC;
941     raw_fd_ostream OS(SaveTempPath, EC, sys::fs::OF_None);
942     if (EC)
943       report_fatal_error(Twine("Failed to open ") + SaveTempPath +
944                          " to save optimized bitcode\n");
945     WriteIndexToFile(*Index, OS);
946   }
947 
948 
949   // Prepare the module map.
950   auto ModuleMap = generateModuleMap(Modules);
951   auto ModuleCount = Modules.size();
952 
953   // Collect for each module the list of function it defines (GUID -> Summary).
954   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
955   Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
956 
957   // Convert the preserved symbols set from string to GUID, this is needed for
958   // computing the caching hash and the internalization.
959   auto GUIDPreservedSymbols =
960       computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
961 
962   // Add used symbol from inputs to the preserved symbols.
963   for (const auto &M : Modules)
964     addUsedSymbolToPreservedGUID(*M, GUIDPreservedSymbols);
965 
966   // Compute "dead" symbols, we don't want to import/export these!
967   computeDeadSymbolsInIndex(*Index, GUIDPreservedSymbols);
968 
969   // Synthesize entry counts for functions in the combined index.
970   computeSyntheticCounts(*Index);
971 
972   // Currently there is no support for enabling whole program visibility via a
973   // linker option in the old LTO API, but this call allows it to be specified
974   // via the internal option. Must be done before WPD below.
975   updateVCallVisibilityInIndex(*Index,
976                                /* WholeProgramVisibilityEnabledInLTO */ false);
977 
978   // Perform index-based WPD. This will return immediately if there are
979   // no index entries in the typeIdMetadata map (e.g. if we are instead
980   // performing IR-based WPD in hybrid regular/thin LTO mode).
981   std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
982   std::set<GlobalValue::GUID> ExportedGUIDs;
983   runWholeProgramDevirtOnIndex(*Index, ExportedGUIDs, LocalWPDTargetsMap);
984   for (auto GUID : ExportedGUIDs)
985     GUIDPreservedSymbols.insert(GUID);
986 
987   // Collect the import/export lists for all modules from the call-graph in the
988   // combined index.
989   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
990   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
991   ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
992                            ExportLists);
993 
994   // We use a std::map here to be able to have a defined ordering when
995   // producing a hash for the cache entry.
996   // FIXME: we should be able to compute the caching hash for the entry based
997   // on the index, and nuke this map.
998   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
999 
1000   DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
1001   computePrevailingCopies(*Index, PrevailingCopy);
1002 
1003   // Resolve prevailing symbols, this has to be computed early because it
1004   // impacts the caching.
1005   resolvePrevailingInIndex(*Index, ResolvedODR, GUIDPreservedSymbols,
1006                            PrevailingCopy);
1007 
1008   // Use global summary-based analysis to identify symbols that can be
1009   // internalized (because they aren't exported or preserved as per callback).
1010   // Changes are made in the index, consumed in the ThinLTO backends.
1011   updateIndexWPDForExports(*Index,
1012                            IsExported(ExportLists, GUIDPreservedSymbols),
1013                            LocalWPDTargetsMap);
1014   thinLTOInternalizeAndPromoteInIndex(
1015       *Index, IsExported(ExportLists, GUIDPreservedSymbols),
1016       IsPrevailing(PrevailingCopy));
1017 
1018   // Make sure that every module has an entry in the ExportLists, ImportList,
1019   // GVSummary and ResolvedODR maps to enable threaded access to these maps
1020   // below.
1021   for (auto &Module : Modules) {
1022     auto ModuleIdentifier = Module->getName();
1023     ExportLists[ModuleIdentifier];
1024     ImportLists[ModuleIdentifier];
1025     ResolvedODR[ModuleIdentifier];
1026     ModuleToDefinedGVSummaries[ModuleIdentifier];
1027   }
1028 
1029   // Compute the ordering we will process the inputs: the rough heuristic here
1030   // is to sort them per size so that the largest module get schedule as soon as
1031   // possible. This is purely a compile-time optimization.
1032   std::vector<int> ModulesOrdering;
1033   ModulesOrdering.resize(Modules.size());
1034   std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
1035   llvm::sort(ModulesOrdering, [&](int LeftIndex, int RightIndex) {
1036     auto LSize =
1037         Modules[LeftIndex]->getSingleBitcodeModule().getBuffer().size();
1038     auto RSize =
1039         Modules[RightIndex]->getSingleBitcodeModule().getBuffer().size();
1040     return LSize > RSize;
1041   });
1042 
1043   // Parallel optimizer + codegen
1044   {
1045     ThreadPool Pool(heavyweight_hardware_concurrency(ThreadCount));
1046     for (auto IndexCount : ModulesOrdering) {
1047       auto &Mod = Modules[IndexCount];
1048       Pool.async([&](int count) {
1049         auto ModuleIdentifier = Mod->getName();
1050         auto &ExportList = ExportLists[ModuleIdentifier];
1051 
1052         auto &DefinedGVSummaries = ModuleToDefinedGVSummaries[ModuleIdentifier];
1053 
1054         // The module may be cached, this helps handling it.
1055         ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
1056                                     ImportLists[ModuleIdentifier], ExportList,
1057                                     ResolvedODR[ModuleIdentifier],
1058                                     DefinedGVSummaries, OptLevel, Freestanding,
1059                                     TMBuilder);
1060         auto CacheEntryPath = CacheEntry.getEntryPath();
1061 
1062         {
1063           auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
1064           LLVM_DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss")
1065                             << " '" << CacheEntryPath << "' for buffer "
1066                             << count << " " << ModuleIdentifier << "\n");
1067 
1068           if (ErrOrBuffer) {
1069             // Cache Hit!
1070             if (SavedObjectsDirectoryPath.empty())
1071               ProducedBinaries[count] = std::move(ErrOrBuffer.get());
1072             else
1073               ProducedBinaryFiles[count] = writeGeneratedObject(
1074                   count, CacheEntryPath, *ErrOrBuffer.get());
1075             return;
1076           }
1077         }
1078 
1079         LLVMContext Context;
1080         Context.setDiscardValueNames(LTODiscardValueNames);
1081         Context.enableDebugTypeODRUniquing();
1082         auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
1083             Context, RemarksFilename, RemarksPasses, RemarksFormat,
1084             RemarksWithHotness, count);
1085         if (!DiagFileOrErr) {
1086           errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
1087           report_fatal_error("ThinLTO: Can't get an output file for the "
1088                              "remarks");
1089         }
1090 
1091         // Parse module now
1092         auto TheModule = loadModuleFromInput(Mod.get(), Context, false,
1093                                              /*IsImporting*/ false);
1094 
1095         // Save temps: original file.
1096         saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
1097 
1098         auto &ImportList = ImportLists[ModuleIdentifier];
1099         // Run the main process now, and generates a binary
1100         auto OutputBuffer = ProcessThinLTOModule(
1101             *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
1102             ExportList, GUIDPreservedSymbols,
1103             ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
1104             DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count);
1105 
1106         // Commit to the cache (if enabled)
1107         CacheEntry.write(*OutputBuffer);
1108 
1109         if (SavedObjectsDirectoryPath.empty()) {
1110           // We need to generated a memory buffer for the linker.
1111           if (!CacheEntryPath.empty()) {
1112             // When cache is enabled, reload from the cache if possible.
1113             // Releasing the buffer from the heap and reloading it from the
1114             // cache file with mmap helps us to lower memory pressure.
1115             // The freed memory can be used for the next input file.
1116             // The final binary link will read from the VFS cache (hopefully!)
1117             // or from disk (if the memory pressure was too high).
1118             auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1119             if (auto EC = ReloadedBufferOrErr.getError()) {
1120               // On error, keep the preexisting buffer and print a diagnostic.
1121               errs() << "error: can't reload cached file '" << CacheEntryPath
1122                      << "': " << EC.message() << "\n";
1123             } else {
1124               OutputBuffer = std::move(*ReloadedBufferOrErr);
1125             }
1126           }
1127           ProducedBinaries[count] = std::move(OutputBuffer);
1128           return;
1129         }
1130         ProducedBinaryFiles[count] = writeGeneratedObject(
1131             count, CacheEntryPath, *OutputBuffer);
1132       }, IndexCount);
1133     }
1134   }
1135 
1136   pruneCache(CacheOptions.Path, CacheOptions.Policy);
1137 
1138   // If statistics were requested, print them out now.
1139   if (llvm::AreStatisticsEnabled())
1140     llvm::PrintStatistics();
1141   reportAndResetTimings();
1142 }
1143