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