xref: /freebsd/contrib/llvm-project/llvm/lib/LTO/LTO.cpp (revision d5b0e70f7e04d971691517ce1304d86a1e367e2e)
1 //===-LTO.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 functions and classes used to support LTO.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/LTO/LTO.h"
14 #include "llvm/ADT/ScopeExit.h"
15 #include "llvm/ADT/SmallSet.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
19 #include "llvm/Analysis/StackSafetyAnalysis.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/Bitcode/BitcodeReader.h"
23 #include "llvm/Bitcode/BitcodeWriter.h"
24 #include "llvm/CodeGen/Analysis.h"
25 #include "llvm/Config/llvm-config.h"
26 #include "llvm/IR/AutoUpgrade.h"
27 #include "llvm/IR/DiagnosticPrinter.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/LLVMRemarkStreamer.h"
30 #include "llvm/IR/LegacyPassManager.h"
31 #include "llvm/IR/Mangler.h"
32 #include "llvm/IR/Metadata.h"
33 #include "llvm/LTO/LTOBackend.h"
34 #include "llvm/LTO/SummaryBasedOptimizations.h"
35 #include "llvm/Linker/IRMover.h"
36 #include "llvm/MC/TargetRegistry.h"
37 #include "llvm/Object/IRObjectFile.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Error.h"
40 #include "llvm/Support/FileSystem.h"
41 #include "llvm/Support/ManagedStatic.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/Path.h"
44 #include "llvm/Support/SHA1.h"
45 #include "llvm/Support/SourceMgr.h"
46 #include "llvm/Support/ThreadPool.h"
47 #include "llvm/Support/Threading.h"
48 #include "llvm/Support/TimeProfiler.h"
49 #include "llvm/Support/ToolOutputFile.h"
50 #include "llvm/Support/VCSRevision.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include "llvm/Target/TargetMachine.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "llvm/Transforms/IPO.h"
55 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
56 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
57 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
58 #include "llvm/Transforms/Utils/SplitModule.h"
59 
60 #include <set>
61 
62 using namespace llvm;
63 using namespace lto;
64 using namespace object;
65 
66 #define DEBUG_TYPE "lto"
67 
68 static cl::opt<bool>
69     DumpThinCGSCCs("dump-thin-cg-sccs", cl::init(false), cl::Hidden,
70                    cl::desc("Dump the SCCs in the ThinLTO index's callgraph"));
71 
72 /// Enable global value internalization in LTO.
73 cl::opt<bool> EnableLTOInternalization(
74     "enable-lto-internalization", cl::init(true), cl::Hidden,
75     cl::desc("Enable global value internalization in LTO"));
76 
77 // Computes a unique hash for the Module considering the current list of
78 // export/import and other global analysis results.
79 // The hash is produced in \p Key.
80 void llvm::computeLTOCacheKey(
81     SmallString<40> &Key, const Config &Conf, const ModuleSummaryIndex &Index,
82     StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList,
83     const FunctionImporter::ExportSetTy &ExportList,
84     const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
85     const GVSummaryMapTy &DefinedGlobals,
86     const std::set<GlobalValue::GUID> &CfiFunctionDefs,
87     const std::set<GlobalValue::GUID> &CfiFunctionDecls) {
88   // Compute the unique hash for this entry.
89   // This is based on the current compiler version, the module itself, the
90   // export list, the hash for every single module in the import list, the
91   // list of ResolvedODR for the module, and the list of preserved symbols.
92   SHA1 Hasher;
93 
94   // Start with the compiler revision
95   Hasher.update(LLVM_VERSION_STRING);
96 #ifdef LLVM_REVISION
97   Hasher.update(LLVM_REVISION);
98 #endif
99 
100   // Include the parts of the LTO configuration that affect code generation.
101   auto AddString = [&](StringRef Str) {
102     Hasher.update(Str);
103     Hasher.update(ArrayRef<uint8_t>{0});
104   };
105   auto AddUnsigned = [&](unsigned I) {
106     uint8_t Data[4];
107     support::endian::write32le(Data, I);
108     Hasher.update(ArrayRef<uint8_t>{Data, 4});
109   };
110   auto AddUint64 = [&](uint64_t I) {
111     uint8_t Data[8];
112     support::endian::write64le(Data, I);
113     Hasher.update(ArrayRef<uint8_t>{Data, 8});
114   };
115   AddString(Conf.CPU);
116   // FIXME: Hash more of Options. For now all clients initialize Options from
117   // command-line flags (which is unsupported in production), but may set
118   // RelaxELFRelocations. The clang driver can also pass FunctionSections,
119   // DataSections and DebuggerTuning via command line flags.
120   AddUnsigned(Conf.Options.RelaxELFRelocations);
121   AddUnsigned(Conf.Options.FunctionSections);
122   AddUnsigned(Conf.Options.DataSections);
123   AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
124   for (auto &A : Conf.MAttrs)
125     AddString(A);
126   if (Conf.RelocModel)
127     AddUnsigned(*Conf.RelocModel);
128   else
129     AddUnsigned(-1);
130   if (Conf.CodeModel)
131     AddUnsigned(*Conf.CodeModel);
132   else
133     AddUnsigned(-1);
134   AddUnsigned(Conf.CGOptLevel);
135   AddUnsigned(Conf.CGFileType);
136   AddUnsigned(Conf.OptLevel);
137   AddUnsigned(Conf.UseNewPM);
138   AddUnsigned(Conf.Freestanding);
139   AddString(Conf.OptPipeline);
140   AddString(Conf.AAPipeline);
141   AddString(Conf.OverrideTriple);
142   AddString(Conf.DefaultTriple);
143   AddString(Conf.DwoDir);
144 
145   // Include the hash for the current module
146   auto ModHash = Index.getModuleHash(ModuleID);
147   Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
148 
149   std::vector<uint64_t> ExportsGUID;
150   ExportsGUID.reserve(ExportList.size());
151   for (const auto &VI : ExportList) {
152     auto GUID = VI.getGUID();
153     ExportsGUID.push_back(GUID);
154   }
155 
156   // Sort the export list elements GUIDs.
157   llvm::sort(ExportsGUID);
158   for (uint64_t GUID : ExportsGUID) {
159     // The export list can impact the internalization, be conservative here
160     Hasher.update(ArrayRef<uint8_t>((uint8_t *)&GUID, sizeof(GUID)));
161   }
162 
163   // Include the hash for every module we import functions from. The set of
164   // imported symbols for each module may affect code generation and is
165   // sensitive to link order, so include that as well.
166   using ImportMapIteratorTy = FunctionImporter::ImportMapTy::const_iterator;
167   std::vector<ImportMapIteratorTy> ImportModulesVector;
168   ImportModulesVector.reserve(ImportList.size());
169 
170   for (ImportMapIteratorTy It = ImportList.begin(); It != ImportList.end();
171        ++It) {
172     ImportModulesVector.push_back(It);
173   }
174   llvm::sort(ImportModulesVector,
175              [](const ImportMapIteratorTy &Lhs, const ImportMapIteratorTy &Rhs)
176                  -> bool { return Lhs->getKey() < Rhs->getKey(); });
177   for (const ImportMapIteratorTy &EntryIt : ImportModulesVector) {
178     auto ModHash = Index.getModuleHash(EntryIt->first());
179     Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
180 
181     AddUint64(EntryIt->second.size());
182     for (auto &Fn : EntryIt->second)
183       AddUint64(Fn);
184   }
185 
186   // Include the hash for the resolved ODR.
187   for (auto &Entry : ResolvedODR) {
188     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
189                                     sizeof(GlobalValue::GUID)));
190     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
191                                     sizeof(GlobalValue::LinkageTypes)));
192   }
193 
194   // Members of CfiFunctionDefs and CfiFunctionDecls that are referenced or
195   // defined in this module.
196   std::set<GlobalValue::GUID> UsedCfiDefs;
197   std::set<GlobalValue::GUID> UsedCfiDecls;
198 
199   // Typeids used in this module.
200   std::set<GlobalValue::GUID> UsedTypeIds;
201 
202   auto AddUsedCfiGlobal = [&](GlobalValue::GUID ValueGUID) {
203     if (CfiFunctionDefs.count(ValueGUID))
204       UsedCfiDefs.insert(ValueGUID);
205     if (CfiFunctionDecls.count(ValueGUID))
206       UsedCfiDecls.insert(ValueGUID);
207   };
208 
209   auto AddUsedThings = [&](GlobalValueSummary *GS) {
210     if (!GS) return;
211     AddUnsigned(GS->getVisibility());
212     AddUnsigned(GS->isLive());
213     AddUnsigned(GS->canAutoHide());
214     for (const ValueInfo &VI : GS->refs()) {
215       AddUnsigned(VI.isDSOLocal(Index.withDSOLocalPropagation()));
216       AddUsedCfiGlobal(VI.getGUID());
217     }
218     if (auto *GVS = dyn_cast<GlobalVarSummary>(GS)) {
219       AddUnsigned(GVS->maybeReadOnly());
220       AddUnsigned(GVS->maybeWriteOnly());
221     }
222     if (auto *FS = dyn_cast<FunctionSummary>(GS)) {
223       for (auto &TT : FS->type_tests())
224         UsedTypeIds.insert(TT);
225       for (auto &TT : FS->type_test_assume_vcalls())
226         UsedTypeIds.insert(TT.GUID);
227       for (auto &TT : FS->type_checked_load_vcalls())
228         UsedTypeIds.insert(TT.GUID);
229       for (auto &TT : FS->type_test_assume_const_vcalls())
230         UsedTypeIds.insert(TT.VFunc.GUID);
231       for (auto &TT : FS->type_checked_load_const_vcalls())
232         UsedTypeIds.insert(TT.VFunc.GUID);
233       for (auto &ET : FS->calls()) {
234         AddUnsigned(ET.first.isDSOLocal(Index.withDSOLocalPropagation()));
235         AddUsedCfiGlobal(ET.first.getGUID());
236       }
237     }
238   };
239 
240   // Include the hash for the linkage type to reflect internalization and weak
241   // resolution, and collect any used type identifier resolutions.
242   for (auto &GS : DefinedGlobals) {
243     GlobalValue::LinkageTypes Linkage = GS.second->linkage();
244     Hasher.update(
245         ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
246     AddUsedCfiGlobal(GS.first);
247     AddUsedThings(GS.second);
248   }
249 
250   // Imported functions may introduce new uses of type identifier resolutions,
251   // so we need to collect their used resolutions as well.
252   for (auto &ImpM : ImportList)
253     for (auto &ImpF : ImpM.second) {
254       GlobalValueSummary *S = Index.findSummaryInModule(ImpF, ImpM.first());
255       AddUsedThings(S);
256       // If this is an alias, we also care about any types/etc. that the aliasee
257       // may reference.
258       if (auto *AS = dyn_cast_or_null<AliasSummary>(S))
259         AddUsedThings(AS->getBaseObject());
260     }
261 
262   auto AddTypeIdSummary = [&](StringRef TId, const TypeIdSummary &S) {
263     AddString(TId);
264 
265     AddUnsigned(S.TTRes.TheKind);
266     AddUnsigned(S.TTRes.SizeM1BitWidth);
267 
268     AddUint64(S.TTRes.AlignLog2);
269     AddUint64(S.TTRes.SizeM1);
270     AddUint64(S.TTRes.BitMask);
271     AddUint64(S.TTRes.InlineBits);
272 
273     AddUint64(S.WPDRes.size());
274     for (auto &WPD : S.WPDRes) {
275       AddUnsigned(WPD.first);
276       AddUnsigned(WPD.second.TheKind);
277       AddString(WPD.second.SingleImplName);
278 
279       AddUint64(WPD.second.ResByArg.size());
280       for (auto &ByArg : WPD.second.ResByArg) {
281         AddUint64(ByArg.first.size());
282         for (uint64_t Arg : ByArg.first)
283           AddUint64(Arg);
284         AddUnsigned(ByArg.second.TheKind);
285         AddUint64(ByArg.second.Info);
286         AddUnsigned(ByArg.second.Byte);
287         AddUnsigned(ByArg.second.Bit);
288       }
289     }
290   };
291 
292   // Include the hash for all type identifiers used by this module.
293   for (GlobalValue::GUID TId : UsedTypeIds) {
294     auto TidIter = Index.typeIds().equal_range(TId);
295     for (auto It = TidIter.first; It != TidIter.second; ++It)
296       AddTypeIdSummary(It->second.first, It->second.second);
297   }
298 
299   AddUnsigned(UsedCfiDefs.size());
300   for (auto &V : UsedCfiDefs)
301     AddUint64(V);
302 
303   AddUnsigned(UsedCfiDecls.size());
304   for (auto &V : UsedCfiDecls)
305     AddUint64(V);
306 
307   if (!Conf.SampleProfile.empty()) {
308     auto FileOrErr = MemoryBuffer::getFile(Conf.SampleProfile);
309     if (FileOrErr) {
310       Hasher.update(FileOrErr.get()->getBuffer());
311 
312       if (!Conf.ProfileRemapping.empty()) {
313         FileOrErr = MemoryBuffer::getFile(Conf.ProfileRemapping);
314         if (FileOrErr)
315           Hasher.update(FileOrErr.get()->getBuffer());
316       }
317     }
318   }
319 
320   Key = toHex(Hasher.result());
321 }
322 
323 static void thinLTOResolvePrevailingGUID(
324     const Config &C, ValueInfo VI,
325     DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
326     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
327         isPrevailing,
328     function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
329         recordNewLinkage,
330     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
331   GlobalValue::VisibilityTypes Visibility =
332       C.VisibilityScheme == Config::ELF ? VI.getELFVisibility()
333                                         : GlobalValue::DefaultVisibility;
334   for (auto &S : VI.getSummaryList()) {
335     GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
336     // Ignore local and appending linkage values since the linker
337     // doesn't resolve them.
338     if (GlobalValue::isLocalLinkage(OriginalLinkage) ||
339         GlobalValue::isAppendingLinkage(S->linkage()))
340       continue;
341     // We need to emit only one of these. The prevailing module will keep it,
342     // but turned into a weak, while the others will drop it when possible.
343     // This is both a compile-time optimization and a correctness
344     // transformation. This is necessary for correctness when we have exported
345     // a reference - we need to convert the linkonce to weak to
346     // ensure a copy is kept to satisfy the exported reference.
347     // FIXME: We may want to split the compile time and correctness
348     // aspects into separate routines.
349     if (isPrevailing(VI.getGUID(), S.get())) {
350       if (GlobalValue::isLinkOnceLinkage(OriginalLinkage)) {
351         S->setLinkage(GlobalValue::getWeakLinkage(
352             GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
353         // The kept copy is eligible for auto-hiding (hidden visibility) if all
354         // copies were (i.e. they were all linkonce_odr global unnamed addr).
355         // If any copy is not (e.g. it was originally weak_odr), then the symbol
356         // must remain externally available (e.g. a weak_odr from an explicitly
357         // instantiated template). Additionally, if it is in the
358         // GUIDPreservedSymbols set, that means that it is visibile outside
359         // the summary (e.g. in a native object or a bitcode file without
360         // summary), and in that case we cannot hide it as it isn't possible to
361         // check all copies.
362         S->setCanAutoHide(VI.canAutoHide() &&
363                           !GUIDPreservedSymbols.count(VI.getGUID()));
364       }
365       if (C.VisibilityScheme == Config::FromPrevailing)
366         Visibility = S->getVisibility();
367     }
368     // Alias and aliasee can't be turned into available_externally.
369     else if (!isa<AliasSummary>(S.get()) &&
370              !GlobalInvolvedWithAlias.count(S.get()))
371       S->setLinkage(GlobalValue::AvailableExternallyLinkage);
372 
373     // For ELF, set visibility to the computed visibility from summaries. We
374     // don't track visibility from declarations so this may be more relaxed than
375     // the most constraining one.
376     if (C.VisibilityScheme == Config::ELF)
377       S->setVisibility(Visibility);
378 
379     if (S->linkage() != OriginalLinkage)
380       recordNewLinkage(S->modulePath(), VI.getGUID(), S->linkage());
381   }
382 
383   if (C.VisibilityScheme == Config::FromPrevailing) {
384     for (auto &S : VI.getSummaryList()) {
385       GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
386       if (GlobalValue::isLocalLinkage(OriginalLinkage) ||
387           GlobalValue::isAppendingLinkage(S->linkage()))
388         continue;
389       S->setVisibility(Visibility);
390     }
391   }
392 }
393 
394 /// Resolve linkage for prevailing symbols in the \p Index.
395 //
396 // We'd like to drop these functions if they are no longer referenced in the
397 // current module. However there is a chance that another module is still
398 // referencing them because of the import. We make sure we always emit at least
399 // one copy.
400 void llvm::thinLTOResolvePrevailingInIndex(
401     const Config &C, ModuleSummaryIndex &Index,
402     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
403         isPrevailing,
404     function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
405         recordNewLinkage,
406     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
407   // We won't optimize the globals that are referenced by an alias for now
408   // Ideally we should turn the alias into a global and duplicate the definition
409   // when needed.
410   DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
411   for (auto &I : Index)
412     for (auto &S : I.second.SummaryList)
413       if (auto AS = dyn_cast<AliasSummary>(S.get()))
414         GlobalInvolvedWithAlias.insert(&AS->getAliasee());
415 
416   for (auto &I : Index)
417     thinLTOResolvePrevailingGUID(C, Index.getValueInfo(I),
418                                  GlobalInvolvedWithAlias, isPrevailing,
419                                  recordNewLinkage, GUIDPreservedSymbols);
420 }
421 
422 static bool isWeakObjectWithRWAccess(GlobalValueSummary *GVS) {
423   if (auto *VarSummary = dyn_cast<GlobalVarSummary>(GVS->getBaseObject()))
424     return !VarSummary->maybeReadOnly() && !VarSummary->maybeWriteOnly() &&
425            (VarSummary->linkage() == GlobalValue::WeakODRLinkage ||
426             VarSummary->linkage() == GlobalValue::LinkOnceODRLinkage);
427   return false;
428 }
429 
430 static void thinLTOInternalizeAndPromoteGUID(
431     ValueInfo VI, function_ref<bool(StringRef, ValueInfo)> isExported,
432     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
433         isPrevailing) {
434   for (auto &S : VI.getSummaryList()) {
435     if (isExported(S->modulePath(), VI)) {
436       if (GlobalValue::isLocalLinkage(S->linkage()))
437         S->setLinkage(GlobalValue::ExternalLinkage);
438     } else if (EnableLTOInternalization &&
439                // Ignore local and appending linkage values since the linker
440                // doesn't resolve them.
441                !GlobalValue::isLocalLinkage(S->linkage()) &&
442                (!GlobalValue::isInterposableLinkage(S->linkage()) ||
443                 isPrevailing(VI.getGUID(), S.get())) &&
444                S->linkage() != GlobalValue::AppendingLinkage &&
445                // We can't internalize available_externally globals because this
446                // can break function pointer equality.
447                S->linkage() != GlobalValue::AvailableExternallyLinkage &&
448                // Functions and read-only variables with linkonce_odr and
449                // weak_odr linkage can be internalized. We can't internalize
450                // linkonce_odr and weak_odr variables which are both modified
451                // and read somewhere in the program because reads and writes
452                // will become inconsistent.
453                !isWeakObjectWithRWAccess(S.get()))
454       S->setLinkage(GlobalValue::InternalLinkage);
455   }
456 }
457 
458 // Update the linkages in the given \p Index to mark exported values
459 // as external and non-exported values as internal.
460 void llvm::thinLTOInternalizeAndPromoteInIndex(
461     ModuleSummaryIndex &Index,
462     function_ref<bool(StringRef, ValueInfo)> isExported,
463     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
464         isPrevailing) {
465   for (auto &I : Index)
466     thinLTOInternalizeAndPromoteGUID(Index.getValueInfo(I), isExported,
467                                      isPrevailing);
468 }
469 
470 // Requires a destructor for std::vector<InputModule>.
471 InputFile::~InputFile() = default;
472 
473 Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
474   std::unique_ptr<InputFile> File(new InputFile);
475 
476   Expected<IRSymtabFile> FOrErr = readIRSymtab(Object);
477   if (!FOrErr)
478     return FOrErr.takeError();
479 
480   File->TargetTriple = FOrErr->TheReader.getTargetTriple();
481   File->SourceFileName = FOrErr->TheReader.getSourceFileName();
482   File->COFFLinkerOpts = FOrErr->TheReader.getCOFFLinkerOpts();
483   File->DependentLibraries = FOrErr->TheReader.getDependentLibraries();
484   File->ComdatTable = FOrErr->TheReader.getComdatTable();
485 
486   for (unsigned I = 0; I != FOrErr->Mods.size(); ++I) {
487     size_t Begin = File->Symbols.size();
488     for (const irsymtab::Reader::SymbolRef &Sym :
489          FOrErr->TheReader.module_symbols(I))
490       // Skip symbols that are irrelevant to LTO. Note that this condition needs
491       // to match the one in Skip() in LTO::addRegularLTO().
492       if (Sym.isGlobal() && !Sym.isFormatSpecific())
493         File->Symbols.push_back(Sym);
494     File->ModuleSymIndices.push_back({Begin, File->Symbols.size()});
495   }
496 
497   File->Mods = FOrErr->Mods;
498   File->Strtab = std::move(FOrErr->Strtab);
499   return std::move(File);
500 }
501 
502 StringRef InputFile::getName() const {
503   return Mods[0].getModuleIdentifier();
504 }
505 
506 BitcodeModule &InputFile::getSingleBitcodeModule() {
507   assert(Mods.size() == 1 && "Expect only one bitcode module");
508   return Mods[0];
509 }
510 
511 LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
512                                       const Config &Conf)
513     : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
514       Ctx(Conf), CombinedModule(std::make_unique<Module>("ld-temp.o", Ctx)),
515       Mover(std::make_unique<IRMover>(*CombinedModule)) {}
516 
517 LTO::ThinLTOState::ThinLTOState(ThinBackend Backend)
518     : Backend(Backend), CombinedIndex(/*HaveGVs*/ false) {
519   if (!Backend)
520     this->Backend =
521         createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
522 }
523 
524 LTO::LTO(Config Conf, ThinBackend Backend,
525          unsigned ParallelCodeGenParallelismLevel)
526     : Conf(std::move(Conf)),
527       RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
528       ThinLTO(std::move(Backend)) {}
529 
530 // Requires a destructor for MapVector<BitcodeModule>.
531 LTO::~LTO() = default;
532 
533 // Add the symbols in the given module to the GlobalResolutions map, and resolve
534 // their partitions.
535 void LTO::addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms,
536                                ArrayRef<SymbolResolution> Res,
537                                unsigned Partition, bool InSummary) {
538   auto *ResI = Res.begin();
539   auto *ResE = Res.end();
540   (void)ResE;
541   const Triple TT(RegularLTO.CombinedModule->getTargetTriple());
542   for (const InputFile::Symbol &Sym : Syms) {
543     assert(ResI != ResE);
544     SymbolResolution Res = *ResI++;
545 
546     StringRef Name = Sym.getName();
547     // Strip the __imp_ prefix from COFF dllimport symbols (similar to the
548     // way they are handled by lld), otherwise we can end up with two
549     // global resolutions (one with and one for a copy of the symbol without).
550     if (TT.isOSBinFormatCOFF() && Name.startswith("__imp_"))
551       Name = Name.substr(strlen("__imp_"));
552     auto &GlobalRes = GlobalResolutions[Name];
553     GlobalRes.UnnamedAddr &= Sym.isUnnamedAddr();
554     if (Res.Prevailing) {
555       assert(!GlobalRes.Prevailing &&
556              "Multiple prevailing defs are not allowed");
557       GlobalRes.Prevailing = true;
558       GlobalRes.IRName = std::string(Sym.getIRName());
559     } else if (!GlobalRes.Prevailing && GlobalRes.IRName.empty()) {
560       // Sometimes it can be two copies of symbol in a module and prevailing
561       // symbol can have no IR name. That might happen if symbol is defined in
562       // module level inline asm block. In case we have multiple modules with
563       // the same symbol we want to use IR name of the prevailing symbol.
564       // Otherwise, if we haven't seen a prevailing symbol, set the name so that
565       // we can later use it to check if there is any prevailing copy in IR.
566       GlobalRes.IRName = std::string(Sym.getIRName());
567     }
568 
569     // Set the partition to external if we know it is re-defined by the linker
570     // with -defsym or -wrap options, used elsewhere, e.g. it is visible to a
571     // regular object, is referenced from llvm.compiler.used/llvm.used, or was
572     // already recorded as being referenced from a different partition.
573     if (Res.LinkerRedefined || Res.VisibleToRegularObj || Sym.isUsed() ||
574         (GlobalRes.Partition != GlobalResolution::Unknown &&
575          GlobalRes.Partition != Partition)) {
576       GlobalRes.Partition = GlobalResolution::External;
577     } else
578       // First recorded reference, save the current partition.
579       GlobalRes.Partition = Partition;
580 
581     // Flag as visible outside of summary if visible from a regular object or
582     // from a module that does not have a summary.
583     GlobalRes.VisibleOutsideSummary |=
584         (Res.VisibleToRegularObj || Sym.isUsed() || !InSummary);
585 
586     GlobalRes.ExportDynamic |= Res.ExportDynamic;
587   }
588 }
589 
590 static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
591                                   ArrayRef<SymbolResolution> Res) {
592   StringRef Path = Input->getName();
593   OS << Path << '\n';
594   auto ResI = Res.begin();
595   for (const InputFile::Symbol &Sym : Input->symbols()) {
596     assert(ResI != Res.end());
597     SymbolResolution Res = *ResI++;
598 
599     OS << "-r=" << Path << ',' << Sym.getName() << ',';
600     if (Res.Prevailing)
601       OS << 'p';
602     if (Res.FinalDefinitionInLinkageUnit)
603       OS << 'l';
604     if (Res.VisibleToRegularObj)
605       OS << 'x';
606     if (Res.LinkerRedefined)
607       OS << 'r';
608     OS << '\n';
609   }
610   OS.flush();
611   assert(ResI == Res.end());
612 }
613 
614 Error LTO::add(std::unique_ptr<InputFile> Input,
615                ArrayRef<SymbolResolution> Res) {
616   assert(!CalledGetMaxTasks);
617 
618   if (Conf.ResolutionFile)
619     writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
620 
621   if (RegularLTO.CombinedModule->getTargetTriple().empty()) {
622     RegularLTO.CombinedModule->setTargetTriple(Input->getTargetTriple());
623     if (Triple(Input->getTargetTriple()).isOSBinFormatELF())
624       Conf.VisibilityScheme = Config::ELF;
625   }
626 
627   const SymbolResolution *ResI = Res.begin();
628   for (unsigned I = 0; I != Input->Mods.size(); ++I)
629     if (Error Err = addModule(*Input, I, ResI, Res.end()))
630       return Err;
631 
632   assert(ResI == Res.end());
633   return Error::success();
634 }
635 
636 Error LTO::addModule(InputFile &Input, unsigned ModI,
637                      const SymbolResolution *&ResI,
638                      const SymbolResolution *ResE) {
639   Expected<BitcodeLTOInfo> LTOInfo = Input.Mods[ModI].getLTOInfo();
640   if (!LTOInfo)
641     return LTOInfo.takeError();
642 
643   if (EnableSplitLTOUnit.hasValue()) {
644     // If only some modules were split, flag this in the index so that
645     // we can skip or error on optimizations that need consistently split
646     // modules (whole program devirt and lower type tests).
647     if (EnableSplitLTOUnit.getValue() != LTOInfo->EnableSplitLTOUnit)
648       ThinLTO.CombinedIndex.setPartiallySplitLTOUnits();
649   } else
650     EnableSplitLTOUnit = LTOInfo->EnableSplitLTOUnit;
651 
652   BitcodeModule BM = Input.Mods[ModI];
653   auto ModSyms = Input.module_symbols(ModI);
654   addModuleToGlobalRes(ModSyms, {ResI, ResE},
655                        LTOInfo->IsThinLTO ? ThinLTO.ModuleMap.size() + 1 : 0,
656                        LTOInfo->HasSummary);
657 
658   if (LTOInfo->IsThinLTO)
659     return addThinLTO(BM, ModSyms, ResI, ResE);
660 
661   RegularLTO.EmptyCombinedModule = false;
662   Expected<RegularLTOState::AddedModule> ModOrErr =
663       addRegularLTO(BM, ModSyms, ResI, ResE);
664   if (!ModOrErr)
665     return ModOrErr.takeError();
666 
667   if (!LTOInfo->HasSummary)
668     return linkRegularLTO(std::move(*ModOrErr), /*LivenessFromIndex=*/false);
669 
670   // Regular LTO module summaries are added to a dummy module that represents
671   // the combined regular LTO module.
672   if (Error Err = BM.readSummary(ThinLTO.CombinedIndex, "", -1ull))
673     return Err;
674   RegularLTO.ModsWithSummaries.push_back(std::move(*ModOrErr));
675   return Error::success();
676 }
677 
678 // Checks whether the given global value is in a non-prevailing comdat
679 // (comdat containing values the linker indicated were not prevailing,
680 // which we then dropped to available_externally), and if so, removes
681 // it from the comdat. This is called for all global values to ensure the
682 // comdat is empty rather than leaving an incomplete comdat. It is needed for
683 // regular LTO modules, in case we are in a mixed-LTO mode (both regular
684 // and thin LTO modules) compilation. Since the regular LTO module will be
685 // linked first in the final native link, we want to make sure the linker
686 // doesn't select any of these incomplete comdats that would be left
687 // in the regular LTO module without this cleanup.
688 static void
689 handleNonPrevailingComdat(GlobalValue &GV,
690                           std::set<const Comdat *> &NonPrevailingComdats) {
691   Comdat *C = GV.getComdat();
692   if (!C)
693     return;
694 
695   if (!NonPrevailingComdats.count(C))
696     return;
697 
698   // Additionally need to drop externally visible global values from the comdat
699   // to available_externally, so that there aren't multiply defined linker
700   // errors.
701   if (!GV.hasLocalLinkage())
702     GV.setLinkage(GlobalValue::AvailableExternallyLinkage);
703 
704   if (auto GO = dyn_cast<GlobalObject>(&GV))
705     GO->setComdat(nullptr);
706 }
707 
708 // Add a regular LTO object to the link.
709 // The resulting module needs to be linked into the combined LTO module with
710 // linkRegularLTO.
711 Expected<LTO::RegularLTOState::AddedModule>
712 LTO::addRegularLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
713                    const SymbolResolution *&ResI,
714                    const SymbolResolution *ResE) {
715   RegularLTOState::AddedModule Mod;
716   Expected<std::unique_ptr<Module>> MOrErr =
717       BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
718                        /*IsImporting*/ false);
719   if (!MOrErr)
720     return MOrErr.takeError();
721   Module &M = **MOrErr;
722   Mod.M = std::move(*MOrErr);
723 
724   if (Error Err = M.materializeMetadata())
725     return std::move(Err);
726   UpgradeDebugInfo(M);
727 
728   ModuleSymbolTable SymTab;
729   SymTab.addModule(&M);
730 
731   for (GlobalVariable &GV : M.globals())
732     if (GV.hasAppendingLinkage())
733       Mod.Keep.push_back(&GV);
734 
735   DenseSet<GlobalObject *> AliasedGlobals;
736   for (auto &GA : M.aliases())
737     if (GlobalObject *GO = GA.getAliaseeObject())
738       AliasedGlobals.insert(GO);
739 
740   // In this function we need IR GlobalValues matching the symbols in Syms
741   // (which is not backed by a module), so we need to enumerate them in the same
742   // order. The symbol enumeration order of a ModuleSymbolTable intentionally
743   // matches the order of an irsymtab, but when we read the irsymtab in
744   // InputFile::create we omit some symbols that are irrelevant to LTO. The
745   // Skip() function skips the same symbols from the module as InputFile does
746   // from the symbol table.
747   auto MsymI = SymTab.symbols().begin(), MsymE = SymTab.symbols().end();
748   auto Skip = [&]() {
749     while (MsymI != MsymE) {
750       auto Flags = SymTab.getSymbolFlags(*MsymI);
751       if ((Flags & object::BasicSymbolRef::SF_Global) &&
752           !(Flags & object::BasicSymbolRef::SF_FormatSpecific))
753         return;
754       ++MsymI;
755     }
756   };
757   Skip();
758 
759   std::set<const Comdat *> NonPrevailingComdats;
760   SmallSet<StringRef, 2> NonPrevailingAsmSymbols;
761   for (const InputFile::Symbol &Sym : Syms) {
762     assert(ResI != ResE);
763     SymbolResolution Res = *ResI++;
764 
765     assert(MsymI != MsymE);
766     ModuleSymbolTable::Symbol Msym = *MsymI++;
767     Skip();
768 
769     if (GlobalValue *GV = Msym.dyn_cast<GlobalValue *>()) {
770       if (Res.Prevailing) {
771         if (Sym.isUndefined())
772           continue;
773         Mod.Keep.push_back(GV);
774         // For symbols re-defined with linker -wrap and -defsym options,
775         // set the linkage to weak to inhibit IPO. The linkage will be
776         // restored by the linker.
777         if (Res.LinkerRedefined)
778           GV->setLinkage(GlobalValue::WeakAnyLinkage);
779 
780         GlobalValue::LinkageTypes OriginalLinkage = GV->getLinkage();
781         if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
782           GV->setLinkage(GlobalValue::getWeakLinkage(
783               GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
784       } else if (isa<GlobalObject>(GV) &&
785                  (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
786                   GV->hasAvailableExternallyLinkage()) &&
787                  !AliasedGlobals.count(cast<GlobalObject>(GV))) {
788         // Any of the above three types of linkage indicates that the
789         // chosen prevailing symbol will have the same semantics as this copy of
790         // the symbol, so we may be able to link it with available_externally
791         // linkage. We will decide later whether to do that when we link this
792         // module (in linkRegularLTO), based on whether it is undefined.
793         Mod.Keep.push_back(GV);
794         GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
795         if (GV->hasComdat())
796           NonPrevailingComdats.insert(GV->getComdat());
797         cast<GlobalObject>(GV)->setComdat(nullptr);
798       }
799 
800       // Set the 'local' flag based on the linker resolution for this symbol.
801       if (Res.FinalDefinitionInLinkageUnit) {
802         GV->setDSOLocal(true);
803         if (GV->hasDLLImportStorageClass())
804           GV->setDLLStorageClass(GlobalValue::DLLStorageClassTypes::
805                                  DefaultStorageClass);
806       }
807     } else if (auto *AS = Msym.dyn_cast<ModuleSymbolTable::AsmSymbol *>()) {
808       // Collect non-prevailing symbols.
809       if (!Res.Prevailing)
810         NonPrevailingAsmSymbols.insert(AS->first);
811     } else {
812       llvm_unreachable("unknown symbol type");
813     }
814 
815     // Common resolution: collect the maximum size/alignment over all commons.
816     // We also record if we see an instance of a common as prevailing, so that
817     // if none is prevailing we can ignore it later.
818     if (Sym.isCommon()) {
819       // FIXME: We should figure out what to do about commons defined by asm.
820       // For now they aren't reported correctly by ModuleSymbolTable.
821       auto &CommonRes = RegularLTO.Commons[std::string(Sym.getIRName())];
822       CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
823       MaybeAlign SymAlign(Sym.getCommonAlignment());
824       if (SymAlign)
825         CommonRes.Align = max(*SymAlign, CommonRes.Align);
826       CommonRes.Prevailing |= Res.Prevailing;
827     }
828   }
829 
830   if (!M.getComdatSymbolTable().empty())
831     for (GlobalValue &GV : M.global_values())
832       handleNonPrevailingComdat(GV, NonPrevailingComdats);
833 
834   // Prepend ".lto_discard <sym>, <sym>*" directive to each module inline asm
835   // block.
836   if (!M.getModuleInlineAsm().empty()) {
837     std::string NewIA = ".lto_discard";
838     if (!NonPrevailingAsmSymbols.empty()) {
839       // Don't dicard a symbol if there is a live .symver for it.
840       ModuleSymbolTable::CollectAsmSymvers(
841           M, [&](StringRef Name, StringRef Alias) {
842             if (!NonPrevailingAsmSymbols.count(Alias))
843               NonPrevailingAsmSymbols.erase(Name);
844           });
845       NewIA += " " + llvm::join(NonPrevailingAsmSymbols, ", ");
846     }
847     NewIA += "\n";
848     M.setModuleInlineAsm(NewIA + M.getModuleInlineAsm());
849   }
850 
851   assert(MsymI == MsymE);
852   return std::move(Mod);
853 }
854 
855 Error LTO::linkRegularLTO(RegularLTOState::AddedModule Mod,
856                           bool LivenessFromIndex) {
857   std::vector<GlobalValue *> Keep;
858   for (GlobalValue *GV : Mod.Keep) {
859     if (LivenessFromIndex && !ThinLTO.CombinedIndex.isGUIDLive(GV->getGUID())) {
860       if (Function *F = dyn_cast<Function>(GV)) {
861         if (DiagnosticOutputFile) {
862           if (Error Err = F->materialize())
863             return Err;
864           OptimizationRemarkEmitter ORE(F, nullptr);
865           ORE.emit(OptimizationRemark(DEBUG_TYPE, "deadfunction", F)
866                    << ore::NV("Function", F)
867                    << " not added to the combined module ");
868         }
869       }
870       continue;
871     }
872 
873     if (!GV->hasAvailableExternallyLinkage()) {
874       Keep.push_back(GV);
875       continue;
876     }
877 
878     // Only link available_externally definitions if we don't already have a
879     // definition.
880     GlobalValue *CombinedGV =
881         RegularLTO.CombinedModule->getNamedValue(GV->getName());
882     if (CombinedGV && !CombinedGV->isDeclaration())
883       continue;
884 
885     Keep.push_back(GV);
886   }
887 
888   return RegularLTO.Mover->move(std::move(Mod.M), Keep,
889                                 [](GlobalValue &, IRMover::ValueAdder) {},
890                                 /* IsPerformingImport */ false);
891 }
892 
893 // Add a ThinLTO module to the link.
894 Error LTO::addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
895                       const SymbolResolution *&ResI,
896                       const SymbolResolution *ResE) {
897   if (Error Err =
898           BM.readSummary(ThinLTO.CombinedIndex, BM.getModuleIdentifier(),
899                          ThinLTO.ModuleMap.size()))
900     return Err;
901 
902   for (const InputFile::Symbol &Sym : Syms) {
903     assert(ResI != ResE);
904     SymbolResolution Res = *ResI++;
905 
906     if (!Sym.getIRName().empty()) {
907       auto GUID = GlobalValue::getGUID(GlobalValue::getGlobalIdentifier(
908           Sym.getIRName(), GlobalValue::ExternalLinkage, ""));
909       if (Res.Prevailing) {
910         ThinLTO.PrevailingModuleForGUID[GUID] = BM.getModuleIdentifier();
911 
912         // For linker redefined symbols (via --wrap or --defsym) we want to
913         // switch the linkage to `weak` to prevent IPOs from happening.
914         // Find the summary in the module for this very GV and record the new
915         // linkage so that we can switch it when we import the GV.
916         if (Res.LinkerRedefined)
917           if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(
918                   GUID, BM.getModuleIdentifier()))
919             S->setLinkage(GlobalValue::WeakAnyLinkage);
920       }
921 
922       // If the linker resolved the symbol to a local definition then mark it
923       // as local in the summary for the module we are adding.
924       if (Res.FinalDefinitionInLinkageUnit) {
925         if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(
926                 GUID, BM.getModuleIdentifier())) {
927           S->setDSOLocal(true);
928         }
929       }
930     }
931   }
932 
933   if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
934     return make_error<StringError>(
935         "Expected at most one ThinLTO module per bitcode file",
936         inconvertibleErrorCode());
937 
938   if (!Conf.ThinLTOModulesToCompile.empty()) {
939     if (!ThinLTO.ModulesToCompile)
940       ThinLTO.ModulesToCompile = ModuleMapType();
941     // This is a fuzzy name matching where only modules with name containing the
942     // specified switch values are going to be compiled.
943     for (const std::string &Name : Conf.ThinLTOModulesToCompile) {
944       if (BM.getModuleIdentifier().contains(Name)) {
945         ThinLTO.ModulesToCompile->insert({BM.getModuleIdentifier(), BM});
946         llvm::errs() << "[ThinLTO] Selecting " << BM.getModuleIdentifier()
947                      << " to compile\n";
948       }
949     }
950   }
951 
952   return Error::success();
953 }
954 
955 unsigned LTO::getMaxTasks() const {
956   CalledGetMaxTasks = true;
957   auto ModuleCount = ThinLTO.ModulesToCompile ? ThinLTO.ModulesToCompile->size()
958                                               : ThinLTO.ModuleMap.size();
959   return RegularLTO.ParallelCodeGenParallelismLevel + ModuleCount;
960 }
961 
962 // If only some of the modules were split, we cannot correctly handle
963 // code that contains type tests or type checked loads.
964 Error LTO::checkPartiallySplit() {
965   if (!ThinLTO.CombinedIndex.partiallySplitLTOUnits())
966     return Error::success();
967 
968   Function *TypeTestFunc = RegularLTO.CombinedModule->getFunction(
969       Intrinsic::getName(Intrinsic::type_test));
970   Function *TypeCheckedLoadFunc = RegularLTO.CombinedModule->getFunction(
971       Intrinsic::getName(Intrinsic::type_checked_load));
972 
973   // First check if there are type tests / type checked loads in the
974   // merged regular LTO module IR.
975   if ((TypeTestFunc && !TypeTestFunc->use_empty()) ||
976       (TypeCheckedLoadFunc && !TypeCheckedLoadFunc->use_empty()))
977     return make_error<StringError>(
978         "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
979         inconvertibleErrorCode());
980 
981   // Otherwise check if there are any recorded in the combined summary from the
982   // ThinLTO modules.
983   for (auto &P : ThinLTO.CombinedIndex) {
984     for (auto &S : P.second.SummaryList) {
985       auto *FS = dyn_cast<FunctionSummary>(S.get());
986       if (!FS)
987         continue;
988       if (!FS->type_test_assume_vcalls().empty() ||
989           !FS->type_checked_load_vcalls().empty() ||
990           !FS->type_test_assume_const_vcalls().empty() ||
991           !FS->type_checked_load_const_vcalls().empty() ||
992           !FS->type_tests().empty())
993         return make_error<StringError>(
994             "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
995             inconvertibleErrorCode());
996     }
997   }
998   return Error::success();
999 }
1000 
1001 Error LTO::run(AddStreamFn AddStream, FileCache Cache) {
1002   // Compute "dead" symbols, we don't want to import/export these!
1003   DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
1004   DenseMap<GlobalValue::GUID, PrevailingType> GUIDPrevailingResolutions;
1005   for (auto &Res : GlobalResolutions) {
1006     // Normally resolution have IR name of symbol. We can do nothing here
1007     // otherwise. See comments in GlobalResolution struct for more details.
1008     if (Res.second.IRName.empty())
1009       continue;
1010 
1011     GlobalValue::GUID GUID = GlobalValue::getGUID(
1012         GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
1013 
1014     if (Res.second.VisibleOutsideSummary && Res.second.Prevailing)
1015       GUIDPreservedSymbols.insert(GUID);
1016 
1017     if (Res.second.ExportDynamic)
1018       DynamicExportSymbols.insert(GUID);
1019 
1020     GUIDPrevailingResolutions[GUID] =
1021         Res.second.Prevailing ? PrevailingType::Yes : PrevailingType::No;
1022   }
1023 
1024   auto isPrevailing = [&](GlobalValue::GUID G) {
1025     auto It = GUIDPrevailingResolutions.find(G);
1026     if (It == GUIDPrevailingResolutions.end())
1027       return PrevailingType::Unknown;
1028     return It->second;
1029   };
1030   computeDeadSymbolsWithConstProp(ThinLTO.CombinedIndex, GUIDPreservedSymbols,
1031                                   isPrevailing, Conf.OptLevel > 0);
1032 
1033   // Setup output file to emit statistics.
1034   auto StatsFileOrErr = setupStatsFile(Conf.StatsFile);
1035   if (!StatsFileOrErr)
1036     return StatsFileOrErr.takeError();
1037   std::unique_ptr<ToolOutputFile> StatsFile = std::move(StatsFileOrErr.get());
1038 
1039   Error Result = runRegularLTO(AddStream);
1040   if (!Result)
1041     Result = runThinLTO(AddStream, Cache, GUIDPreservedSymbols);
1042 
1043   if (StatsFile)
1044     PrintStatisticsJSON(StatsFile->os());
1045 
1046   return Result;
1047 }
1048 
1049 Error LTO::runRegularLTO(AddStreamFn AddStream) {
1050   // Setup optimization remarks.
1051   auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
1052       RegularLTO.CombinedModule->getContext(), Conf.RemarksFilename,
1053       Conf.RemarksPasses, Conf.RemarksFormat, Conf.RemarksWithHotness,
1054       Conf.RemarksHotnessThreshold);
1055   if (!DiagFileOrErr)
1056     return DiagFileOrErr.takeError();
1057   DiagnosticOutputFile = std::move(*DiagFileOrErr);
1058 
1059   // Finalize linking of regular LTO modules containing summaries now that
1060   // we have computed liveness information.
1061   for (auto &M : RegularLTO.ModsWithSummaries)
1062     if (Error Err = linkRegularLTO(std::move(M),
1063                                    /*LivenessFromIndex=*/true))
1064       return Err;
1065 
1066   // Ensure we don't have inconsistently split LTO units with type tests.
1067   // FIXME: this checks both LTO and ThinLTO. It happens to work as we take
1068   // this path both cases but eventually this should be split into two and
1069   // do the ThinLTO checks in `runThinLTO`.
1070   if (Error Err = checkPartiallySplit())
1071     return Err;
1072 
1073   // Make sure commons have the right size/alignment: we kept the largest from
1074   // all the prevailing when adding the inputs, and we apply it here.
1075   const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
1076   for (auto &I : RegularLTO.Commons) {
1077     if (!I.second.Prevailing)
1078       // Don't do anything if no instance of this common was prevailing.
1079       continue;
1080     GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
1081     if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
1082       // Don't create a new global if the type is already correct, just make
1083       // sure the alignment is correct.
1084       OldGV->setAlignment(I.second.Align);
1085       continue;
1086     }
1087     ArrayType *Ty =
1088         ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
1089     auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
1090                                   GlobalValue::CommonLinkage,
1091                                   ConstantAggregateZero::get(Ty), "");
1092     GV->setAlignment(I.second.Align);
1093     if (OldGV) {
1094       OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
1095       GV->takeName(OldGV);
1096       OldGV->eraseFromParent();
1097     } else {
1098       GV->setName(I.first);
1099     }
1100   }
1101 
1102   // If allowed, upgrade public vcall visibility metadata to linkage unit
1103   // visibility before whole program devirtualization in the optimizer.
1104   updateVCallVisibilityInModule(*RegularLTO.CombinedModule,
1105                                 Conf.HasWholeProgramVisibility,
1106                                 DynamicExportSymbols);
1107 
1108   if (Conf.PreOptModuleHook &&
1109       !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
1110     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
1111 
1112   if (!Conf.CodeGenOnly) {
1113     for (const auto &R : GlobalResolutions) {
1114       if (!R.second.isPrevailingIRSymbol())
1115         continue;
1116       if (R.second.Partition != 0 &&
1117           R.second.Partition != GlobalResolution::External)
1118         continue;
1119 
1120       GlobalValue *GV =
1121           RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
1122       // Ignore symbols defined in other partitions.
1123       // Also skip declarations, which are not allowed to have internal linkage.
1124       if (!GV || GV->hasLocalLinkage() || GV->isDeclaration())
1125         continue;
1126       GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
1127                                               : GlobalValue::UnnamedAddr::None);
1128       if (EnableLTOInternalization && R.second.Partition == 0)
1129         GV->setLinkage(GlobalValue::InternalLinkage);
1130     }
1131 
1132     RegularLTO.CombinedModule->addModuleFlag(Module::Error, "LTOPostLink", 1);
1133 
1134     if (Conf.PostInternalizeModuleHook &&
1135         !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
1136       return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
1137   }
1138 
1139   if (!RegularLTO.EmptyCombinedModule || Conf.AlwaysEmitRegularLTOObj) {
1140     if (Error Err =
1141             backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
1142                     *RegularLTO.CombinedModule, ThinLTO.CombinedIndex))
1143       return Err;
1144   }
1145 
1146   return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
1147 }
1148 
1149 static const char *libcallRoutineNames[] = {
1150 #define HANDLE_LIBCALL(code, name) name,
1151 #include "llvm/IR/RuntimeLibcalls.def"
1152 #undef HANDLE_LIBCALL
1153 };
1154 
1155 ArrayRef<const char*> LTO::getRuntimeLibcallSymbols() {
1156   return makeArrayRef(libcallRoutineNames);
1157 }
1158 
1159 /// This class defines the interface to the ThinLTO backend.
1160 class lto::ThinBackendProc {
1161 protected:
1162   const Config &Conf;
1163   ModuleSummaryIndex &CombinedIndex;
1164   const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
1165 
1166 public:
1167   ThinBackendProc(const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1168                   const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
1169       : Conf(Conf), CombinedIndex(CombinedIndex),
1170         ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
1171 
1172   virtual ~ThinBackendProc() {}
1173   virtual Error start(
1174       unsigned Task, BitcodeModule BM,
1175       const FunctionImporter::ImportMapTy &ImportList,
1176       const FunctionImporter::ExportSetTy &ExportList,
1177       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1178       MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
1179   virtual Error wait() = 0;
1180   virtual unsigned getThreadCount() = 0;
1181 };
1182 
1183 namespace {
1184 class InProcessThinBackend : public ThinBackendProc {
1185   ThreadPool BackendThreadPool;
1186   AddStreamFn AddStream;
1187   FileCache Cache;
1188   std::set<GlobalValue::GUID> CfiFunctionDefs;
1189   std::set<GlobalValue::GUID> CfiFunctionDecls;
1190 
1191   Optional<Error> Err;
1192   std::mutex ErrMu;
1193 
1194 public:
1195   InProcessThinBackend(
1196       const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1197       ThreadPoolStrategy ThinLTOParallelism,
1198       const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1199       AddStreamFn AddStream, FileCache Cache)
1200       : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
1201         BackendThreadPool(ThinLTOParallelism), AddStream(std::move(AddStream)),
1202         Cache(std::move(Cache)) {
1203     for (auto &Name : CombinedIndex.cfiFunctionDefs())
1204       CfiFunctionDefs.insert(
1205           GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Name)));
1206     for (auto &Name : CombinedIndex.cfiFunctionDecls())
1207       CfiFunctionDecls.insert(
1208           GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Name)));
1209   }
1210 
1211   Error runThinLTOBackendThread(
1212       AddStreamFn AddStream, FileCache Cache, unsigned Task, BitcodeModule BM,
1213       ModuleSummaryIndex &CombinedIndex,
1214       const FunctionImporter::ImportMapTy &ImportList,
1215       const FunctionImporter::ExportSetTy &ExportList,
1216       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1217       const GVSummaryMapTy &DefinedGlobals,
1218       MapVector<StringRef, BitcodeModule> &ModuleMap) {
1219     auto RunThinBackend = [&](AddStreamFn AddStream) {
1220       LTOLLVMContext BackendContext(Conf);
1221       Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
1222       if (!MOrErr)
1223         return MOrErr.takeError();
1224 
1225       return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
1226                          ImportList, DefinedGlobals, &ModuleMap);
1227     };
1228 
1229     auto ModuleID = BM.getModuleIdentifier();
1230 
1231     if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
1232         all_of(CombinedIndex.getModuleHash(ModuleID),
1233                [](uint32_t V) { return V == 0; }))
1234       // Cache disabled or no entry for this module in the combined index or
1235       // no module hash.
1236       return RunThinBackend(AddStream);
1237 
1238     SmallString<40> Key;
1239     // The module may be cached, this helps handling it.
1240     computeLTOCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList,
1241                        ExportList, ResolvedODR, DefinedGlobals, CfiFunctionDefs,
1242                        CfiFunctionDecls);
1243     Expected<AddStreamFn> CacheAddStreamOrErr = Cache(Task, Key);
1244     if (Error Err = CacheAddStreamOrErr.takeError())
1245       return Err;
1246     AddStreamFn &CacheAddStream = *CacheAddStreamOrErr;
1247     if (CacheAddStream)
1248       return RunThinBackend(CacheAddStream);
1249 
1250     return Error::success();
1251   }
1252 
1253   Error start(
1254       unsigned Task, BitcodeModule BM,
1255       const FunctionImporter::ImportMapTy &ImportList,
1256       const FunctionImporter::ExportSetTy &ExportList,
1257       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1258       MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1259     StringRef ModulePath = BM.getModuleIdentifier();
1260     assert(ModuleToDefinedGVSummaries.count(ModulePath));
1261     const GVSummaryMapTy &DefinedGlobals =
1262         ModuleToDefinedGVSummaries.find(ModulePath)->second;
1263     BackendThreadPool.async(
1264         [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
1265             const FunctionImporter::ImportMapTy &ImportList,
1266             const FunctionImporter::ExportSetTy &ExportList,
1267             const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
1268                 &ResolvedODR,
1269             const GVSummaryMapTy &DefinedGlobals,
1270             MapVector<StringRef, BitcodeModule> &ModuleMap) {
1271           if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled)
1272             timeTraceProfilerInitialize(Conf.TimeTraceGranularity,
1273                                         "thin backend");
1274           Error E = runThinLTOBackendThread(
1275               AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
1276               ResolvedODR, DefinedGlobals, ModuleMap);
1277           if (E) {
1278             std::unique_lock<std::mutex> L(ErrMu);
1279             if (Err)
1280               Err = joinErrors(std::move(*Err), std::move(E));
1281             else
1282               Err = std::move(E);
1283           }
1284           if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled)
1285             timeTraceProfilerFinishThread();
1286         },
1287         BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList),
1288         std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap));
1289     return Error::success();
1290   }
1291 
1292   Error wait() override {
1293     BackendThreadPool.wait();
1294     if (Err)
1295       return std::move(*Err);
1296     else
1297       return Error::success();
1298   }
1299 
1300   unsigned getThreadCount() override {
1301     return BackendThreadPool.getThreadCount();
1302   }
1303 };
1304 } // end anonymous namespace
1305 
1306 ThinBackend lto::createInProcessThinBackend(ThreadPoolStrategy Parallelism) {
1307   return [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1308              const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1309              AddStreamFn AddStream, FileCache Cache) {
1310     return std::make_unique<InProcessThinBackend>(
1311         Conf, CombinedIndex, Parallelism, ModuleToDefinedGVSummaries, AddStream,
1312         Cache);
1313   };
1314 }
1315 
1316 // Given the original \p Path to an output file, replace any path
1317 // prefix matching \p OldPrefix with \p NewPrefix. Also, create the
1318 // resulting directory if it does not yet exist.
1319 std::string lto::getThinLTOOutputFile(const std::string &Path,
1320                                       const std::string &OldPrefix,
1321                                       const std::string &NewPrefix) {
1322   if (OldPrefix.empty() && NewPrefix.empty())
1323     return Path;
1324   SmallString<128> NewPath(Path);
1325   llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
1326   StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
1327   if (!ParentPath.empty()) {
1328     // Make sure the new directory exists, creating it if necessary.
1329     if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
1330       llvm::errs() << "warning: could not create directory '" << ParentPath
1331                    << "': " << EC.message() << '\n';
1332   }
1333   return std::string(NewPath.str());
1334 }
1335 
1336 namespace {
1337 class WriteIndexesThinBackend : public ThinBackendProc {
1338   std::string OldPrefix, NewPrefix;
1339   bool ShouldEmitImportsFiles;
1340   raw_fd_ostream *LinkedObjectsFile;
1341   lto::IndexWriteCallback OnWrite;
1342 
1343 public:
1344   WriteIndexesThinBackend(
1345       const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1346       const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1347       std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
1348       raw_fd_ostream *LinkedObjectsFile, lto::IndexWriteCallback OnWrite)
1349       : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
1350         OldPrefix(OldPrefix), NewPrefix(NewPrefix),
1351         ShouldEmitImportsFiles(ShouldEmitImportsFiles),
1352         LinkedObjectsFile(LinkedObjectsFile), OnWrite(OnWrite) {}
1353 
1354   Error start(
1355       unsigned Task, BitcodeModule BM,
1356       const FunctionImporter::ImportMapTy &ImportList,
1357       const FunctionImporter::ExportSetTy &ExportList,
1358       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1359       MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1360     StringRef ModulePath = BM.getModuleIdentifier();
1361     std::string NewModulePath =
1362         getThinLTOOutputFile(std::string(ModulePath), OldPrefix, NewPrefix);
1363 
1364     if (LinkedObjectsFile)
1365       *LinkedObjectsFile << NewModulePath << '\n';
1366 
1367     std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
1368     gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
1369                                      ImportList, ModuleToSummariesForIndex);
1370 
1371     std::error_code EC;
1372     raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
1373                       sys::fs::OpenFlags::OF_None);
1374     if (EC)
1375       return errorCodeToError(EC);
1376     writeIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
1377 
1378     if (ShouldEmitImportsFiles) {
1379       EC = EmitImportsFiles(ModulePath, NewModulePath + ".imports",
1380                             ModuleToSummariesForIndex);
1381       if (EC)
1382         return errorCodeToError(EC);
1383     }
1384 
1385     if (OnWrite)
1386       OnWrite(std::string(ModulePath));
1387     return Error::success();
1388   }
1389 
1390   Error wait() override { return Error::success(); }
1391 
1392   // WriteIndexesThinBackend should always return 1 to prevent module
1393   // re-ordering and avoid non-determinism in the final link.
1394   unsigned getThreadCount() override { return 1; }
1395 };
1396 } // end anonymous namespace
1397 
1398 ThinBackend lto::createWriteIndexesThinBackend(
1399     std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
1400     raw_fd_ostream *LinkedObjectsFile, IndexWriteCallback OnWrite) {
1401   return [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1402              const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1403              AddStreamFn AddStream, FileCache Cache) {
1404     return std::make_unique<WriteIndexesThinBackend>(
1405         Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
1406         ShouldEmitImportsFiles, LinkedObjectsFile, OnWrite);
1407   };
1408 }
1409 
1410 Error LTO::runThinLTO(AddStreamFn AddStream, FileCache Cache,
1411                       const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
1412   timeTraceProfilerBegin("ThinLink", StringRef(""));
1413   auto TimeTraceScopeExit = llvm::make_scope_exit([]() {
1414     if (llvm::timeTraceProfilerEnabled())
1415       llvm::timeTraceProfilerEnd();
1416   });
1417   if (ThinLTO.ModuleMap.empty())
1418     return Error::success();
1419 
1420   if (ThinLTO.ModulesToCompile && ThinLTO.ModulesToCompile->empty()) {
1421     llvm::errs() << "warning: [ThinLTO] No module compiled\n";
1422     return Error::success();
1423   }
1424 
1425   if (Conf.CombinedIndexHook &&
1426       !Conf.CombinedIndexHook(ThinLTO.CombinedIndex, GUIDPreservedSymbols))
1427     return Error::success();
1428 
1429   // Collect for each module the list of function it defines (GUID ->
1430   // Summary).
1431   StringMap<GVSummaryMapTy>
1432       ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
1433   ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
1434       ModuleToDefinedGVSummaries);
1435   // Create entries for any modules that didn't have any GV summaries
1436   // (either they didn't have any GVs to start with, or we suppressed
1437   // generation of the summaries because they e.g. had inline assembly
1438   // uses that couldn't be promoted/renamed on export). This is so
1439   // InProcessThinBackend::start can still launch a backend thread, which
1440   // is passed the map of summaries for the module, without any special
1441   // handling for this case.
1442   for (auto &Mod : ThinLTO.ModuleMap)
1443     if (!ModuleToDefinedGVSummaries.count(Mod.first))
1444       ModuleToDefinedGVSummaries.try_emplace(Mod.first);
1445 
1446   // Synthesize entry counts for functions in the CombinedIndex.
1447   computeSyntheticCounts(ThinLTO.CombinedIndex);
1448 
1449   StringMap<FunctionImporter::ImportMapTy> ImportLists(
1450       ThinLTO.ModuleMap.size());
1451   StringMap<FunctionImporter::ExportSetTy> ExportLists(
1452       ThinLTO.ModuleMap.size());
1453   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
1454 
1455   if (DumpThinCGSCCs)
1456     ThinLTO.CombinedIndex.dumpSCCs(outs());
1457 
1458   std::set<GlobalValue::GUID> ExportedGUIDs;
1459 
1460   // If allowed, upgrade public vcall visibility to linkage unit visibility in
1461   // the summaries before whole program devirtualization below.
1462   updateVCallVisibilityInIndex(ThinLTO.CombinedIndex,
1463                                Conf.HasWholeProgramVisibility,
1464                                DynamicExportSymbols);
1465 
1466   // Perform index-based WPD. This will return immediately if there are
1467   // no index entries in the typeIdMetadata map (e.g. if we are instead
1468   // performing IR-based WPD in hybrid regular/thin LTO mode).
1469   std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
1470   runWholeProgramDevirtOnIndex(ThinLTO.CombinedIndex, ExportedGUIDs,
1471                                LocalWPDTargetsMap);
1472 
1473   if (Conf.OptLevel > 0)
1474     ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
1475                              ImportLists, ExportLists);
1476 
1477   // Figure out which symbols need to be internalized. This also needs to happen
1478   // at -O0 because summary-based DCE is implemented using internalization, and
1479   // we must apply DCE consistently with the full LTO module in order to avoid
1480   // undefined references during the final link.
1481   for (auto &Res : GlobalResolutions) {
1482     // If the symbol does not have external references or it is not prevailing,
1483     // then not need to mark it as exported from a ThinLTO partition.
1484     if (Res.second.Partition != GlobalResolution::External ||
1485         !Res.second.isPrevailingIRSymbol())
1486       continue;
1487     auto GUID = GlobalValue::getGUID(
1488         GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
1489     // Mark exported unless index-based analysis determined it to be dead.
1490     if (ThinLTO.CombinedIndex.isGUIDLive(GUID))
1491       ExportedGUIDs.insert(GUID);
1492   }
1493 
1494   // Any functions referenced by the jump table in the regular LTO object must
1495   // be exported.
1496   for (auto &Def : ThinLTO.CombinedIndex.cfiFunctionDefs())
1497     ExportedGUIDs.insert(
1498         GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Def)));
1499   for (auto &Decl : ThinLTO.CombinedIndex.cfiFunctionDecls())
1500     ExportedGUIDs.insert(
1501         GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Decl)));
1502 
1503   auto isExported = [&](StringRef ModuleIdentifier, ValueInfo VI) {
1504     const auto &ExportList = ExportLists.find(ModuleIdentifier);
1505     return (ExportList != ExportLists.end() && ExportList->second.count(VI)) ||
1506            ExportedGUIDs.count(VI.getGUID());
1507   };
1508 
1509   // Update local devirtualized targets that were exported by cross-module
1510   // importing or by other devirtualizations marked in the ExportedGUIDs set.
1511   updateIndexWPDForExports(ThinLTO.CombinedIndex, isExported,
1512                            LocalWPDTargetsMap);
1513 
1514   auto isPrevailing = [&](GlobalValue::GUID GUID,
1515                           const GlobalValueSummary *S) {
1516     return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
1517   };
1518   thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported,
1519                                       isPrevailing);
1520 
1521   auto recordNewLinkage = [&](StringRef ModuleIdentifier,
1522                               GlobalValue::GUID GUID,
1523                               GlobalValue::LinkageTypes NewLinkage) {
1524     ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
1525   };
1526   thinLTOResolvePrevailingInIndex(Conf, ThinLTO.CombinedIndex, isPrevailing,
1527                                   recordNewLinkage, GUIDPreservedSymbols);
1528 
1529   thinLTOPropagateFunctionAttrs(ThinLTO.CombinedIndex, isPrevailing);
1530 
1531   generateParamAccessSummary(ThinLTO.CombinedIndex);
1532 
1533   if (llvm::timeTraceProfilerEnabled())
1534     llvm::timeTraceProfilerEnd();
1535 
1536   TimeTraceScopeExit.release();
1537 
1538   std::unique_ptr<ThinBackendProc> BackendProc =
1539       ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
1540                       AddStream, Cache);
1541 
1542   auto &ModuleMap =
1543       ThinLTO.ModulesToCompile ? *ThinLTO.ModulesToCompile : ThinLTO.ModuleMap;
1544 
1545   auto ProcessOneModule = [&](int I) -> Error {
1546     auto &Mod = *(ModuleMap.begin() + I);
1547     // Tasks 0 through ParallelCodeGenParallelismLevel-1 are reserved for
1548     // combined module and parallel code generation partitions.
1549     return BackendProc->start(RegularLTO.ParallelCodeGenParallelismLevel + I,
1550                               Mod.second, ImportLists[Mod.first],
1551                               ExportLists[Mod.first], ResolvedODR[Mod.first],
1552                               ThinLTO.ModuleMap);
1553   };
1554 
1555   if (BackendProc->getThreadCount() == 1) {
1556     // Process the modules in the order they were provided on the command-line.
1557     // It is important for this codepath to be used for WriteIndexesThinBackend,
1558     // to ensure the emitted LinkedObjectsFile lists ThinLTO objects in the same
1559     // order as the inputs, which otherwise would affect the final link order.
1560     for (int I = 0, E = ModuleMap.size(); I != E; ++I)
1561       if (Error E = ProcessOneModule(I))
1562         return E;
1563   } else {
1564     // When executing in parallel, process largest bitsize modules first to
1565     // improve parallelism, and avoid starving the thread pool near the end.
1566     // This saves about 15 sec on a 36-core machine while link `clang.exe` (out
1567     // of 100 sec).
1568     std::vector<BitcodeModule *> ModulesVec;
1569     ModulesVec.reserve(ModuleMap.size());
1570     for (auto &Mod : ModuleMap)
1571       ModulesVec.push_back(&Mod.second);
1572     for (int I : generateModulesOrdering(ModulesVec))
1573       if (Error E = ProcessOneModule(I))
1574         return E;
1575   }
1576   return BackendProc->wait();
1577 }
1578 
1579 Expected<std::unique_ptr<ToolOutputFile>> lto::setupLLVMOptimizationRemarks(
1580     LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses,
1581     StringRef RemarksFormat, bool RemarksWithHotness,
1582     Optional<uint64_t> RemarksHotnessThreshold, int Count) {
1583   std::string Filename = std::string(RemarksFilename);
1584   // For ThinLTO, file.opt.<format> becomes
1585   // file.opt.<format>.thin.<num>.<format>.
1586   if (!Filename.empty() && Count != -1)
1587     Filename =
1588         (Twine(Filename) + ".thin." + llvm::utostr(Count) + "." + RemarksFormat)
1589             .str();
1590 
1591   auto ResultOrErr = llvm::setupLLVMOptimizationRemarks(
1592       Context, Filename, RemarksPasses, RemarksFormat, RemarksWithHotness,
1593       RemarksHotnessThreshold);
1594   if (Error E = ResultOrErr.takeError())
1595     return std::move(E);
1596 
1597   if (*ResultOrErr)
1598     (*ResultOrErr)->keep();
1599 
1600   return ResultOrErr;
1601 }
1602 
1603 Expected<std::unique_ptr<ToolOutputFile>>
1604 lto::setupStatsFile(StringRef StatsFilename) {
1605   // Setup output file to emit statistics.
1606   if (StatsFilename.empty())
1607     return nullptr;
1608 
1609   llvm::EnableStatistics(false);
1610   std::error_code EC;
1611   auto StatsFile =
1612       std::make_unique<ToolOutputFile>(StatsFilename, EC, sys::fs::OF_None);
1613   if (EC)
1614     return errorCodeToError(EC);
1615 
1616   StatsFile->keep();
1617   return std::move(StatsFile);
1618 }
1619 
1620 // Compute the ordering we will process the inputs: the rough heuristic here
1621 // is to sort them per size so that the largest module get schedule as soon as
1622 // possible. This is purely a compile-time optimization.
1623 std::vector<int> lto::generateModulesOrdering(ArrayRef<BitcodeModule *> R) {
1624   std::vector<int> ModulesOrdering;
1625   ModulesOrdering.resize(R.size());
1626   std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
1627   llvm::sort(ModulesOrdering, [&](int LeftIndex, int RightIndex) {
1628     auto LSize = R[LeftIndex]->getBuffer().size();
1629     auto RSize = R[RightIndex]->getBuffer().size();
1630     return LSize > RSize;
1631   });
1632   return ModulesOrdering;
1633 }
1634