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>(
382       std::move(OutputBuffer), /*RequiresNullTerminator=*/false);
383 }
384 
385 /// Manage caching for a single Module.
386 class ModuleCacheEntry {
387   SmallString<128> EntryPath;
388 
389 public:
390   // Create a cache entry. This compute a unique hash for the Module considering
391   // the current list of export/import, and offer an interface to query to
392   // access the content in the cache.
393   ModuleCacheEntry(
394       StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
395       const FunctionImporter::ImportMapTy &ImportList,
396       const FunctionImporter::ExportSetTy &ExportList,
397       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
398       const GVSummaryMapTy &DefinedGVSummaries, unsigned OptLevel,
399       bool Freestanding, const TargetMachineBuilder &TMBuilder) {
400     if (CachePath.empty())
401       return;
402 
403     if (!Index.modulePaths().count(ModuleID))
404       // The module does not have an entry, it can't have a hash at all
405       return;
406 
407     if (all_of(Index.getModuleHash(ModuleID),
408                [](uint32_t V) { return V == 0; }))
409       // No hash entry, no caching!
410       return;
411 
412     llvm::lto::Config Conf;
413     Conf.OptLevel = OptLevel;
414     Conf.Options = TMBuilder.Options;
415     Conf.CPU = TMBuilder.MCpu;
416     Conf.MAttrs.push_back(TMBuilder.MAttr);
417     Conf.RelocModel = TMBuilder.RelocModel;
418     Conf.CGOptLevel = TMBuilder.CGOptLevel;
419     Conf.Freestanding = Freestanding;
420     SmallString<40> Key;
421     computeLTOCacheKey(Key, Conf, Index, ModuleID, ImportList, ExportList,
422                        ResolvedODR, DefinedGVSummaries);
423 
424     // This choice of file name allows the cache to be pruned (see pruneCache()
425     // in include/llvm/Support/CachePruning.h).
426     sys::path::append(EntryPath, CachePath, "llvmcache-" + Key);
427   }
428 
429   // Access the path to this entry in the cache.
430   StringRef getEntryPath() { return EntryPath; }
431 
432   // Try loading the buffer for this cache entry.
433   ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
434     if (EntryPath.empty())
435       return std::error_code();
436     SmallString<64> ResultPath;
437     Expected<sys::fs::file_t> FDOrErr = sys::fs::openNativeFileForRead(
438         Twine(EntryPath), sys::fs::OF_UpdateAtime, &ResultPath);
439     if (!FDOrErr)
440       return errorToErrorCode(FDOrErr.takeError());
441     ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getOpenFile(
442         *FDOrErr, EntryPath, /*FileSize=*/-1, /*RequiresNullTerminator=*/false);
443     sys::fs::closeFile(*FDOrErr);
444     return MBOrErr;
445   }
446 
447   // Cache the Produced object file
448   void write(const MemoryBuffer &OutputBuffer) {
449     if (EntryPath.empty())
450       return;
451 
452     // Write to a temporary to avoid race condition
453     SmallString<128> TempFilename;
454     SmallString<128> CachePath(EntryPath);
455     llvm::sys::path::remove_filename(CachePath);
456     sys::path::append(TempFilename, CachePath, "Thin-%%%%%%.tmp.o");
457 
458     if (auto Err = handleErrors(
459             llvm::writeFileAtomically(TempFilename, EntryPath,
460                                       OutputBuffer.getBuffer()),
461             [](const llvm::AtomicFileWriteError &E) {
462               std::string ErrorMsgBuffer;
463               llvm::raw_string_ostream S(ErrorMsgBuffer);
464               E.log(S);
465 
466               if (E.Error ==
467                   llvm::atomic_write_error::failed_to_create_uniq_file) {
468                 errs() << "Error: " << ErrorMsgBuffer << "\n";
469                 report_fatal_error("ThinLTO: Can't get a temporary file");
470               }
471             })) {
472       // FIXME
473       consumeError(std::move(Err));
474     }
475   }
476 };
477 
478 static std::unique_ptr<MemoryBuffer>
479 ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
480                      StringMap<lto::InputFile *> &ModuleMap, TargetMachine &TM,
481                      const FunctionImporter::ImportMapTy &ImportList,
482                      const FunctionImporter::ExportSetTy &ExportList,
483                      const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
484                      const GVSummaryMapTy &DefinedGlobals,
485                      const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
486                      bool DisableCodeGen, StringRef SaveTempsDir,
487                      bool Freestanding, unsigned OptLevel, unsigned count,
488                      bool UseNewPM, bool DebugPassManager) {
489 
490   // "Benchmark"-like optimization: single-source case
491   bool SingleModule = (ModuleMap.size() == 1);
492 
493   // When linking an ELF shared object, dso_local should be dropped. We
494   // conservatively do this for -fpic.
495   bool ClearDSOLocalOnDeclarations =
496       TM.getTargetTriple().isOSBinFormatELF() &&
497       TM.getRelocationModel() != Reloc::Static &&
498       TheModule.getPIELevel() == PIELevel::Default;
499 
500   if (!SingleModule) {
501     promoteModule(TheModule, Index, ClearDSOLocalOnDeclarations);
502 
503     // Apply summary-based prevailing-symbol resolution decisions.
504     thinLTOFinalizeInModule(TheModule, DefinedGlobals, /*PropagateAttrs=*/true);
505 
506     // Save temps: after promotion.
507     saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
508   }
509 
510   // Be friendly and don't nuke totally the module when the client didn't
511   // supply anything to preserve.
512   if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
513     // Apply summary-based internalization decisions.
514     thinLTOInternalizeModule(TheModule, DefinedGlobals);
515   }
516 
517   // Save internalized bitcode
518   saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
519 
520   if (!SingleModule) {
521     crossImportIntoModule(TheModule, Index, ModuleMap, ImportList,
522                           ClearDSOLocalOnDeclarations);
523 
524     // Save temps: after cross-module import.
525     saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
526   }
527 
528   if (UseNewPM)
529     optimizeModuleNewPM(TheModule, TM, OptLevel, Freestanding, DebugPassManager,
530                         &Index);
531   else
532     optimizeModule(TheModule, TM, OptLevel, Freestanding, &Index);
533 
534   saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
535 
536   if (DisableCodeGen) {
537     // Configured to stop before CodeGen, serialize the bitcode and return.
538     SmallVector<char, 128> OutputBuffer;
539     {
540       raw_svector_ostream OS(OutputBuffer);
541       ProfileSummaryInfo PSI(TheModule);
542       auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI);
543       WriteBitcodeToFile(TheModule, OS, true, &Index);
544     }
545     return std::make_unique<SmallVectorMemoryBuffer>(
546         std::move(OutputBuffer), /*RequiresNullTerminator=*/false);
547   }
548 
549   return codegenModule(TheModule, TM);
550 }
551 
552 /// Resolve prevailing symbols. Record resolutions in the \p ResolvedODR map
553 /// for caching, and in the \p Index for application during the ThinLTO
554 /// backends. This is needed for correctness for exported symbols (ensure
555 /// at least one copy kept) and a compile-time optimization (to drop duplicate
556 /// copies when possible).
557 static void resolvePrevailingInIndex(
558     ModuleSummaryIndex &Index,
559     StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
560         &ResolvedODR,
561     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
562     const DenseMap<GlobalValue::GUID, const GlobalValueSummary *>
563         &PrevailingCopy) {
564 
565   auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
566     const auto &Prevailing = PrevailingCopy.find(GUID);
567     // Not in map means that there was only one copy, which must be prevailing.
568     if (Prevailing == PrevailingCopy.end())
569       return true;
570     return Prevailing->second == S;
571   };
572 
573   auto recordNewLinkage = [&](StringRef ModuleIdentifier,
574                               GlobalValue::GUID GUID,
575                               GlobalValue::LinkageTypes NewLinkage) {
576     ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
577   };
578 
579   // TODO Conf.VisibilityScheme can be lto::Config::ELF for ELF.
580   lto::Config Conf;
581   thinLTOResolvePrevailingInIndex(Conf, Index, isPrevailing, recordNewLinkage,
582                                   GUIDPreservedSymbols);
583 }
584 
585 // Initialize the TargetMachine builder for a given Triple
586 static void initTMBuilder(TargetMachineBuilder &TMBuilder,
587                           const Triple &TheTriple) {
588   // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
589   // FIXME this looks pretty terrible...
590   if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
591     if (TheTriple.getArch() == llvm::Triple::x86_64)
592       TMBuilder.MCpu = "core2";
593     else if (TheTriple.getArch() == llvm::Triple::x86)
594       TMBuilder.MCpu = "yonah";
595     else if (TheTriple.getArch() == llvm::Triple::aarch64 ||
596              TheTriple.getArch() == llvm::Triple::aarch64_32)
597       TMBuilder.MCpu = "cyclone";
598   }
599   TMBuilder.TheTriple = std::move(TheTriple);
600 }
601 
602 } // end anonymous namespace
603 
604 void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
605   MemoryBufferRef Buffer(Data, Identifier);
606 
607   auto InputOrError = lto::InputFile::create(Buffer);
608   if (!InputOrError)
609     report_fatal_error(Twine("ThinLTO cannot create input file: ") +
610                        toString(InputOrError.takeError()));
611 
612   auto TripleStr = (*InputOrError)->getTargetTriple();
613   Triple TheTriple(TripleStr);
614 
615   if (Modules.empty())
616     initTMBuilder(TMBuilder, Triple(TheTriple));
617   else if (TMBuilder.TheTriple != TheTriple) {
618     if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
619       report_fatal_error("ThinLTO modules with incompatible triples not "
620                          "supported");
621     initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple)));
622   }
623 
624   Modules.emplace_back(std::move(*InputOrError));
625 }
626 
627 void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
628   PreservedSymbols.insert(Name);
629 }
630 
631 void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
632   // FIXME: At the moment, we don't take advantage of this extra information,
633   // we're conservatively considering cross-references as preserved.
634   //  CrossReferencedSymbols.insert(Name);
635   PreservedSymbols.insert(Name);
636 }
637 
638 // TargetMachine factory
639 std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
640   std::string ErrMsg;
641   const Target *TheTarget =
642       TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
643   if (!TheTarget) {
644     report_fatal_error(Twine("Can't load target for this Triple: ") + ErrMsg);
645   }
646 
647   // Use MAttr as the default set of features.
648   SubtargetFeatures Features(MAttr);
649   Features.getDefaultSubtargetFeatures(TheTriple);
650   std::string FeatureStr = Features.getString();
651 
652   std::unique_ptr<TargetMachine> TM(
653       TheTarget->createTargetMachine(TheTriple.str(), MCpu, FeatureStr, Options,
654                                      RelocModel, None, CGOptLevel));
655   assert(TM && "Cannot create target machine");
656 
657   return TM;
658 }
659 
660 /**
661  * Produce the combined summary index from all the bitcode files:
662  * "thin-link".
663  */
664 std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
665   std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
666       std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
667   uint64_t NextModuleId = 0;
668   for (auto &Mod : Modules) {
669     auto &M = Mod->getSingleBitcodeModule();
670     if (Error Err =
671             M.readSummary(*CombinedIndex, Mod->getName(), NextModuleId++)) {
672       // FIXME diagnose
673       logAllUnhandledErrors(
674           std::move(Err), errs(),
675           "error: can't create module summary index for buffer: ");
676       return nullptr;
677     }
678   }
679   return CombinedIndex;
680 }
681 
682 namespace {
683 struct IsExported {
684   const StringMap<FunctionImporter::ExportSetTy> &ExportLists;
685   const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols;
686 
687   IsExported(const StringMap<FunctionImporter::ExportSetTy> &ExportLists,
688              const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols)
689       : ExportLists(ExportLists), GUIDPreservedSymbols(GUIDPreservedSymbols) {}
690 
691   bool operator()(StringRef ModuleIdentifier, ValueInfo VI) const {
692     const auto &ExportList = ExportLists.find(ModuleIdentifier);
693     return (ExportList != ExportLists.end() && ExportList->second.count(VI)) ||
694            GUIDPreservedSymbols.count(VI.getGUID());
695   }
696 };
697 
698 struct IsPrevailing {
699   const DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy;
700   IsPrevailing(const DenseMap<GlobalValue::GUID, const GlobalValueSummary *>
701                    &PrevailingCopy)
702       : PrevailingCopy(PrevailingCopy) {}
703 
704   bool operator()(GlobalValue::GUID GUID, const GlobalValueSummary *S) const {
705     const auto &Prevailing = PrevailingCopy.find(GUID);
706     // Not in map means that there was only one copy, which must be prevailing.
707     if (Prevailing == PrevailingCopy.end())
708       return true;
709     return Prevailing->second == S;
710   };
711 };
712 } // namespace
713 
714 static void computeDeadSymbolsInIndex(
715     ModuleSummaryIndex &Index,
716     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
717   // We have no symbols resolution available. And can't do any better now in the
718   // case where the prevailing symbol is in a native object. It can be refined
719   // with linker information in the future.
720   auto isPrevailing = [&](GlobalValue::GUID G) {
721     return PrevailingType::Unknown;
722   };
723   computeDeadSymbolsWithConstProp(Index, GUIDPreservedSymbols, isPrevailing,
724                                   /* ImportEnabled = */ true);
725 }
726 
727 /**
728  * Perform promotion and renaming of exported internal functions.
729  * Index is updated to reflect linkage changes from weak resolution.
730  */
731 void ThinLTOCodeGenerator::promote(Module &TheModule, ModuleSummaryIndex &Index,
732                                    const lto::InputFile &File) {
733   auto ModuleCount = Index.modulePaths().size();
734   auto ModuleIdentifier = TheModule.getModuleIdentifier();
735 
736   // Collect for each module the list of function it defines (GUID -> Summary).
737   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
738   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
739 
740   // Convert the preserved symbols set from string to GUID
741   auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
742       File, PreservedSymbols, Triple(TheModule.getTargetTriple()));
743 
744   // Add used symbol to the preserved symbols.
745   addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
746 
747   // Compute "dead" symbols, we don't want to import/export these!
748   computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
749 
750   // Generate import/export list
751   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
752   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
753   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
754                            ExportLists);
755 
756   DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
757   computePrevailingCopies(Index, PrevailingCopy);
758 
759   // Resolve prevailing symbols
760   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
761   resolvePrevailingInIndex(Index, ResolvedODR, GUIDPreservedSymbols,
762                            PrevailingCopy);
763 
764   thinLTOFinalizeInModule(TheModule,
765                           ModuleToDefinedGVSummaries[ModuleIdentifier],
766                           /*PropagateAttrs=*/false);
767 
768   // Promote the exported values in the index, so that they are promoted
769   // in the module.
770   thinLTOInternalizeAndPromoteInIndex(
771       Index, IsExported(ExportLists, GUIDPreservedSymbols),
772       IsPrevailing(PrevailingCopy));
773 
774   // FIXME Set ClearDSOLocalOnDeclarations.
775   promoteModule(TheModule, Index, /*ClearDSOLocalOnDeclarations=*/false);
776 }
777 
778 /**
779  * Perform cross-module importing for the module identified by ModuleIdentifier.
780  */
781 void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
782                                              ModuleSummaryIndex &Index,
783                                              const lto::InputFile &File) {
784   auto ModuleMap = generateModuleMap(Modules);
785   auto ModuleCount = Index.modulePaths().size();
786 
787   // Collect for each module the list of function it defines (GUID -> Summary).
788   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
789   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
790 
791   // Convert the preserved symbols set from string to GUID
792   auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
793       File, PreservedSymbols, Triple(TheModule.getTargetTriple()));
794 
795   addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
796 
797   // Compute "dead" symbols, we don't want to import/export these!
798   computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
799 
800   // Generate import/export list
801   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
802   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
803   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
804                            ExportLists);
805   auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
806 
807   // FIXME Set ClearDSOLocalOnDeclarations.
808   crossImportIntoModule(TheModule, Index, ModuleMap, ImportList,
809                         /*ClearDSOLocalOnDeclarations=*/false);
810 }
811 
812 /**
813  * Compute the list of summaries needed for importing into module.
814  */
815 void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
816     Module &TheModule, ModuleSummaryIndex &Index,
817     std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex,
818     const lto::InputFile &File) {
819   auto ModuleCount = Index.modulePaths().size();
820   auto ModuleIdentifier = TheModule.getModuleIdentifier();
821 
822   // Collect for each module the list of function it defines (GUID -> Summary).
823   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
824   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
825 
826   // Convert the preserved symbols set from string to GUID
827   auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
828       File, PreservedSymbols, Triple(TheModule.getTargetTriple()));
829 
830   addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
831 
832   // Compute "dead" symbols, we don't want to import/export these!
833   computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
834 
835   // Generate import/export list
836   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
837   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
838   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
839                            ExportLists);
840 
841   llvm::gatherImportedSummariesForModule(
842       ModuleIdentifier, ModuleToDefinedGVSummaries,
843       ImportLists[ModuleIdentifier], ModuleToSummariesForIndex);
844 }
845 
846 /**
847  * Emit the list of files needed for importing into module.
848  */
849 void ThinLTOCodeGenerator::emitImports(Module &TheModule, StringRef OutputName,
850                                        ModuleSummaryIndex &Index,
851                                        const lto::InputFile &File) {
852   auto ModuleCount = Index.modulePaths().size();
853   auto ModuleIdentifier = TheModule.getModuleIdentifier();
854 
855   // Collect for each module the list of function it defines (GUID -> Summary).
856   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
857   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
858 
859   // Convert the preserved symbols set from string to GUID
860   auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
861       File, PreservedSymbols, Triple(TheModule.getTargetTriple()));
862 
863   addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
864 
865   // Compute "dead" symbols, we don't want to import/export these!
866   computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
867 
868   // Generate import/export list
869   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
870   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
871   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
872                            ExportLists);
873 
874   std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
875   llvm::gatherImportedSummariesForModule(
876       ModuleIdentifier, ModuleToDefinedGVSummaries,
877       ImportLists[ModuleIdentifier], ModuleToSummariesForIndex);
878 
879   std::error_code EC;
880   if ((EC = EmitImportsFiles(ModuleIdentifier, OutputName,
881                              ModuleToSummariesForIndex)))
882     report_fatal_error(Twine("Failed to open ") + OutputName +
883                        " to save imports lists\n");
884 }
885 
886 /**
887  * Perform internalization. Runs promote and internalization together.
888  * Index is updated to reflect linkage changes.
889  */
890 void ThinLTOCodeGenerator::internalize(Module &TheModule,
891                                        ModuleSummaryIndex &Index,
892                                        const lto::InputFile &File) {
893   initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
894   auto ModuleCount = Index.modulePaths().size();
895   auto ModuleIdentifier = TheModule.getModuleIdentifier();
896 
897   // Convert the preserved symbols set from string to GUID
898   auto GUIDPreservedSymbols =
899       computeGUIDPreservedSymbols(File, PreservedSymbols, TMBuilder.TheTriple);
900 
901   addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
902 
903   // Collect for each module the list of function it defines (GUID -> Summary).
904   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
905   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
906 
907   // Compute "dead" symbols, we don't want to import/export these!
908   computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
909 
910   // Generate import/export list
911   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
912   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
913   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
914                            ExportLists);
915   auto &ExportList = ExportLists[ModuleIdentifier];
916 
917   // Be friendly and don't nuke totally the module when the client didn't
918   // supply anything to preserve.
919   if (ExportList.empty() && GUIDPreservedSymbols.empty())
920     return;
921 
922   DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
923   computePrevailingCopies(Index, PrevailingCopy);
924 
925   // Resolve prevailing symbols
926   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
927   resolvePrevailingInIndex(Index, ResolvedODR, GUIDPreservedSymbols,
928                            PrevailingCopy);
929 
930   // Promote the exported values in the index, so that they are promoted
931   // in the module.
932   thinLTOInternalizeAndPromoteInIndex(
933       Index, IsExported(ExportLists, GUIDPreservedSymbols),
934       IsPrevailing(PrevailingCopy));
935 
936   // FIXME Set ClearDSOLocalOnDeclarations.
937   promoteModule(TheModule, Index, /*ClearDSOLocalOnDeclarations=*/false);
938 
939   // Internalization
940   thinLTOFinalizeInModule(TheModule,
941                           ModuleToDefinedGVSummaries[ModuleIdentifier],
942                           /*PropagateAttrs=*/false);
943 
944   thinLTOInternalizeModule(TheModule,
945                            ModuleToDefinedGVSummaries[ModuleIdentifier]);
946 }
947 
948 /**
949  * Perform post-importing ThinLTO optimizations.
950  */
951 void ThinLTOCodeGenerator::optimize(Module &TheModule) {
952   initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
953 
954   // Optimize now
955   optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding,
956                  nullptr);
957 }
958 
959 /// Write out the generated object file, either from CacheEntryPath or from
960 /// OutputBuffer, preferring hard-link when possible.
961 /// Returns the path to the generated file in SavedObjectsDirectoryPath.
962 std::string
963 ThinLTOCodeGenerator::writeGeneratedObject(int count, StringRef CacheEntryPath,
964                                            const MemoryBuffer &OutputBuffer) {
965   auto ArchName = TMBuilder.TheTriple.getArchName();
966   SmallString<128> OutputPath(SavedObjectsDirectoryPath);
967   llvm::sys::path::append(OutputPath,
968                           Twine(count) + "." + ArchName + ".thinlto.o");
969   OutputPath.c_str(); // Ensure the string is null terminated.
970   if (sys::fs::exists(OutputPath))
971     sys::fs::remove(OutputPath);
972 
973   // We don't return a memory buffer to the linker, just a list of files.
974   if (!CacheEntryPath.empty()) {
975     // Cache is enabled, hard-link the entry (or copy if hard-link fails).
976     auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
977     if (!Err)
978       return std::string(OutputPath.str());
979     // Hard linking failed, try to copy.
980     Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
981     if (!Err)
982       return std::string(OutputPath.str());
983     // Copy failed (could be because the CacheEntry was removed from the cache
984     // in the meantime by another process), fall back and try to write down the
985     // buffer to the output.
986     errs() << "remark: can't link or copy from cached entry '" << CacheEntryPath
987            << "' to '" << OutputPath << "'\n";
988   }
989   // No cache entry, just write out the buffer.
990   std::error_code Err;
991   raw_fd_ostream OS(OutputPath, Err, sys::fs::OF_None);
992   if (Err)
993     report_fatal_error(Twine("Can't open output '") + OutputPath + "'\n");
994   OS << OutputBuffer.getBuffer();
995   return std::string(OutputPath.str());
996 }
997 
998 // Main entry point for the ThinLTO processing
999 void ThinLTOCodeGenerator::run() {
1000   timeTraceProfilerBegin("ThinLink", StringRef(""));
1001   auto TimeTraceScopeExit = llvm::make_scope_exit([]() {
1002     if (llvm::timeTraceProfilerEnabled())
1003       llvm::timeTraceProfilerEnd();
1004   });
1005   // Prepare the resulting object vector
1006   assert(ProducedBinaries.empty() && "The generator should not be reused");
1007   if (SavedObjectsDirectoryPath.empty())
1008     ProducedBinaries.resize(Modules.size());
1009   else {
1010     sys::fs::create_directories(SavedObjectsDirectoryPath);
1011     bool IsDir;
1012     sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
1013     if (!IsDir)
1014       report_fatal_error(Twine("Unexistent dir: '") + SavedObjectsDirectoryPath + "'");
1015     ProducedBinaryFiles.resize(Modules.size());
1016   }
1017 
1018   if (CodeGenOnly) {
1019     // Perform only parallel codegen and return.
1020     ThreadPool Pool;
1021     int count = 0;
1022     for (auto &Mod : Modules) {
1023       Pool.async([&](int count) {
1024         LLVMContext Context;
1025         Context.setDiscardValueNames(LTODiscardValueNames);
1026 
1027         // Parse module now
1028         auto TheModule = loadModuleFromInput(Mod.get(), Context, false,
1029                                              /*IsImporting*/ false);
1030 
1031         // CodeGen
1032         auto OutputBuffer = codegenModule(*TheModule, *TMBuilder.create());
1033         if (SavedObjectsDirectoryPath.empty())
1034           ProducedBinaries[count] = std::move(OutputBuffer);
1035         else
1036           ProducedBinaryFiles[count] =
1037               writeGeneratedObject(count, "", *OutputBuffer);
1038       }, count++);
1039     }
1040 
1041     return;
1042   }
1043 
1044   // Sequential linking phase
1045   auto Index = linkCombinedIndex();
1046 
1047   // Save temps: index.
1048   if (!SaveTempsDir.empty()) {
1049     auto SaveTempPath = SaveTempsDir + "index.bc";
1050     std::error_code EC;
1051     raw_fd_ostream OS(SaveTempPath, EC, sys::fs::OF_None);
1052     if (EC)
1053       report_fatal_error(Twine("Failed to open ") + SaveTempPath +
1054                          " to save optimized bitcode\n");
1055     writeIndexToFile(*Index, OS);
1056   }
1057 
1058 
1059   // Prepare the module map.
1060   auto ModuleMap = generateModuleMap(Modules);
1061   auto ModuleCount = Modules.size();
1062 
1063   // Collect for each module the list of function it defines (GUID -> Summary).
1064   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
1065   Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1066 
1067   // Convert the preserved symbols set from string to GUID, this is needed for
1068   // computing the caching hash and the internalization.
1069   DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
1070   for (const auto &M : Modules)
1071     computeGUIDPreservedSymbols(*M, PreservedSymbols, TMBuilder.TheTriple,
1072                                 GUIDPreservedSymbols);
1073 
1074   // Add used symbol from inputs to the preserved symbols.
1075   for (const auto &M : Modules)
1076     addUsedSymbolToPreservedGUID(*M, GUIDPreservedSymbols);
1077 
1078   // Compute "dead" symbols, we don't want to import/export these!
1079   computeDeadSymbolsInIndex(*Index, GUIDPreservedSymbols);
1080 
1081   // Synthesize entry counts for functions in the combined index.
1082   computeSyntheticCounts(*Index);
1083 
1084   // Currently there is no support for enabling whole program visibility via a
1085   // linker option in the old LTO API, but this call allows it to be specified
1086   // via the internal option. Must be done before WPD below.
1087   updateVCallVisibilityInIndex(*Index,
1088                                /* WholeProgramVisibilityEnabledInLTO */ false,
1089                                // FIXME: This needs linker information via a
1090                                // TBD new interface.
1091                                /* DynamicExportSymbols */ {});
1092 
1093   // Perform index-based WPD. This will return immediately if there are
1094   // no index entries in the typeIdMetadata map (e.g. if we are instead
1095   // performing IR-based WPD in hybrid regular/thin LTO mode).
1096   std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
1097   std::set<GlobalValue::GUID> ExportedGUIDs;
1098   runWholeProgramDevirtOnIndex(*Index, ExportedGUIDs, LocalWPDTargetsMap);
1099   for (auto GUID : ExportedGUIDs)
1100     GUIDPreservedSymbols.insert(GUID);
1101 
1102   // Collect the import/export lists for all modules from the call-graph in the
1103   // combined index.
1104   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
1105   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
1106   ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
1107                            ExportLists);
1108 
1109   // We use a std::map here to be able to have a defined ordering when
1110   // producing a hash for the cache entry.
1111   // FIXME: we should be able to compute the caching hash for the entry based
1112   // on the index, and nuke this map.
1113   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
1114 
1115   DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
1116   computePrevailingCopies(*Index, PrevailingCopy);
1117 
1118   // Resolve prevailing symbols, this has to be computed early because it
1119   // impacts the caching.
1120   resolvePrevailingInIndex(*Index, ResolvedODR, GUIDPreservedSymbols,
1121                            PrevailingCopy);
1122 
1123   // Use global summary-based analysis to identify symbols that can be
1124   // internalized (because they aren't exported or preserved as per callback).
1125   // Changes are made in the index, consumed in the ThinLTO backends.
1126   updateIndexWPDForExports(*Index,
1127                            IsExported(ExportLists, GUIDPreservedSymbols),
1128                            LocalWPDTargetsMap);
1129   thinLTOInternalizeAndPromoteInIndex(
1130       *Index, IsExported(ExportLists, GUIDPreservedSymbols),
1131       IsPrevailing(PrevailingCopy));
1132 
1133   thinLTOPropagateFunctionAttrs(*Index, IsPrevailing(PrevailingCopy));
1134 
1135   // Make sure that every module has an entry in the ExportLists, ImportList,
1136   // GVSummary and ResolvedODR maps to enable threaded access to these maps
1137   // below.
1138   for (auto &Module : Modules) {
1139     auto ModuleIdentifier = Module->getName();
1140     ExportLists[ModuleIdentifier];
1141     ImportLists[ModuleIdentifier];
1142     ResolvedODR[ModuleIdentifier];
1143     ModuleToDefinedGVSummaries[ModuleIdentifier];
1144   }
1145 
1146   std::vector<BitcodeModule *> ModulesVec;
1147   ModulesVec.reserve(Modules.size());
1148   for (auto &Mod : Modules)
1149     ModulesVec.push_back(&Mod->getSingleBitcodeModule());
1150   std::vector<int> ModulesOrdering = lto::generateModulesOrdering(ModulesVec);
1151 
1152   if (llvm::timeTraceProfilerEnabled())
1153     llvm::timeTraceProfilerEnd();
1154 
1155   TimeTraceScopeExit.release();
1156 
1157   // Parallel optimizer + codegen
1158   {
1159     ThreadPool Pool(heavyweight_hardware_concurrency(ThreadCount));
1160     for (auto IndexCount : ModulesOrdering) {
1161       auto &Mod = Modules[IndexCount];
1162       Pool.async([&](int count) {
1163         auto ModuleIdentifier = Mod->getName();
1164         auto &ExportList = ExportLists[ModuleIdentifier];
1165 
1166         auto &DefinedGVSummaries = ModuleToDefinedGVSummaries[ModuleIdentifier];
1167 
1168         // The module may be cached, this helps handling it.
1169         ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
1170                                     ImportLists[ModuleIdentifier], ExportList,
1171                                     ResolvedODR[ModuleIdentifier],
1172                                     DefinedGVSummaries, OptLevel, Freestanding,
1173                                     TMBuilder);
1174         auto CacheEntryPath = CacheEntry.getEntryPath();
1175 
1176         {
1177           auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
1178           LLVM_DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss")
1179                             << " '" << CacheEntryPath << "' for buffer "
1180                             << count << " " << ModuleIdentifier << "\n");
1181 
1182           if (ErrOrBuffer) {
1183             // Cache Hit!
1184             if (SavedObjectsDirectoryPath.empty())
1185               ProducedBinaries[count] = std::move(ErrOrBuffer.get());
1186             else
1187               ProducedBinaryFiles[count] = writeGeneratedObject(
1188                   count, CacheEntryPath, *ErrOrBuffer.get());
1189             return;
1190           }
1191         }
1192 
1193         LLVMContext Context;
1194         Context.setDiscardValueNames(LTODiscardValueNames);
1195         Context.enableDebugTypeODRUniquing();
1196         auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
1197             Context, RemarksFilename, RemarksPasses, RemarksFormat,
1198             RemarksWithHotness, RemarksHotnessThreshold, count);
1199         if (!DiagFileOrErr) {
1200           errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
1201           report_fatal_error("ThinLTO: Can't get an output file for the "
1202                              "remarks");
1203         }
1204 
1205         // Parse module now
1206         auto TheModule = loadModuleFromInput(Mod.get(), Context, false,
1207                                              /*IsImporting*/ false);
1208 
1209         // Save temps: original file.
1210         saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
1211 
1212         auto &ImportList = ImportLists[ModuleIdentifier];
1213         // Run the main process now, and generates a binary
1214         auto OutputBuffer = ProcessThinLTOModule(
1215             *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
1216             ExportList, GUIDPreservedSymbols,
1217             ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
1218             DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count,
1219             UseNewPM, DebugPassManager);
1220 
1221         // Commit to the cache (if enabled)
1222         CacheEntry.write(*OutputBuffer);
1223 
1224         if (SavedObjectsDirectoryPath.empty()) {
1225           // We need to generated a memory buffer for the linker.
1226           if (!CacheEntryPath.empty()) {
1227             // When cache is enabled, reload from the cache if possible.
1228             // Releasing the buffer from the heap and reloading it from the
1229             // cache file with mmap helps us to lower memory pressure.
1230             // The freed memory can be used for the next input file.
1231             // The final binary link will read from the VFS cache (hopefully!)
1232             // or from disk (if the memory pressure was too high).
1233             auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1234             if (auto EC = ReloadedBufferOrErr.getError()) {
1235               // On error, keep the preexisting buffer and print a diagnostic.
1236               errs() << "remark: can't reload cached file '" << CacheEntryPath
1237                      << "': " << EC.message() << "\n";
1238             } else {
1239               OutputBuffer = std::move(*ReloadedBufferOrErr);
1240             }
1241           }
1242           ProducedBinaries[count] = std::move(OutputBuffer);
1243           return;
1244         }
1245         ProducedBinaryFiles[count] = writeGeneratedObject(
1246             count, CacheEntryPath, *OutputBuffer);
1247       }, IndexCount);
1248     }
1249   }
1250 
1251   pruneCache(CacheOptions.Path, CacheOptions.Policy);
1252 
1253   // If statistics were requested, print them out now.
1254   if (llvm::AreStatisticsEnabled())
1255     llvm::PrintStatistics();
1256   reportAndResetTimings();
1257 }
1258