xref: /llvm-project/llvm/lib/LTO/LTO.cpp (revision 6924fc03260370876f7091ba06cdc350989ac3c5)
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/StableHashing.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
20 #include "llvm/Analysis/StackSafetyAnalysis.h"
21 #include "llvm/Analysis/TargetLibraryInfo.h"
22 #include "llvm/Analysis/TargetTransformInfo.h"
23 #include "llvm/Bitcode/BitcodeReader.h"
24 #include "llvm/Bitcode/BitcodeWriter.h"
25 #include "llvm/CGData/CodeGenData.h"
26 #include "llvm/CodeGen/Analysis.h"
27 #include "llvm/Config/llvm-config.h"
28 #include "llvm/IR/AutoUpgrade.h"
29 #include "llvm/IR/DiagnosticPrinter.h"
30 #include "llvm/IR/Intrinsics.h"
31 #include "llvm/IR/LLVMRemarkStreamer.h"
32 #include "llvm/IR/LegacyPassManager.h"
33 #include "llvm/IR/Mangler.h"
34 #include "llvm/IR/Metadata.h"
35 #include "llvm/IR/RuntimeLibcalls.h"
36 #include "llvm/LTO/LTOBackend.h"
37 #include "llvm/Linker/IRMover.h"
38 #include "llvm/MC/TargetRegistry.h"
39 #include "llvm/Object/IRObjectFile.h"
40 #include "llvm/Support/Caching.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Error.h"
43 #include "llvm/Support/FileSystem.h"
44 #include "llvm/Support/MemoryBuffer.h"
45 #include "llvm/Support/Path.h"
46 #include "llvm/Support/SHA1.h"
47 #include "llvm/Support/SourceMgr.h"
48 #include "llvm/Support/ThreadPool.h"
49 #include "llvm/Support/Threading.h"
50 #include "llvm/Support/TimeProfiler.h"
51 #include "llvm/Support/ToolOutputFile.h"
52 #include "llvm/Support/VCSRevision.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetOptions.h"
55 #include "llvm/Transforms/IPO.h"
56 #include "llvm/Transforms/IPO/MemProfContextDisambiguation.h"
57 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
58 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
59 #include "llvm/Transforms/Utils/SplitModule.h"
60 
61 #include <optional>
62 #include <set>
63 
64 using namespace llvm;
65 using namespace lto;
66 using namespace object;
67 
68 #define DEBUG_TYPE "lto"
69 
70 extern cl::opt<bool> UseNewDbgInfoFormat;
71 
72 static cl::opt<bool>
73     DumpThinCGSCCs("dump-thin-cg-sccs", cl::init(false), cl::Hidden,
74                    cl::desc("Dump the SCCs in the ThinLTO index's callgraph"));
75 
76 extern cl::opt<bool> CodeGenDataThinLTOTwoRounds;
77 
78 namespace llvm {
79 /// Enable global value internalization in LTO.
80 cl::opt<bool> EnableLTOInternalization(
81     "enable-lto-internalization", cl::init(true), cl::Hidden,
82     cl::desc("Enable global value internalization in LTO"));
83 
84 static cl::opt<bool>
85     LTOKeepSymbolCopies("lto-keep-symbol-copies", cl::init(false), cl::Hidden,
86                         cl::desc("Keep copies of symbols in LTO indexing"));
87 
88 /// Indicate we are linking with an allocator that supports hot/cold operator
89 /// new interfaces.
90 extern cl::opt<bool> SupportsHotColdNew;
91 
92 /// Enable MemProf context disambiguation for thin link.
93 extern cl::opt<bool> EnableMemProfContextDisambiguation;
94 } // namespace llvm
95 
96 // Computes a unique hash for the Module considering the current list of
97 // export/import and other global analysis results.
98 // Returns the hash in its hexadecimal representation.
99 std::string llvm::computeLTOCacheKey(
100     const Config &Conf, const ModuleSummaryIndex &Index, StringRef ModuleID,
101     const FunctionImporter::ImportMapTy &ImportList,
102     const FunctionImporter::ExportSetTy &ExportList,
103     const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
104     const GVSummaryMapTy &DefinedGlobals,
105     const DenseSet<GlobalValue::GUID> &CfiFunctionDefs,
106     const DenseSet<GlobalValue::GUID> &CfiFunctionDecls) {
107   // Compute the unique hash for this entry.
108   // This is based on the current compiler version, the module itself, the
109   // export list, the hash for every single module in the import list, the
110   // list of ResolvedODR for the module, and the list of preserved symbols.
111   SHA1 Hasher;
112 
113   // Start with the compiler revision
114   Hasher.update(LLVM_VERSION_STRING);
115 #ifdef LLVM_REVISION
116   Hasher.update(LLVM_REVISION);
117 #endif
118 
119   // Include the parts of the LTO configuration that affect code generation.
120   auto AddString = [&](StringRef Str) {
121     Hasher.update(Str);
122     Hasher.update(ArrayRef<uint8_t>{0});
123   };
124   auto AddUnsigned = [&](unsigned I) {
125     uint8_t Data[4];
126     support::endian::write32le(Data, I);
127     Hasher.update(Data);
128   };
129   auto AddUint64 = [&](uint64_t I) {
130     uint8_t Data[8];
131     support::endian::write64le(Data, I);
132     Hasher.update(Data);
133   };
134   auto AddUint8 = [&](const uint8_t I) {
135     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&I, 1));
136   };
137   AddString(Conf.CPU);
138   // FIXME: Hash more of Options. For now all clients initialize Options from
139   // command-line flags (which is unsupported in production), but may set
140   // X86RelaxRelocations. The clang driver can also pass FunctionSections,
141   // DataSections and DebuggerTuning via command line flags.
142   AddUnsigned(Conf.Options.MCOptions.X86RelaxRelocations);
143   AddUnsigned(Conf.Options.FunctionSections);
144   AddUnsigned(Conf.Options.DataSections);
145   AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
146   for (auto &A : Conf.MAttrs)
147     AddString(A);
148   if (Conf.RelocModel)
149     AddUnsigned(*Conf.RelocModel);
150   else
151     AddUnsigned(-1);
152   if (Conf.CodeModel)
153     AddUnsigned(*Conf.CodeModel);
154   else
155     AddUnsigned(-1);
156   for (const auto &S : Conf.MllvmArgs)
157     AddString(S);
158   AddUnsigned(static_cast<int>(Conf.CGOptLevel));
159   AddUnsigned(static_cast<int>(Conf.CGFileType));
160   AddUnsigned(Conf.OptLevel);
161   AddUnsigned(Conf.Freestanding);
162   AddString(Conf.OptPipeline);
163   AddString(Conf.AAPipeline);
164   AddString(Conf.OverrideTriple);
165   AddString(Conf.DefaultTriple);
166   AddString(Conf.DwoDir);
167 
168   // Include the hash for the current module
169   auto ModHash = Index.getModuleHash(ModuleID);
170   Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
171 
172   // TODO: `ExportList` is determined by `ImportList`. Since `ImportList` is
173   // used to compute cache key, we could omit hashing `ExportList` here.
174   std::vector<uint64_t> ExportsGUID;
175   ExportsGUID.reserve(ExportList.size());
176   for (const auto &VI : ExportList)
177     ExportsGUID.push_back(VI.getGUID());
178 
179   // Sort the export list elements GUIDs.
180   llvm::sort(ExportsGUID);
181   for (auto GUID : ExportsGUID)
182     Hasher.update(ArrayRef<uint8_t>((uint8_t *)&GUID, sizeof(GUID)));
183 
184   // Order using module hash, to be both independent of module name and
185   // module order.
186   auto Comp = [&](const std::pair<StringRef, GlobalValue::GUID> &L,
187                   const std::pair<StringRef, GlobalValue::GUID> &R) {
188     return std::make_pair(Index.getModule(L.first)->second, L.second) <
189            std::make_pair(Index.getModule(R.first)->second, R.second);
190   };
191   FunctionImporter::SortedImportList SortedImportList(ImportList, Comp);
192 
193   // Count the number of imports for each source module.
194   DenseMap<StringRef, unsigned> ModuleToNumImports;
195   for (const auto &[FromModule, GUID, Type] : SortedImportList)
196     ++ModuleToNumImports[FromModule];
197 
198   std::optional<StringRef> LastModule;
199   for (const auto &[FromModule, GUID, Type] : SortedImportList) {
200     if (LastModule != FromModule) {
201       // Include the hash for every module we import functions from. The set of
202       // imported symbols for each module may affect code generation and is
203       // sensitive to link order, so include that as well.
204       LastModule = FromModule;
205       auto ModHash = Index.getModule(FromModule)->second;
206       Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
207       AddUint64(ModuleToNumImports[FromModule]);
208     }
209     AddUint64(GUID);
210     AddUint8(Type);
211   }
212 
213   // Include the hash for the resolved ODR.
214   for (auto &Entry : ResolvedODR) {
215     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
216                                     sizeof(GlobalValue::GUID)));
217     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
218                                     sizeof(GlobalValue::LinkageTypes)));
219   }
220 
221   // Members of CfiFunctionDefs and CfiFunctionDecls that are referenced or
222   // defined in this module.
223   std::set<GlobalValue::GUID> UsedCfiDefs;
224   std::set<GlobalValue::GUID> UsedCfiDecls;
225 
226   // Typeids used in this module.
227   std::set<GlobalValue::GUID> UsedTypeIds;
228 
229   auto AddUsedCfiGlobal = [&](GlobalValue::GUID ValueGUID) {
230     if (CfiFunctionDefs.contains(ValueGUID))
231       UsedCfiDefs.insert(ValueGUID);
232     if (CfiFunctionDecls.contains(ValueGUID))
233       UsedCfiDecls.insert(ValueGUID);
234   };
235 
236   auto AddUsedThings = [&](GlobalValueSummary *GS) {
237     if (!GS) return;
238     AddUnsigned(GS->getVisibility());
239     AddUnsigned(GS->isLive());
240     AddUnsigned(GS->canAutoHide());
241     for (const ValueInfo &VI : GS->refs()) {
242       AddUnsigned(VI.isDSOLocal(Index.withDSOLocalPropagation()));
243       AddUsedCfiGlobal(VI.getGUID());
244     }
245     if (auto *GVS = dyn_cast<GlobalVarSummary>(GS)) {
246       AddUnsigned(GVS->maybeReadOnly());
247       AddUnsigned(GVS->maybeWriteOnly());
248     }
249     if (auto *FS = dyn_cast<FunctionSummary>(GS)) {
250       for (auto &TT : FS->type_tests())
251         UsedTypeIds.insert(TT);
252       for (auto &TT : FS->type_test_assume_vcalls())
253         UsedTypeIds.insert(TT.GUID);
254       for (auto &TT : FS->type_checked_load_vcalls())
255         UsedTypeIds.insert(TT.GUID);
256       for (auto &TT : FS->type_test_assume_const_vcalls())
257         UsedTypeIds.insert(TT.VFunc.GUID);
258       for (auto &TT : FS->type_checked_load_const_vcalls())
259         UsedTypeIds.insert(TT.VFunc.GUID);
260       for (auto &ET : FS->calls()) {
261         AddUnsigned(ET.first.isDSOLocal(Index.withDSOLocalPropagation()));
262         AddUsedCfiGlobal(ET.first.getGUID());
263       }
264     }
265   };
266 
267   // Include the hash for the linkage type to reflect internalization and weak
268   // resolution, and collect any used type identifier resolutions.
269   for (auto &GS : DefinedGlobals) {
270     GlobalValue::LinkageTypes Linkage = GS.second->linkage();
271     Hasher.update(
272         ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
273     AddUsedCfiGlobal(GS.first);
274     AddUsedThings(GS.second);
275   }
276 
277   // Imported functions may introduce new uses of type identifier resolutions,
278   // so we need to collect their used resolutions as well.
279   for (const auto &[FromModule, GUID, Type] : SortedImportList) {
280     GlobalValueSummary *S = Index.findSummaryInModule(GUID, FromModule);
281     AddUsedThings(S);
282     // If this is an alias, we also care about any types/etc. that the aliasee
283     // may reference.
284     if (auto *AS = dyn_cast_or_null<AliasSummary>(S))
285       AddUsedThings(AS->getBaseObject());
286   }
287 
288   auto AddTypeIdSummary = [&](StringRef TId, const TypeIdSummary &S) {
289     AddString(TId);
290 
291     AddUnsigned(S.TTRes.TheKind);
292     AddUnsigned(S.TTRes.SizeM1BitWidth);
293 
294     AddUint64(S.TTRes.AlignLog2);
295     AddUint64(S.TTRes.SizeM1);
296     AddUint64(S.TTRes.BitMask);
297     AddUint64(S.TTRes.InlineBits);
298 
299     AddUint64(S.WPDRes.size());
300     for (auto &WPD : S.WPDRes) {
301       AddUnsigned(WPD.first);
302       AddUnsigned(WPD.second.TheKind);
303       AddString(WPD.second.SingleImplName);
304 
305       AddUint64(WPD.second.ResByArg.size());
306       for (auto &ByArg : WPD.second.ResByArg) {
307         AddUint64(ByArg.first.size());
308         for (uint64_t Arg : ByArg.first)
309           AddUint64(Arg);
310         AddUnsigned(ByArg.second.TheKind);
311         AddUint64(ByArg.second.Info);
312         AddUnsigned(ByArg.second.Byte);
313         AddUnsigned(ByArg.second.Bit);
314       }
315     }
316   };
317 
318   // Include the hash for all type identifiers used by this module.
319   for (GlobalValue::GUID TId : UsedTypeIds) {
320     auto TidIter = Index.typeIds().equal_range(TId);
321     for (const auto &I : make_range(TidIter))
322       AddTypeIdSummary(I.second.first, I.second.second);
323   }
324 
325   AddUnsigned(UsedCfiDefs.size());
326   for (auto &V : UsedCfiDefs)
327     AddUint64(V);
328 
329   AddUnsigned(UsedCfiDecls.size());
330   for (auto &V : UsedCfiDecls)
331     AddUint64(V);
332 
333   if (!Conf.SampleProfile.empty()) {
334     auto FileOrErr = MemoryBuffer::getFile(Conf.SampleProfile);
335     if (FileOrErr) {
336       Hasher.update(FileOrErr.get()->getBuffer());
337 
338       if (!Conf.ProfileRemapping.empty()) {
339         FileOrErr = MemoryBuffer::getFile(Conf.ProfileRemapping);
340         if (FileOrErr)
341           Hasher.update(FileOrErr.get()->getBuffer());
342       }
343     }
344   }
345 
346   return toHex(Hasher.result());
347 }
348 
349 std::string llvm::recomputeLTOCacheKey(const std::string &Key,
350                                        StringRef ExtraID) {
351   SHA1 Hasher;
352 
353   auto AddString = [&](StringRef Str) {
354     Hasher.update(Str);
355     Hasher.update(ArrayRef<uint8_t>{0});
356   };
357   AddString(Key);
358   AddString(ExtraID);
359 
360   return toHex(Hasher.result());
361 }
362 
363 static void thinLTOResolvePrevailingGUID(
364     const Config &C, ValueInfo VI,
365     DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
366     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
367         isPrevailing,
368     function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
369         recordNewLinkage,
370     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
371   GlobalValue::VisibilityTypes Visibility =
372       C.VisibilityScheme == Config::ELF ? VI.getELFVisibility()
373                                         : GlobalValue::DefaultVisibility;
374   for (auto &S : VI.getSummaryList()) {
375     GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
376     // Ignore local and appending linkage values since the linker
377     // doesn't resolve them.
378     if (GlobalValue::isLocalLinkage(OriginalLinkage) ||
379         GlobalValue::isAppendingLinkage(S->linkage()))
380       continue;
381     // We need to emit only one of these. The prevailing module will keep it,
382     // but turned into a weak, while the others will drop it when possible.
383     // This is both a compile-time optimization and a correctness
384     // transformation. This is necessary for correctness when we have exported
385     // a reference - we need to convert the linkonce to weak to
386     // ensure a copy is kept to satisfy the exported reference.
387     // FIXME: We may want to split the compile time and correctness
388     // aspects into separate routines.
389     if (isPrevailing(VI.getGUID(), S.get())) {
390       if (GlobalValue::isLinkOnceLinkage(OriginalLinkage)) {
391         S->setLinkage(GlobalValue::getWeakLinkage(
392             GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
393         // The kept copy is eligible for auto-hiding (hidden visibility) if all
394         // copies were (i.e. they were all linkonce_odr global unnamed addr).
395         // If any copy is not (e.g. it was originally weak_odr), then the symbol
396         // must remain externally available (e.g. a weak_odr from an explicitly
397         // instantiated template). Additionally, if it is in the
398         // GUIDPreservedSymbols set, that means that it is visibile outside
399         // the summary (e.g. in a native object or a bitcode file without
400         // summary), and in that case we cannot hide it as it isn't possible to
401         // check all copies.
402         S->setCanAutoHide(VI.canAutoHide() &&
403                           !GUIDPreservedSymbols.count(VI.getGUID()));
404       }
405       if (C.VisibilityScheme == Config::FromPrevailing)
406         Visibility = S->getVisibility();
407     }
408     // Alias and aliasee can't be turned into available_externally.
409     else if (!isa<AliasSummary>(S.get()) &&
410              !GlobalInvolvedWithAlias.count(S.get()))
411       S->setLinkage(GlobalValue::AvailableExternallyLinkage);
412 
413     // For ELF, set visibility to the computed visibility from summaries. We
414     // don't track visibility from declarations so this may be more relaxed than
415     // the most constraining one.
416     if (C.VisibilityScheme == Config::ELF)
417       S->setVisibility(Visibility);
418 
419     if (S->linkage() != OriginalLinkage)
420       recordNewLinkage(S->modulePath(), VI.getGUID(), S->linkage());
421   }
422 
423   if (C.VisibilityScheme == Config::FromPrevailing) {
424     for (auto &S : VI.getSummaryList()) {
425       GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
426       if (GlobalValue::isLocalLinkage(OriginalLinkage) ||
427           GlobalValue::isAppendingLinkage(S->linkage()))
428         continue;
429       S->setVisibility(Visibility);
430     }
431   }
432 }
433 
434 /// Resolve linkage for prevailing symbols in the \p Index.
435 //
436 // We'd like to drop these functions if they are no longer referenced in the
437 // current module. However there is a chance that another module is still
438 // referencing them because of the import. We make sure we always emit at least
439 // one copy.
440 void llvm::thinLTOResolvePrevailingInIndex(
441     const Config &C, ModuleSummaryIndex &Index,
442     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
443         isPrevailing,
444     function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
445         recordNewLinkage,
446     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
447   // We won't optimize the globals that are referenced by an alias for now
448   // Ideally we should turn the alias into a global and duplicate the definition
449   // when needed.
450   DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
451   for (auto &I : Index)
452     for (auto &S : I.second.SummaryList)
453       if (auto AS = dyn_cast<AliasSummary>(S.get()))
454         GlobalInvolvedWithAlias.insert(&AS->getAliasee());
455 
456   for (auto &I : Index)
457     thinLTOResolvePrevailingGUID(C, Index.getValueInfo(I),
458                                  GlobalInvolvedWithAlias, isPrevailing,
459                                  recordNewLinkage, GUIDPreservedSymbols);
460 }
461 
462 static void thinLTOInternalizeAndPromoteGUID(
463     ValueInfo VI, function_ref<bool(StringRef, ValueInfo)> isExported,
464     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
465         isPrevailing) {
466   auto ExternallyVisibleCopies =
467       llvm::count_if(VI.getSummaryList(),
468                      [](const std::unique_ptr<GlobalValueSummary> &Summary) {
469                        return !GlobalValue::isLocalLinkage(Summary->linkage());
470                      });
471 
472   for (auto &S : VI.getSummaryList()) {
473     // First see if we need to promote an internal value because it is not
474     // exported.
475     if (isExported(S->modulePath(), VI)) {
476       if (GlobalValue::isLocalLinkage(S->linkage()))
477         S->setLinkage(GlobalValue::ExternalLinkage);
478       continue;
479     }
480 
481     // Otherwise, see if we can internalize.
482     if (!EnableLTOInternalization)
483       continue;
484 
485     // Non-exported values with external linkage can be internalized.
486     if (GlobalValue::isExternalLinkage(S->linkage())) {
487       S->setLinkage(GlobalValue::InternalLinkage);
488       continue;
489     }
490 
491     // Non-exported function and variable definitions with a weak-for-linker
492     // linkage can be internalized in certain cases. The minimum legality
493     // requirements would be that they are not address taken to ensure that we
494     // don't break pointer equality checks, and that variables are either read-
495     // or write-only. For functions, this is the case if either all copies are
496     // [local_]unnamed_addr, or we can propagate reference edge attributes
497     // (which is how this is guaranteed for variables, when analyzing whether
498     // they are read or write-only).
499     //
500     // However, we only get to this code for weak-for-linkage values in one of
501     // two cases:
502     // 1) The prevailing copy is not in IR (it is in native code).
503     // 2) The prevailing copy in IR is not exported from its module.
504     // Additionally, at least for the new LTO API, case 2 will only happen if
505     // there is exactly one definition of the value (i.e. in exactly one
506     // module), as duplicate defs are result in the value being marked exported.
507     // Likely, users of the legacy LTO API are similar, however, currently there
508     // are llvm-lto based tests of the legacy LTO API that do not mark
509     // duplicate linkonce_odr copies as exported via the tool, so we need
510     // to handle that case below by checking the number of copies.
511     //
512     // Generally, we only want to internalize a weak-for-linker value in case
513     // 2, because in case 1 we cannot see how the value is used to know if it
514     // is read or write-only. We also don't want to bloat the binary with
515     // multiple internalized copies of non-prevailing linkonce/weak functions.
516     // Note if we don't internalize, we will convert non-prevailing copies to
517     // available_externally anyway, so that we drop them after inlining. The
518     // only reason to internalize such a function is if we indeed have a single
519     // copy, because internalizing it won't increase binary size, and enables
520     // use of inliner heuristics that are more aggressive in the face of a
521     // single call to a static (local). For variables, internalizing a read or
522     // write only variable can enable more aggressive optimization. However, we
523     // already perform this elsewhere in the ThinLTO backend handling for
524     // read or write-only variables (processGlobalForThinLTO).
525     //
526     // Therefore, only internalize linkonce/weak if there is a single copy, that
527     // is prevailing in this IR module. We can do so aggressively, without
528     // requiring the address to be insignificant, or that a variable be read or
529     // write-only.
530     if (!GlobalValue::isWeakForLinker(S->linkage()) ||
531         GlobalValue::isExternalWeakLinkage(S->linkage()))
532       continue;
533 
534     if (isPrevailing(VI.getGUID(), S.get()) && ExternallyVisibleCopies == 1)
535       S->setLinkage(GlobalValue::InternalLinkage);
536   }
537 }
538 
539 // Update the linkages in the given \p Index to mark exported values
540 // as external and non-exported values as internal.
541 void llvm::thinLTOInternalizeAndPromoteInIndex(
542     ModuleSummaryIndex &Index,
543     function_ref<bool(StringRef, ValueInfo)> isExported,
544     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
545         isPrevailing) {
546   for (auto &I : Index)
547     thinLTOInternalizeAndPromoteGUID(Index.getValueInfo(I), isExported,
548                                      isPrevailing);
549 }
550 
551 // Requires a destructor for std::vector<InputModule>.
552 InputFile::~InputFile() = default;
553 
554 Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
555   std::unique_ptr<InputFile> File(new InputFile);
556 
557   Expected<IRSymtabFile> FOrErr = readIRSymtab(Object);
558   if (!FOrErr)
559     return FOrErr.takeError();
560 
561   File->TargetTriple = FOrErr->TheReader.getTargetTriple();
562   File->SourceFileName = FOrErr->TheReader.getSourceFileName();
563   File->COFFLinkerOpts = FOrErr->TheReader.getCOFFLinkerOpts();
564   File->DependentLibraries = FOrErr->TheReader.getDependentLibraries();
565   File->ComdatTable = FOrErr->TheReader.getComdatTable();
566 
567   for (unsigned I = 0; I != FOrErr->Mods.size(); ++I) {
568     size_t Begin = File->Symbols.size();
569     for (const irsymtab::Reader::SymbolRef &Sym :
570          FOrErr->TheReader.module_symbols(I))
571       // Skip symbols that are irrelevant to LTO. Note that this condition needs
572       // to match the one in Skip() in LTO::addRegularLTO().
573       if (Sym.isGlobal() && !Sym.isFormatSpecific())
574         File->Symbols.push_back(Sym);
575     File->ModuleSymIndices.push_back({Begin, File->Symbols.size()});
576   }
577 
578   File->Mods = FOrErr->Mods;
579   File->Strtab = std::move(FOrErr->Strtab);
580   return std::move(File);
581 }
582 
583 StringRef InputFile::getName() const {
584   return Mods[0].getModuleIdentifier();
585 }
586 
587 BitcodeModule &InputFile::getSingleBitcodeModule() {
588   assert(Mods.size() == 1 && "Expect only one bitcode module");
589   return Mods[0];
590 }
591 
592 LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
593                                       const Config &Conf)
594     : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
595       Ctx(Conf), CombinedModule(std::make_unique<Module>("ld-temp.o", Ctx)),
596       Mover(std::make_unique<IRMover>(*CombinedModule)) {
597   CombinedModule->IsNewDbgInfoFormat = UseNewDbgInfoFormat;
598 }
599 
600 LTO::ThinLTOState::ThinLTOState(ThinBackend BackendParam)
601     : Backend(std::move(BackendParam)), CombinedIndex(/*HaveGVs*/ false) {
602   if (!Backend.isValid())
603     Backend =
604         createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
605 }
606 
607 LTO::LTO(Config Conf, ThinBackend Backend,
608          unsigned ParallelCodeGenParallelismLevel, LTOKind LTOMode)
609     : Conf(std::move(Conf)),
610       RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
611       ThinLTO(std::move(Backend)),
612       GlobalResolutions(
613           std::make_unique<DenseMap<StringRef, GlobalResolution>>()),
614       LTOMode(LTOMode) {
615   if (Conf.KeepSymbolNameCopies || LTOKeepSymbolCopies) {
616     Alloc = std::make_unique<BumpPtrAllocator>();
617     GlobalResolutionSymbolSaver = std::make_unique<llvm::StringSaver>(*Alloc);
618   }
619 }
620 
621 // Requires a destructor for MapVector<BitcodeModule>.
622 LTO::~LTO() = default;
623 
624 // Add the symbols in the given module to the GlobalResolutions map, and resolve
625 // their partitions.
626 void LTO::addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms,
627                                ArrayRef<SymbolResolution> Res,
628                                unsigned Partition, bool InSummary) {
629   auto *ResI = Res.begin();
630   auto *ResE = Res.end();
631   (void)ResE;
632   const Triple TT(RegularLTO.CombinedModule->getTargetTriple());
633   for (const InputFile::Symbol &Sym : Syms) {
634     assert(ResI != ResE);
635     SymbolResolution Res = *ResI++;
636 
637     StringRef SymbolName = Sym.getName();
638     // Keep copies of symbols if the client of LTO says so.
639     if (GlobalResolutionSymbolSaver && !GlobalResolutions->contains(SymbolName))
640       SymbolName = GlobalResolutionSymbolSaver->save(SymbolName);
641 
642     auto &GlobalRes = (*GlobalResolutions)[SymbolName];
643     GlobalRes.UnnamedAddr &= Sym.isUnnamedAddr();
644     if (Res.Prevailing) {
645       assert(!GlobalRes.Prevailing &&
646              "Multiple prevailing defs are not allowed");
647       GlobalRes.Prevailing = true;
648       GlobalRes.IRName = std::string(Sym.getIRName());
649     } else if (!GlobalRes.Prevailing && GlobalRes.IRName.empty()) {
650       // Sometimes it can be two copies of symbol in a module and prevailing
651       // symbol can have no IR name. That might happen if symbol is defined in
652       // module level inline asm block. In case we have multiple modules with
653       // the same symbol we want to use IR name of the prevailing symbol.
654       // Otherwise, if we haven't seen a prevailing symbol, set the name so that
655       // we can later use it to check if there is any prevailing copy in IR.
656       GlobalRes.IRName = std::string(Sym.getIRName());
657     }
658 
659     // In rare occasion, the symbol used to initialize GlobalRes has a different
660     // IRName from the inspected Symbol. This can happen on macOS + iOS, when a
661     // symbol is referenced through its mangled name, say @"\01_symbol" while
662     // the IRName is @symbol (the prefix underscore comes from MachO mangling).
663     // In that case, we have the same actual Symbol that can get two different
664     // GUID, leading to some invalid internalization. Workaround this by marking
665     // the GlobalRes external.
666 
667     // FIXME: instead of this check, it would be desirable to compute GUIDs
668     // based on mangled name, but this requires an access to the Target Triple
669     // and would be relatively invasive on the codebase.
670     if (GlobalRes.IRName != Sym.getIRName()) {
671       GlobalRes.Partition = GlobalResolution::External;
672       GlobalRes.VisibleOutsideSummary = true;
673     }
674 
675     // Set the partition to external if we know it is re-defined by the linker
676     // with -defsym or -wrap options, used elsewhere, e.g. it is visible to a
677     // regular object, is referenced from llvm.compiler.used/llvm.used, or was
678     // already recorded as being referenced from a different partition.
679     if (Res.LinkerRedefined || Res.VisibleToRegularObj || Sym.isUsed() ||
680         (GlobalRes.Partition != GlobalResolution::Unknown &&
681          GlobalRes.Partition != Partition)) {
682       GlobalRes.Partition = GlobalResolution::External;
683     } else
684       // First recorded reference, save the current partition.
685       GlobalRes.Partition = Partition;
686 
687     // Flag as visible outside of summary if visible from a regular object or
688     // from a module that does not have a summary.
689     GlobalRes.VisibleOutsideSummary |=
690         (Res.VisibleToRegularObj || Sym.isUsed() || !InSummary);
691 
692     GlobalRes.ExportDynamic |= Res.ExportDynamic;
693   }
694 }
695 
696 void LTO::releaseGlobalResolutionsMemory() {
697   // Release GlobalResolutions dense-map itself.
698   GlobalResolutions.reset();
699   // Release the string saver memory.
700   GlobalResolutionSymbolSaver.reset();
701   Alloc.reset();
702 }
703 
704 static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
705                                   ArrayRef<SymbolResolution> Res) {
706   StringRef Path = Input->getName();
707   OS << Path << '\n';
708   auto ResI = Res.begin();
709   for (const InputFile::Symbol &Sym : Input->symbols()) {
710     assert(ResI != Res.end());
711     SymbolResolution Res = *ResI++;
712 
713     OS << "-r=" << Path << ',' << Sym.getName() << ',';
714     if (Res.Prevailing)
715       OS << 'p';
716     if (Res.FinalDefinitionInLinkageUnit)
717       OS << 'l';
718     if (Res.VisibleToRegularObj)
719       OS << 'x';
720     if (Res.LinkerRedefined)
721       OS << 'r';
722     OS << '\n';
723   }
724   OS.flush();
725   assert(ResI == Res.end());
726 }
727 
728 Error LTO::add(std::unique_ptr<InputFile> Input,
729                ArrayRef<SymbolResolution> Res) {
730   assert(!CalledGetMaxTasks);
731 
732   if (Conf.ResolutionFile)
733     writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
734 
735   if (RegularLTO.CombinedModule->getTargetTriple().empty()) {
736     RegularLTO.CombinedModule->setTargetTriple(Input->getTargetTriple());
737     if (Triple(Input->getTargetTriple()).isOSBinFormatELF())
738       Conf.VisibilityScheme = Config::ELF;
739   }
740 
741   const SymbolResolution *ResI = Res.begin();
742   for (unsigned I = 0; I != Input->Mods.size(); ++I)
743     if (Error Err = addModule(*Input, I, ResI, Res.end()))
744       return Err;
745 
746   assert(ResI == Res.end());
747   return Error::success();
748 }
749 
750 Error LTO::addModule(InputFile &Input, unsigned ModI,
751                      const SymbolResolution *&ResI,
752                      const SymbolResolution *ResE) {
753   Expected<BitcodeLTOInfo> LTOInfo = Input.Mods[ModI].getLTOInfo();
754   if (!LTOInfo)
755     return LTOInfo.takeError();
756 
757   if (EnableSplitLTOUnit) {
758     // If only some modules were split, flag this in the index so that
759     // we can skip or error on optimizations that need consistently split
760     // modules (whole program devirt and lower type tests).
761     if (*EnableSplitLTOUnit != LTOInfo->EnableSplitLTOUnit)
762       ThinLTO.CombinedIndex.setPartiallySplitLTOUnits();
763   } else
764     EnableSplitLTOUnit = LTOInfo->EnableSplitLTOUnit;
765 
766   BitcodeModule BM = Input.Mods[ModI];
767 
768   if ((LTOMode == LTOK_UnifiedRegular || LTOMode == LTOK_UnifiedThin) &&
769       !LTOInfo->UnifiedLTO)
770     return make_error<StringError>(
771         "unified LTO compilation must use "
772         "compatible bitcode modules (use -funified-lto)",
773         inconvertibleErrorCode());
774 
775   if (LTOInfo->UnifiedLTO && LTOMode == LTOK_Default)
776     LTOMode = LTOK_UnifiedThin;
777 
778   bool IsThinLTO = LTOInfo->IsThinLTO && (LTOMode != LTOK_UnifiedRegular);
779 
780   auto ModSyms = Input.module_symbols(ModI);
781   addModuleToGlobalRes(ModSyms, {ResI, ResE},
782                        IsThinLTO ? ThinLTO.ModuleMap.size() + 1 : 0,
783                        LTOInfo->HasSummary);
784 
785   if (IsThinLTO)
786     return addThinLTO(BM, ModSyms, ResI, ResE);
787 
788   RegularLTO.EmptyCombinedModule = false;
789   Expected<RegularLTOState::AddedModule> ModOrErr =
790       addRegularLTO(BM, ModSyms, ResI, ResE);
791   if (!ModOrErr)
792     return ModOrErr.takeError();
793 
794   if (!LTOInfo->HasSummary)
795     return linkRegularLTO(std::move(*ModOrErr), /*LivenessFromIndex=*/false);
796 
797   // Regular LTO module summaries are added to a dummy module that represents
798   // the combined regular LTO module.
799   if (Error Err = BM.readSummary(ThinLTO.CombinedIndex, ""))
800     return Err;
801   RegularLTO.ModsWithSummaries.push_back(std::move(*ModOrErr));
802   return Error::success();
803 }
804 
805 // Checks whether the given global value is in a non-prevailing comdat
806 // (comdat containing values the linker indicated were not prevailing,
807 // which we then dropped to available_externally), and if so, removes
808 // it from the comdat. This is called for all global values to ensure the
809 // comdat is empty rather than leaving an incomplete comdat. It is needed for
810 // regular LTO modules, in case we are in a mixed-LTO mode (both regular
811 // and thin LTO modules) compilation. Since the regular LTO module will be
812 // linked first in the final native link, we want to make sure the linker
813 // doesn't select any of these incomplete comdats that would be left
814 // in the regular LTO module without this cleanup.
815 static void
816 handleNonPrevailingComdat(GlobalValue &GV,
817                           std::set<const Comdat *> &NonPrevailingComdats) {
818   Comdat *C = GV.getComdat();
819   if (!C)
820     return;
821 
822   if (!NonPrevailingComdats.count(C))
823     return;
824 
825   // Additionally need to drop all global values from the comdat to
826   // available_externally, to satisfy the COMDAT requirement that all members
827   // are discarded as a unit. The non-local linkage global values avoid
828   // duplicate definition linker errors.
829   GV.setLinkage(GlobalValue::AvailableExternallyLinkage);
830 
831   if (auto GO = dyn_cast<GlobalObject>(&GV))
832     GO->setComdat(nullptr);
833 }
834 
835 // Add a regular LTO object to the link.
836 // The resulting module needs to be linked into the combined LTO module with
837 // linkRegularLTO.
838 Expected<LTO::RegularLTOState::AddedModule>
839 LTO::addRegularLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
840                    const SymbolResolution *&ResI,
841                    const SymbolResolution *ResE) {
842   RegularLTOState::AddedModule Mod;
843   Expected<std::unique_ptr<Module>> MOrErr =
844       BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
845                        /*IsImporting*/ false);
846   if (!MOrErr)
847     return MOrErr.takeError();
848   Module &M = **MOrErr;
849   Mod.M = std::move(*MOrErr);
850 
851   if (Error Err = M.materializeMetadata())
852     return std::move(Err);
853 
854   // If cfi.functions is present and we are in regular LTO mode, LowerTypeTests
855   // will rename local functions in the merged module as "<function name>.1".
856   // This causes linking errors, since other parts of the module expect the
857   // original function name.
858   if (LTOMode == LTOK_UnifiedRegular)
859     if (NamedMDNode *CfiFunctionsMD = M.getNamedMetadata("cfi.functions"))
860       M.eraseNamedMetadata(CfiFunctionsMD);
861 
862   UpgradeDebugInfo(M);
863 
864   ModuleSymbolTable SymTab;
865   SymTab.addModule(&M);
866 
867   for (GlobalVariable &GV : M.globals())
868     if (GV.hasAppendingLinkage())
869       Mod.Keep.push_back(&GV);
870 
871   DenseSet<GlobalObject *> AliasedGlobals;
872   for (auto &GA : M.aliases())
873     if (GlobalObject *GO = GA.getAliaseeObject())
874       AliasedGlobals.insert(GO);
875 
876   // In this function we need IR GlobalValues matching the symbols in Syms
877   // (which is not backed by a module), so we need to enumerate them in the same
878   // order. The symbol enumeration order of a ModuleSymbolTable intentionally
879   // matches the order of an irsymtab, but when we read the irsymtab in
880   // InputFile::create we omit some symbols that are irrelevant to LTO. The
881   // Skip() function skips the same symbols from the module as InputFile does
882   // from the symbol table.
883   auto MsymI = SymTab.symbols().begin(), MsymE = SymTab.symbols().end();
884   auto Skip = [&]() {
885     while (MsymI != MsymE) {
886       auto Flags = SymTab.getSymbolFlags(*MsymI);
887       if ((Flags & object::BasicSymbolRef::SF_Global) &&
888           !(Flags & object::BasicSymbolRef::SF_FormatSpecific))
889         return;
890       ++MsymI;
891     }
892   };
893   Skip();
894 
895   std::set<const Comdat *> NonPrevailingComdats;
896   SmallSet<StringRef, 2> NonPrevailingAsmSymbols;
897   for (const InputFile::Symbol &Sym : Syms) {
898     assert(ResI != ResE);
899     SymbolResolution Res = *ResI++;
900 
901     assert(MsymI != MsymE);
902     ModuleSymbolTable::Symbol Msym = *MsymI++;
903     Skip();
904 
905     if (GlobalValue *GV = dyn_cast_if_present<GlobalValue *>(Msym)) {
906       if (Res.Prevailing) {
907         if (Sym.isUndefined())
908           continue;
909         Mod.Keep.push_back(GV);
910         // For symbols re-defined with linker -wrap and -defsym options,
911         // set the linkage to weak to inhibit IPO. The linkage will be
912         // restored by the linker.
913         if (Res.LinkerRedefined)
914           GV->setLinkage(GlobalValue::WeakAnyLinkage);
915 
916         GlobalValue::LinkageTypes OriginalLinkage = GV->getLinkage();
917         if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
918           GV->setLinkage(GlobalValue::getWeakLinkage(
919               GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
920       } else if (isa<GlobalObject>(GV) &&
921                  (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
922                   GV->hasAvailableExternallyLinkage()) &&
923                  !AliasedGlobals.count(cast<GlobalObject>(GV))) {
924         // Any of the above three types of linkage indicates that the
925         // chosen prevailing symbol will have the same semantics as this copy of
926         // the symbol, so we may be able to link it with available_externally
927         // linkage. We will decide later whether to do that when we link this
928         // module (in linkRegularLTO), based on whether it is undefined.
929         Mod.Keep.push_back(GV);
930         GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
931         if (GV->hasComdat())
932           NonPrevailingComdats.insert(GV->getComdat());
933         cast<GlobalObject>(GV)->setComdat(nullptr);
934       }
935 
936       // Set the 'local' flag based on the linker resolution for this symbol.
937       if (Res.FinalDefinitionInLinkageUnit) {
938         GV->setDSOLocal(true);
939         if (GV->hasDLLImportStorageClass())
940           GV->setDLLStorageClass(GlobalValue::DLLStorageClassTypes::
941                                  DefaultStorageClass);
942       }
943     } else if (auto *AS =
944                    dyn_cast_if_present<ModuleSymbolTable::AsmSymbol *>(Msym)) {
945       // Collect non-prevailing symbols.
946       if (!Res.Prevailing)
947         NonPrevailingAsmSymbols.insert(AS->first);
948     } else {
949       llvm_unreachable("unknown symbol type");
950     }
951 
952     // Common resolution: collect the maximum size/alignment over all commons.
953     // We also record if we see an instance of a common as prevailing, so that
954     // if none is prevailing we can ignore it later.
955     if (Sym.isCommon()) {
956       // FIXME: We should figure out what to do about commons defined by asm.
957       // For now they aren't reported correctly by ModuleSymbolTable.
958       auto &CommonRes = RegularLTO.Commons[std::string(Sym.getIRName())];
959       CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
960       if (uint32_t SymAlignValue = Sym.getCommonAlignment()) {
961         CommonRes.Alignment =
962             std::max(Align(SymAlignValue), CommonRes.Alignment);
963       }
964       CommonRes.Prevailing |= Res.Prevailing;
965     }
966   }
967 
968   if (!M.getComdatSymbolTable().empty())
969     for (GlobalValue &GV : M.global_values())
970       handleNonPrevailingComdat(GV, NonPrevailingComdats);
971 
972   // Prepend ".lto_discard <sym>, <sym>*" directive to each module inline asm
973   // block.
974   if (!M.getModuleInlineAsm().empty()) {
975     std::string NewIA = ".lto_discard";
976     if (!NonPrevailingAsmSymbols.empty()) {
977       // Don't dicard a symbol if there is a live .symver for it.
978       ModuleSymbolTable::CollectAsmSymvers(
979           M, [&](StringRef Name, StringRef Alias) {
980             if (!NonPrevailingAsmSymbols.count(Alias))
981               NonPrevailingAsmSymbols.erase(Name);
982           });
983       NewIA += " " + llvm::join(NonPrevailingAsmSymbols, ", ");
984     }
985     NewIA += "\n";
986     M.setModuleInlineAsm(NewIA + M.getModuleInlineAsm());
987   }
988 
989   assert(MsymI == MsymE);
990   return std::move(Mod);
991 }
992 
993 Error LTO::linkRegularLTO(RegularLTOState::AddedModule Mod,
994                           bool LivenessFromIndex) {
995   std::vector<GlobalValue *> Keep;
996   for (GlobalValue *GV : Mod.Keep) {
997     if (LivenessFromIndex && !ThinLTO.CombinedIndex.isGUIDLive(GV->getGUID())) {
998       if (Function *F = dyn_cast<Function>(GV)) {
999         if (DiagnosticOutputFile) {
1000           if (Error Err = F->materialize())
1001             return Err;
1002           OptimizationRemarkEmitter ORE(F, nullptr);
1003           ORE.emit(OptimizationRemark(DEBUG_TYPE, "deadfunction", F)
1004                    << ore::NV("Function", F)
1005                    << " not added to the combined module ");
1006         }
1007       }
1008       continue;
1009     }
1010 
1011     if (!GV->hasAvailableExternallyLinkage()) {
1012       Keep.push_back(GV);
1013       continue;
1014     }
1015 
1016     // Only link available_externally definitions if we don't already have a
1017     // definition.
1018     GlobalValue *CombinedGV =
1019         RegularLTO.CombinedModule->getNamedValue(GV->getName());
1020     if (CombinedGV && !CombinedGV->isDeclaration())
1021       continue;
1022 
1023     Keep.push_back(GV);
1024   }
1025 
1026   return RegularLTO.Mover->move(std::move(Mod.M), Keep, nullptr,
1027                                 /* IsPerformingImport */ false);
1028 }
1029 
1030 // Add a ThinLTO module to the link.
1031 Error LTO::addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
1032                       const SymbolResolution *&ResI,
1033                       const SymbolResolution *ResE) {
1034   const SymbolResolution *ResITmp = ResI;
1035   for (const InputFile::Symbol &Sym : Syms) {
1036     assert(ResITmp != ResE);
1037     SymbolResolution Res = *ResITmp++;
1038 
1039     if (!Sym.getIRName().empty()) {
1040       auto GUID = GlobalValue::getGUID(GlobalValue::getGlobalIdentifier(
1041           Sym.getIRName(), GlobalValue::ExternalLinkage, ""));
1042       if (Res.Prevailing)
1043         ThinLTO.PrevailingModuleForGUID[GUID] = BM.getModuleIdentifier();
1044     }
1045   }
1046 
1047   if (Error Err =
1048           BM.readSummary(ThinLTO.CombinedIndex, BM.getModuleIdentifier(),
1049                          [&](GlobalValue::GUID GUID) {
1050                            return ThinLTO.PrevailingModuleForGUID[GUID] ==
1051                                   BM.getModuleIdentifier();
1052                          }))
1053     return Err;
1054   LLVM_DEBUG(dbgs() << "Module " << BM.getModuleIdentifier() << "\n");
1055 
1056   for (const InputFile::Symbol &Sym : Syms) {
1057     assert(ResI != ResE);
1058     SymbolResolution Res = *ResI++;
1059 
1060     if (!Sym.getIRName().empty()) {
1061       auto GUID = GlobalValue::getGUID(GlobalValue::getGlobalIdentifier(
1062           Sym.getIRName(), GlobalValue::ExternalLinkage, ""));
1063       if (Res.Prevailing) {
1064         assert(ThinLTO.PrevailingModuleForGUID[GUID] ==
1065                BM.getModuleIdentifier());
1066 
1067         // For linker redefined symbols (via --wrap or --defsym) we want to
1068         // switch the linkage to `weak` to prevent IPOs from happening.
1069         // Find the summary in the module for this very GV and record the new
1070         // linkage so that we can switch it when we import the GV.
1071         if (Res.LinkerRedefined)
1072           if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(
1073                   GUID, BM.getModuleIdentifier()))
1074             S->setLinkage(GlobalValue::WeakAnyLinkage);
1075       }
1076 
1077       // If the linker resolved the symbol to a local definition then mark it
1078       // as local in the summary for the module we are adding.
1079       if (Res.FinalDefinitionInLinkageUnit) {
1080         if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(
1081                 GUID, BM.getModuleIdentifier())) {
1082           S->setDSOLocal(true);
1083         }
1084       }
1085     }
1086   }
1087 
1088   if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
1089     return make_error<StringError>(
1090         "Expected at most one ThinLTO module per bitcode file",
1091         inconvertibleErrorCode());
1092 
1093   if (!Conf.ThinLTOModulesToCompile.empty()) {
1094     if (!ThinLTO.ModulesToCompile)
1095       ThinLTO.ModulesToCompile = ModuleMapType();
1096     // This is a fuzzy name matching where only modules with name containing the
1097     // specified switch values are going to be compiled.
1098     for (const std::string &Name : Conf.ThinLTOModulesToCompile) {
1099       if (BM.getModuleIdentifier().contains(Name)) {
1100         ThinLTO.ModulesToCompile->insert({BM.getModuleIdentifier(), BM});
1101         LLVM_DEBUG(dbgs() << "[ThinLTO] Selecting " << BM.getModuleIdentifier()
1102                           << " to compile\n");
1103       }
1104     }
1105   }
1106 
1107   return Error::success();
1108 }
1109 
1110 unsigned LTO::getMaxTasks() const {
1111   CalledGetMaxTasks = true;
1112   auto ModuleCount = ThinLTO.ModulesToCompile ? ThinLTO.ModulesToCompile->size()
1113                                               : ThinLTO.ModuleMap.size();
1114   return RegularLTO.ParallelCodeGenParallelismLevel + ModuleCount;
1115 }
1116 
1117 // If only some of the modules were split, we cannot correctly handle
1118 // code that contains type tests or type checked loads.
1119 Error LTO::checkPartiallySplit() {
1120   if (!ThinLTO.CombinedIndex.partiallySplitLTOUnits())
1121     return Error::success();
1122 
1123   const Module *Combined = RegularLTO.CombinedModule.get();
1124   Function *TypeTestFunc =
1125       Intrinsic::getDeclarationIfExists(Combined, Intrinsic::type_test);
1126   Function *TypeCheckedLoadFunc =
1127       Intrinsic::getDeclarationIfExists(Combined, Intrinsic::type_checked_load);
1128   Function *TypeCheckedLoadRelativeFunc = Intrinsic::getDeclarationIfExists(
1129       Combined, Intrinsic::type_checked_load_relative);
1130 
1131   // First check if there are type tests / type checked loads in the
1132   // merged regular LTO module IR.
1133   if ((TypeTestFunc && !TypeTestFunc->use_empty()) ||
1134       (TypeCheckedLoadFunc && !TypeCheckedLoadFunc->use_empty()) ||
1135       (TypeCheckedLoadRelativeFunc &&
1136        !TypeCheckedLoadRelativeFunc->use_empty()))
1137     return make_error<StringError>(
1138         "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
1139         inconvertibleErrorCode());
1140 
1141   // Otherwise check if there are any recorded in the combined summary from the
1142   // ThinLTO modules.
1143   for (auto &P : ThinLTO.CombinedIndex) {
1144     for (auto &S : P.second.SummaryList) {
1145       auto *FS = dyn_cast<FunctionSummary>(S.get());
1146       if (!FS)
1147         continue;
1148       if (!FS->type_test_assume_vcalls().empty() ||
1149           !FS->type_checked_load_vcalls().empty() ||
1150           !FS->type_test_assume_const_vcalls().empty() ||
1151           !FS->type_checked_load_const_vcalls().empty() ||
1152           !FS->type_tests().empty())
1153         return make_error<StringError>(
1154             "inconsistent LTO Unit splitting (recompile with -fsplit-lto-unit)",
1155             inconvertibleErrorCode());
1156     }
1157   }
1158   return Error::success();
1159 }
1160 
1161 Error LTO::run(AddStreamFn AddStream, FileCache Cache) {
1162   // Compute "dead" symbols, we don't want to import/export these!
1163   DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
1164   DenseMap<GlobalValue::GUID, PrevailingType> GUIDPrevailingResolutions;
1165   for (auto &Res : *GlobalResolutions) {
1166     // Normally resolution have IR name of symbol. We can do nothing here
1167     // otherwise. See comments in GlobalResolution struct for more details.
1168     if (Res.second.IRName.empty())
1169       continue;
1170 
1171     GlobalValue::GUID GUID = GlobalValue::getGUID(
1172         GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
1173 
1174     if (Res.second.VisibleOutsideSummary && Res.second.Prevailing)
1175       GUIDPreservedSymbols.insert(GUID);
1176 
1177     if (Res.second.ExportDynamic)
1178       DynamicExportSymbols.insert(GUID);
1179 
1180     GUIDPrevailingResolutions[GUID] =
1181         Res.second.Prevailing ? PrevailingType::Yes : PrevailingType::No;
1182   }
1183 
1184   auto isPrevailing = [&](GlobalValue::GUID G) {
1185     auto It = GUIDPrevailingResolutions.find(G);
1186     if (It == GUIDPrevailingResolutions.end())
1187       return PrevailingType::Unknown;
1188     return It->second;
1189   };
1190   computeDeadSymbolsWithConstProp(ThinLTO.CombinedIndex, GUIDPreservedSymbols,
1191                                   isPrevailing, Conf.OptLevel > 0);
1192 
1193   // Setup output file to emit statistics.
1194   auto StatsFileOrErr = setupStatsFile(Conf.StatsFile);
1195   if (!StatsFileOrErr)
1196     return StatsFileOrErr.takeError();
1197   std::unique_ptr<ToolOutputFile> StatsFile = std::move(StatsFileOrErr.get());
1198 
1199   // TODO: Ideally this would be controlled automatically by detecting that we
1200   // are linking with an allocator that supports these interfaces, rather than
1201   // an internal option (which would still be needed for tests, however). For
1202   // example, if the library exported a symbol like __malloc_hot_cold the linker
1203   // could recognize that and set a flag in the lto::Config.
1204   if (SupportsHotColdNew)
1205     ThinLTO.CombinedIndex.setWithSupportsHotColdNew();
1206 
1207   Error Result = runRegularLTO(AddStream);
1208   if (!Result)
1209     // This will reset the GlobalResolutions optional once done with it to
1210     // reduce peak memory before importing.
1211     Result = runThinLTO(AddStream, Cache, GUIDPreservedSymbols);
1212 
1213   if (StatsFile)
1214     PrintStatisticsJSON(StatsFile->os());
1215 
1216   return Result;
1217 }
1218 
1219 void lto::updateMemProfAttributes(Module &Mod,
1220                                   const ModuleSummaryIndex &Index) {
1221   if (Index.withSupportsHotColdNew())
1222     return;
1223 
1224   // The profile matcher applies hotness attributes directly for allocations,
1225   // and those will cause us to generate calls to the hot/cold interfaces
1226   // unconditionally. If supports-hot-cold-new was not enabled in the LTO
1227   // link then assume we don't want these calls (e.g. not linking with
1228   // the appropriate library, or otherwise trying to disable this behavior).
1229   for (auto &F : Mod) {
1230     for (auto &BB : F) {
1231       for (auto &I : BB) {
1232         auto *CI = dyn_cast<CallBase>(&I);
1233         if (!CI)
1234           continue;
1235         if (CI->hasFnAttr("memprof"))
1236           CI->removeFnAttr("memprof");
1237         // Strip off all memprof metadata as it is no longer needed.
1238         // Importantly, this avoids the addition of new memprof attributes
1239         // after inlining propagation.
1240         // TODO: If we support additional types of MemProf metadata beyond hot
1241         // and cold, we will need to update the metadata based on the allocator
1242         // APIs supported instead of completely stripping all.
1243         CI->setMetadata(LLVMContext::MD_memprof, nullptr);
1244         CI->setMetadata(LLVMContext::MD_callsite, nullptr);
1245       }
1246     }
1247   }
1248 }
1249 
1250 Error LTO::runRegularLTO(AddStreamFn AddStream) {
1251   // Setup optimization remarks.
1252   auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
1253       RegularLTO.CombinedModule->getContext(), Conf.RemarksFilename,
1254       Conf.RemarksPasses, Conf.RemarksFormat, Conf.RemarksWithHotness,
1255       Conf.RemarksHotnessThreshold);
1256   LLVM_DEBUG(dbgs() << "Running regular LTO\n");
1257   if (!DiagFileOrErr)
1258     return DiagFileOrErr.takeError();
1259   DiagnosticOutputFile = std::move(*DiagFileOrErr);
1260 
1261   // Finalize linking of regular LTO modules containing summaries now that
1262   // we have computed liveness information.
1263   for (auto &M : RegularLTO.ModsWithSummaries)
1264     if (Error Err = linkRegularLTO(std::move(M),
1265                                    /*LivenessFromIndex=*/true))
1266       return Err;
1267 
1268   // Ensure we don't have inconsistently split LTO units with type tests.
1269   // FIXME: this checks both LTO and ThinLTO. It happens to work as we take
1270   // this path both cases but eventually this should be split into two and
1271   // do the ThinLTO checks in `runThinLTO`.
1272   if (Error Err = checkPartiallySplit())
1273     return Err;
1274 
1275   // Make sure commons have the right size/alignment: we kept the largest from
1276   // all the prevailing when adding the inputs, and we apply it here.
1277   const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
1278   for (auto &I : RegularLTO.Commons) {
1279     if (!I.second.Prevailing)
1280       // Don't do anything if no instance of this common was prevailing.
1281       continue;
1282     GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
1283     if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
1284       // Don't create a new global if the type is already correct, just make
1285       // sure the alignment is correct.
1286       OldGV->setAlignment(I.second.Alignment);
1287       continue;
1288     }
1289     ArrayType *Ty =
1290         ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
1291     auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
1292                                   GlobalValue::CommonLinkage,
1293                                   ConstantAggregateZero::get(Ty), "");
1294     GV->setAlignment(I.second.Alignment);
1295     if (OldGV) {
1296       OldGV->replaceAllUsesWith(GV);
1297       GV->takeName(OldGV);
1298       OldGV->eraseFromParent();
1299     } else {
1300       GV->setName(I.first);
1301     }
1302   }
1303 
1304   updateMemProfAttributes(*RegularLTO.CombinedModule, ThinLTO.CombinedIndex);
1305 
1306   bool WholeProgramVisibilityEnabledInLTO =
1307       Conf.HasWholeProgramVisibility &&
1308       // If validation is enabled, upgrade visibility only when all vtables
1309       // have typeinfos.
1310       (!Conf.ValidateAllVtablesHaveTypeInfos || Conf.AllVtablesHaveTypeInfos);
1311 
1312   // This returns true when the name is local or not defined. Locals are
1313   // expected to be handled separately.
1314   auto IsVisibleToRegularObj = [&](StringRef name) {
1315     auto It = GlobalResolutions->find(name);
1316     return (It == GlobalResolutions->end() || It->second.VisibleOutsideSummary);
1317   };
1318 
1319   // If allowed, upgrade public vcall visibility metadata to linkage unit
1320   // visibility before whole program devirtualization in the optimizer.
1321   updateVCallVisibilityInModule(
1322       *RegularLTO.CombinedModule, WholeProgramVisibilityEnabledInLTO,
1323       DynamicExportSymbols, Conf.ValidateAllVtablesHaveTypeInfos,
1324       IsVisibleToRegularObj);
1325   updatePublicTypeTestCalls(*RegularLTO.CombinedModule,
1326                             WholeProgramVisibilityEnabledInLTO);
1327 
1328   if (Conf.PreOptModuleHook &&
1329       !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
1330     return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
1331 
1332   if (!Conf.CodeGenOnly) {
1333     for (const auto &R : *GlobalResolutions) {
1334       GlobalValue *GV =
1335           RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
1336       if (!R.second.isPrevailingIRSymbol())
1337         continue;
1338       if (R.second.Partition != 0 &&
1339           R.second.Partition != GlobalResolution::External)
1340         continue;
1341 
1342       // Ignore symbols defined in other partitions.
1343       // Also skip declarations, which are not allowed to have internal linkage.
1344       if (!GV || GV->hasLocalLinkage() || GV->isDeclaration())
1345         continue;
1346 
1347       // Symbols that are marked DLLImport or DLLExport should not be
1348       // internalized, as they are either externally visible or referencing
1349       // external symbols. Symbols that have AvailableExternally or Appending
1350       // linkage might be used by future passes and should be kept as is.
1351       // These linkages are seen in Unified regular LTO, because the process
1352       // of creating split LTO units introduces symbols with that linkage into
1353       // one of the created modules. Normally, only the ThinLTO backend would
1354       // compile this module, but Unified Regular LTO processes both
1355       // modules created by the splitting process as regular LTO modules.
1356       if ((LTOMode == LTOKind::LTOK_UnifiedRegular) &&
1357           ((GV->getDLLStorageClass() != GlobalValue::DefaultStorageClass) ||
1358            GV->hasAvailableExternallyLinkage() || GV->hasAppendingLinkage()))
1359         continue;
1360 
1361       GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
1362                                               : GlobalValue::UnnamedAddr::None);
1363       if (EnableLTOInternalization && R.second.Partition == 0)
1364         GV->setLinkage(GlobalValue::InternalLinkage);
1365     }
1366 
1367     if (Conf.PostInternalizeModuleHook &&
1368         !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
1369       return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
1370   }
1371 
1372   if (!RegularLTO.EmptyCombinedModule || Conf.AlwaysEmitRegularLTOObj) {
1373     if (Error Err =
1374             backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
1375                     *RegularLTO.CombinedModule, ThinLTO.CombinedIndex))
1376       return Err;
1377   }
1378 
1379   return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
1380 }
1381 
1382 SmallVector<const char *> LTO::getRuntimeLibcallSymbols(const Triple &TT) {
1383   RTLIB::RuntimeLibcallsInfo Libcalls(TT);
1384   SmallVector<const char *> LibcallSymbols;
1385   copy_if(Libcalls.getLibcallNames(), std::back_inserter(LibcallSymbols),
1386           [](const char *Name) { return Name; });
1387   return LibcallSymbols;
1388 }
1389 
1390 Error ThinBackendProc::emitFiles(
1391     const FunctionImporter::ImportMapTy &ImportList, llvm::StringRef ModulePath,
1392     const std::string &NewModulePath) const {
1393   ModuleToSummariesForIndexTy ModuleToSummariesForIndex;
1394   GVSummaryPtrSet DeclarationSummaries;
1395 
1396   std::error_code EC;
1397   gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
1398                                    ImportList, ModuleToSummariesForIndex,
1399                                    DeclarationSummaries);
1400 
1401   raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
1402                     sys::fs::OpenFlags::OF_None);
1403   if (EC)
1404     return createFileError("cannot open " + NewModulePath + ".thinlto.bc", EC);
1405 
1406   writeIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex,
1407                    &DeclarationSummaries);
1408 
1409   if (ShouldEmitImportsFiles) {
1410     Error ImportFilesError = EmitImportsFiles(
1411         ModulePath, NewModulePath + ".imports", ModuleToSummariesForIndex);
1412     if (ImportFilesError)
1413       return ImportFilesError;
1414   }
1415   return Error::success();
1416 }
1417 
1418 namespace {
1419 class InProcessThinBackend : public ThinBackendProc {
1420 protected:
1421   AddStreamFn AddStream;
1422   FileCache Cache;
1423   DenseSet<GlobalValue::GUID> CfiFunctionDefs;
1424   DenseSet<GlobalValue::GUID> CfiFunctionDecls;
1425 
1426   bool ShouldEmitIndexFiles;
1427 
1428 public:
1429   InProcessThinBackend(
1430       const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1431       ThreadPoolStrategy ThinLTOParallelism,
1432       const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1433       AddStreamFn AddStream, FileCache Cache, lto::IndexWriteCallback OnWrite,
1434       bool ShouldEmitIndexFiles, bool ShouldEmitImportsFiles)
1435       : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
1436                         OnWrite, ShouldEmitImportsFiles, ThinLTOParallelism),
1437         AddStream(std::move(AddStream)), Cache(std::move(Cache)),
1438         ShouldEmitIndexFiles(ShouldEmitIndexFiles) {
1439     for (auto &Name : CombinedIndex.cfiFunctionDefs())
1440       CfiFunctionDefs.insert(
1441           GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Name)));
1442     for (auto &Name : CombinedIndex.cfiFunctionDecls())
1443       CfiFunctionDecls.insert(
1444           GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Name)));
1445   }
1446 
1447   virtual Error runThinLTOBackendThread(
1448       AddStreamFn AddStream, FileCache Cache, unsigned Task, BitcodeModule BM,
1449       ModuleSummaryIndex &CombinedIndex,
1450       const FunctionImporter::ImportMapTy &ImportList,
1451       const FunctionImporter::ExportSetTy &ExportList,
1452       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1453       const GVSummaryMapTy &DefinedGlobals,
1454       MapVector<StringRef, BitcodeModule> &ModuleMap) {
1455     auto RunThinBackend = [&](AddStreamFn AddStream) {
1456       LTOLLVMContext BackendContext(Conf);
1457       Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
1458       if (!MOrErr)
1459         return MOrErr.takeError();
1460 
1461       return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
1462                          ImportList, DefinedGlobals, &ModuleMap,
1463                          Conf.CodeGenOnly);
1464     };
1465 
1466     auto ModuleID = BM.getModuleIdentifier();
1467 
1468     if (ShouldEmitIndexFiles) {
1469       if (auto E = emitFiles(ImportList, ModuleID, ModuleID.str()))
1470         return E;
1471     }
1472 
1473     if (!Cache.isValid() || !CombinedIndex.modulePaths().count(ModuleID) ||
1474         all_of(CombinedIndex.getModuleHash(ModuleID),
1475                [](uint32_t V) { return V == 0; }))
1476       // Cache disabled or no entry for this module in the combined index or
1477       // no module hash.
1478       return RunThinBackend(AddStream);
1479 
1480     // The module may be cached, this helps handling it.
1481     std::string Key = computeLTOCacheKey(
1482         Conf, CombinedIndex, ModuleID, ImportList, ExportList, ResolvedODR,
1483         DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
1484     Expected<AddStreamFn> CacheAddStreamOrErr = Cache(Task, Key, ModuleID);
1485     if (Error Err = CacheAddStreamOrErr.takeError())
1486       return Err;
1487     AddStreamFn &CacheAddStream = *CacheAddStreamOrErr;
1488     if (CacheAddStream)
1489       return RunThinBackend(CacheAddStream);
1490 
1491     return Error::success();
1492   }
1493 
1494   Error start(
1495       unsigned Task, BitcodeModule BM,
1496       const FunctionImporter::ImportMapTy &ImportList,
1497       const FunctionImporter::ExportSetTy &ExportList,
1498       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1499       MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1500     StringRef ModulePath = BM.getModuleIdentifier();
1501     assert(ModuleToDefinedGVSummaries.count(ModulePath));
1502     const GVSummaryMapTy &DefinedGlobals =
1503         ModuleToDefinedGVSummaries.find(ModulePath)->second;
1504     BackendThreadPool.async(
1505         [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
1506             const FunctionImporter::ImportMapTy &ImportList,
1507             const FunctionImporter::ExportSetTy &ExportList,
1508             const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
1509                 &ResolvedODR,
1510             const GVSummaryMapTy &DefinedGlobals,
1511             MapVector<StringRef, BitcodeModule> &ModuleMap) {
1512           if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled)
1513             timeTraceProfilerInitialize(Conf.TimeTraceGranularity,
1514                                         "thin backend");
1515           Error E = runThinLTOBackendThread(
1516               AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
1517               ResolvedODR, DefinedGlobals, ModuleMap);
1518           if (E) {
1519             std::unique_lock<std::mutex> L(ErrMu);
1520             if (Err)
1521               Err = joinErrors(std::move(*Err), std::move(E));
1522             else
1523               Err = std::move(E);
1524           }
1525           if (LLVM_ENABLE_THREADS && Conf.TimeTraceEnabled)
1526             timeTraceProfilerFinishThread();
1527         },
1528         BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList),
1529         std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap));
1530 
1531     if (OnWrite)
1532       OnWrite(std::string(ModulePath));
1533     return Error::success();
1534   }
1535 };
1536 
1537 /// This backend is utilized in the first round of a two-codegen round process.
1538 /// It first saves optimized bitcode files to disk before the codegen process
1539 /// begins. After codegen, it stores the resulting object files in a scratch
1540 /// buffer. Note the codegen data stored in the scratch buffer will be extracted
1541 /// and merged in the subsequent step.
1542 class FirstRoundThinBackend : public InProcessThinBackend {
1543   AddStreamFn IRAddStream;
1544   FileCache IRCache;
1545 
1546 public:
1547   FirstRoundThinBackend(
1548       const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1549       ThreadPoolStrategy ThinLTOParallelism,
1550       const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1551       AddStreamFn CGAddStream, FileCache CGCache, AddStreamFn IRAddStream,
1552       FileCache IRCache)
1553       : InProcessThinBackend(Conf, CombinedIndex, ThinLTOParallelism,
1554                              ModuleToDefinedGVSummaries, std::move(CGAddStream),
1555                              std::move(CGCache), /*OnWrite=*/nullptr,
1556                              /*ShouldEmitIndexFiles=*/false,
1557                              /*ShouldEmitImportsFiles=*/false),
1558         IRAddStream(std::move(IRAddStream)), IRCache(std::move(IRCache)) {}
1559 
1560   Error runThinLTOBackendThread(
1561       AddStreamFn CGAddStream, FileCache CGCache, unsigned Task,
1562       BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
1563       const FunctionImporter::ImportMapTy &ImportList,
1564       const FunctionImporter::ExportSetTy &ExportList,
1565       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1566       const GVSummaryMapTy &DefinedGlobals,
1567       MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1568     auto RunThinBackend = [&](AddStreamFn CGAddStream,
1569                               AddStreamFn IRAddStream) {
1570       LTOLLVMContext BackendContext(Conf);
1571       Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
1572       if (!MOrErr)
1573         return MOrErr.takeError();
1574 
1575       return thinBackend(Conf, Task, CGAddStream, **MOrErr, CombinedIndex,
1576                          ImportList, DefinedGlobals, &ModuleMap,
1577                          Conf.CodeGenOnly, IRAddStream);
1578     };
1579 
1580     auto ModuleID = BM.getModuleIdentifier();
1581     // Like InProcessThinBackend, we produce index files as needed for
1582     // FirstRoundThinBackend. However, these files are not generated for
1583     // SecondRoundThinBackend.
1584     if (ShouldEmitIndexFiles) {
1585       if (auto E = emitFiles(ImportList, ModuleID, ModuleID.str()))
1586         return E;
1587     }
1588 
1589     assert((CGCache.isValid() == IRCache.isValid()) &&
1590            "Both caches for CG and IR should have matching availability");
1591     if (!CGCache.isValid() || !CombinedIndex.modulePaths().count(ModuleID) ||
1592         all_of(CombinedIndex.getModuleHash(ModuleID),
1593                [](uint32_t V) { return V == 0; }))
1594       // Cache disabled or no entry for this module in the combined index or
1595       // no module hash.
1596       return RunThinBackend(CGAddStream, IRAddStream);
1597 
1598     // Get CGKey for caching object in CGCache.
1599     std::string CGKey = computeLTOCacheKey(
1600         Conf, CombinedIndex, ModuleID, ImportList, ExportList, ResolvedODR,
1601         DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
1602     Expected<AddStreamFn> CacheCGAddStreamOrErr =
1603         CGCache(Task, CGKey, ModuleID);
1604     if (Error Err = CacheCGAddStreamOrErr.takeError())
1605       return Err;
1606     AddStreamFn &CacheCGAddStream = *CacheCGAddStreamOrErr;
1607 
1608     // Get IRKey for caching (optimized) IR in IRCache with an extra ID.
1609     std::string IRKey = recomputeLTOCacheKey(CGKey, /*ExtraID=*/"IR");
1610     Expected<AddStreamFn> CacheIRAddStreamOrErr =
1611         IRCache(Task, IRKey, ModuleID);
1612     if (Error Err = CacheIRAddStreamOrErr.takeError())
1613       return Err;
1614     AddStreamFn &CacheIRAddStream = *CacheIRAddStreamOrErr;
1615 
1616     // Ideally, both CG and IR caching should be synchronized. However, in
1617     // practice, their availability may differ due to different expiration
1618     // times. Therefore, if either cache is missing, the backend process is
1619     // triggered.
1620     if (CacheCGAddStream || CacheIRAddStream) {
1621       LLVM_DEBUG(dbgs() << "[FirstRound] Cache Miss for "
1622                         << BM.getModuleIdentifier() << "\n");
1623       return RunThinBackend(CacheCGAddStream ? CacheCGAddStream : CGAddStream,
1624                             CacheIRAddStream ? CacheIRAddStream : IRAddStream);
1625     }
1626 
1627     return Error::success();
1628   }
1629 };
1630 
1631 /// This backend operates in the second round of a two-codegen round process.
1632 /// It starts by reading the optimized bitcode files that were saved during the
1633 /// first round. The backend then executes the codegen only to further optimize
1634 /// the code, utilizing the codegen data merged from the first round. Finally,
1635 /// it writes the resulting object files as usual.
1636 class SecondRoundThinBackend : public InProcessThinBackend {
1637   std::unique_ptr<SmallVector<StringRef>> IRFiles;
1638   stable_hash CombinedCGDataHash;
1639 
1640 public:
1641   SecondRoundThinBackend(
1642       const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1643       ThreadPoolStrategy ThinLTOParallelism,
1644       const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1645       AddStreamFn AddStream, FileCache Cache,
1646       std::unique_ptr<SmallVector<StringRef>> IRFiles,
1647       stable_hash CombinedCGDataHash)
1648       : InProcessThinBackend(Conf, CombinedIndex, ThinLTOParallelism,
1649                              ModuleToDefinedGVSummaries, std::move(AddStream),
1650                              std::move(Cache),
1651                              /*OnWrite=*/nullptr,
1652                              /*ShouldEmitIndexFiles=*/false,
1653                              /*ShouldEmitImportsFiles=*/false),
1654         IRFiles(std::move(IRFiles)), CombinedCGDataHash(CombinedCGDataHash) {}
1655 
1656   virtual Error runThinLTOBackendThread(
1657       AddStreamFn AddStream, FileCache Cache, unsigned Task, BitcodeModule BM,
1658       ModuleSummaryIndex &CombinedIndex,
1659       const FunctionImporter::ImportMapTy &ImportList,
1660       const FunctionImporter::ExportSetTy &ExportList,
1661       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1662       const GVSummaryMapTy &DefinedGlobals,
1663       MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1664     auto RunThinBackend = [&](AddStreamFn AddStream) {
1665       LTOLLVMContext BackendContext(Conf);
1666       std::unique_ptr<Module> LoadedModule =
1667           cgdata::loadModuleForTwoRounds(BM, Task, BackendContext, *IRFiles);
1668 
1669       return thinBackend(Conf, Task, AddStream, *LoadedModule, CombinedIndex,
1670                          ImportList, DefinedGlobals, &ModuleMap,
1671                          /*CodeGenOnly=*/true);
1672     };
1673 
1674     auto ModuleID = BM.getModuleIdentifier();
1675     if (!Cache.isValid() || !CombinedIndex.modulePaths().count(ModuleID) ||
1676         all_of(CombinedIndex.getModuleHash(ModuleID),
1677                [](uint32_t V) { return V == 0; }))
1678       // Cache disabled or no entry for this module in the combined index or
1679       // no module hash.
1680       return RunThinBackend(AddStream);
1681 
1682     // Get Key for caching the final object file in Cache with the combined
1683     // CGData hash.
1684     std::string Key = computeLTOCacheKey(
1685         Conf, CombinedIndex, ModuleID, ImportList, ExportList, ResolvedODR,
1686         DefinedGlobals, CfiFunctionDefs, CfiFunctionDecls);
1687     Key = recomputeLTOCacheKey(Key,
1688                                /*ExtraID=*/std::to_string(CombinedCGDataHash));
1689     Expected<AddStreamFn> CacheAddStreamOrErr = Cache(Task, Key, ModuleID);
1690     if (Error Err = CacheAddStreamOrErr.takeError())
1691       return Err;
1692     AddStreamFn &CacheAddStream = *CacheAddStreamOrErr;
1693 
1694     if (CacheAddStream) {
1695       LLVM_DEBUG(dbgs() << "[SecondRound] Cache Miss for "
1696                         << BM.getModuleIdentifier() << "\n");
1697       return RunThinBackend(CacheAddStream);
1698     }
1699 
1700     return Error::success();
1701   }
1702 };
1703 } // end anonymous namespace
1704 
1705 ThinBackend lto::createInProcessThinBackend(ThreadPoolStrategy Parallelism,
1706                                             lto::IndexWriteCallback OnWrite,
1707                                             bool ShouldEmitIndexFiles,
1708                                             bool ShouldEmitImportsFiles) {
1709   auto Func =
1710       [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1711           const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1712           AddStreamFn AddStream, FileCache Cache) {
1713         return std::make_unique<InProcessThinBackend>(
1714             Conf, CombinedIndex, Parallelism, ModuleToDefinedGVSummaries,
1715             AddStream, Cache, OnWrite, ShouldEmitIndexFiles,
1716             ShouldEmitImportsFiles);
1717       };
1718   return ThinBackend(Func, Parallelism);
1719 }
1720 
1721 StringLiteral lto::getThinLTODefaultCPU(const Triple &TheTriple) {
1722   if (!TheTriple.isOSDarwin())
1723     return "";
1724   if (TheTriple.getArch() == Triple::x86_64)
1725     return "core2";
1726   if (TheTriple.getArch() == Triple::x86)
1727     return "yonah";
1728   if (TheTriple.isArm64e())
1729     return "apple-a12";
1730   if (TheTriple.getArch() == Triple::aarch64 ||
1731       TheTriple.getArch() == Triple::aarch64_32)
1732     return "cyclone";
1733   return "";
1734 }
1735 
1736 // Given the original \p Path to an output file, replace any path
1737 // prefix matching \p OldPrefix with \p NewPrefix. Also, create the
1738 // resulting directory if it does not yet exist.
1739 std::string lto::getThinLTOOutputFile(StringRef Path, StringRef OldPrefix,
1740                                       StringRef NewPrefix) {
1741   if (OldPrefix.empty() && NewPrefix.empty())
1742     return std::string(Path);
1743   SmallString<128> NewPath(Path);
1744   llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
1745   StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
1746   if (!ParentPath.empty()) {
1747     // Make sure the new directory exists, creating it if necessary.
1748     if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
1749       llvm::errs() << "warning: could not create directory '" << ParentPath
1750                    << "': " << EC.message() << '\n';
1751   }
1752   return std::string(NewPath);
1753 }
1754 
1755 namespace {
1756 class WriteIndexesThinBackend : public ThinBackendProc {
1757   std::string OldPrefix, NewPrefix, NativeObjectPrefix;
1758   raw_fd_ostream *LinkedObjectsFile;
1759 
1760 public:
1761   WriteIndexesThinBackend(
1762       const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1763       ThreadPoolStrategy ThinLTOParallelism,
1764       const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1765       std::string OldPrefix, std::string NewPrefix,
1766       std::string NativeObjectPrefix, bool ShouldEmitImportsFiles,
1767       raw_fd_ostream *LinkedObjectsFile, lto::IndexWriteCallback OnWrite)
1768       : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries,
1769                         OnWrite, ShouldEmitImportsFiles, ThinLTOParallelism),
1770         OldPrefix(OldPrefix), NewPrefix(NewPrefix),
1771         NativeObjectPrefix(NativeObjectPrefix),
1772         LinkedObjectsFile(LinkedObjectsFile) {}
1773 
1774   Error start(
1775       unsigned Task, BitcodeModule BM,
1776       const FunctionImporter::ImportMapTy &ImportList,
1777       const FunctionImporter::ExportSetTy &ExportList,
1778       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
1779       MapVector<StringRef, BitcodeModule> &ModuleMap) override {
1780     StringRef ModulePath = BM.getModuleIdentifier();
1781 
1782     // The contents of this file may be used as input to a native link, and must
1783     // therefore contain the processed modules in a determinstic order that
1784     // match the order they are provided on the command line. For that reason,
1785     // we cannot include this in the asynchronously executed lambda below.
1786     if (LinkedObjectsFile) {
1787       std::string ObjectPrefix =
1788           NativeObjectPrefix.empty() ? NewPrefix : NativeObjectPrefix;
1789       std::string LinkedObjectsFilePath =
1790           getThinLTOOutputFile(ModulePath, OldPrefix, ObjectPrefix);
1791       *LinkedObjectsFile << LinkedObjectsFilePath << '\n';
1792     }
1793 
1794     BackendThreadPool.async(
1795         [this](const StringRef ModulePath,
1796                const FunctionImporter::ImportMapTy &ImportList,
1797                const std::string &OldPrefix, const std::string &NewPrefix) {
1798           std::string NewModulePath =
1799               getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
1800           auto E = emitFiles(ImportList, ModulePath, NewModulePath);
1801           if (E) {
1802             std::unique_lock<std::mutex> L(ErrMu);
1803             if (Err)
1804               Err = joinErrors(std::move(*Err), std::move(E));
1805             else
1806               Err = std::move(E);
1807             return;
1808           }
1809         },
1810         ModulePath, ImportList, OldPrefix, NewPrefix);
1811 
1812     if (OnWrite)
1813       OnWrite(std::string(ModulePath));
1814     return Error::success();
1815   }
1816 
1817   bool isSensitiveToInputOrder() override {
1818     // The order which modules are written to LinkedObjectsFile should be
1819     // deterministic and match the order they are passed on the command line.
1820     return true;
1821   }
1822 };
1823 } // end anonymous namespace
1824 
1825 ThinBackend lto::createWriteIndexesThinBackend(
1826     ThreadPoolStrategy Parallelism, std::string OldPrefix,
1827     std::string NewPrefix, std::string NativeObjectPrefix,
1828     bool ShouldEmitImportsFiles, raw_fd_ostream *LinkedObjectsFile,
1829     IndexWriteCallback OnWrite) {
1830   auto Func =
1831       [=](const Config &Conf, ModuleSummaryIndex &CombinedIndex,
1832           const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
1833           AddStreamFn AddStream, FileCache Cache) {
1834         return std::make_unique<WriteIndexesThinBackend>(
1835             Conf, CombinedIndex, Parallelism, ModuleToDefinedGVSummaries,
1836             OldPrefix, NewPrefix, NativeObjectPrefix, ShouldEmitImportsFiles,
1837             LinkedObjectsFile, OnWrite);
1838       };
1839   return ThinBackend(Func, Parallelism);
1840 }
1841 
1842 Error LTO::runThinLTO(AddStreamFn AddStream, FileCache Cache,
1843                       const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
1844   LLVM_DEBUG(dbgs() << "Running ThinLTO\n");
1845   ThinLTO.CombinedIndex.releaseTemporaryMemory();
1846   timeTraceProfilerBegin("ThinLink", StringRef(""));
1847   auto TimeTraceScopeExit = llvm::make_scope_exit([]() {
1848     if (llvm::timeTraceProfilerEnabled())
1849       llvm::timeTraceProfilerEnd();
1850   });
1851   if (ThinLTO.ModuleMap.empty())
1852     return Error::success();
1853 
1854   if (ThinLTO.ModulesToCompile && ThinLTO.ModulesToCompile->empty()) {
1855     llvm::errs() << "warning: [ThinLTO] No module compiled\n";
1856     return Error::success();
1857   }
1858 
1859   if (Conf.CombinedIndexHook &&
1860       !Conf.CombinedIndexHook(ThinLTO.CombinedIndex, GUIDPreservedSymbols))
1861     return Error::success();
1862 
1863   // Collect for each module the list of function it defines (GUID ->
1864   // Summary).
1865   DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(
1866       ThinLTO.ModuleMap.size());
1867   ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
1868       ModuleToDefinedGVSummaries);
1869   // Create entries for any modules that didn't have any GV summaries
1870   // (either they didn't have any GVs to start with, or we suppressed
1871   // generation of the summaries because they e.g. had inline assembly
1872   // uses that couldn't be promoted/renamed on export). This is so
1873   // InProcessThinBackend::start can still launch a backend thread, which
1874   // is passed the map of summaries for the module, without any special
1875   // handling for this case.
1876   for (auto &Mod : ThinLTO.ModuleMap)
1877     if (!ModuleToDefinedGVSummaries.count(Mod.first))
1878       ModuleToDefinedGVSummaries.try_emplace(Mod.first);
1879 
1880   FunctionImporter::ImportListsTy ImportLists(ThinLTO.ModuleMap.size());
1881   DenseMap<StringRef, FunctionImporter::ExportSetTy> ExportLists(
1882       ThinLTO.ModuleMap.size());
1883   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
1884 
1885   if (DumpThinCGSCCs)
1886     ThinLTO.CombinedIndex.dumpSCCs(outs());
1887 
1888   std::set<GlobalValue::GUID> ExportedGUIDs;
1889 
1890   bool WholeProgramVisibilityEnabledInLTO =
1891       Conf.HasWholeProgramVisibility &&
1892       // If validation is enabled, upgrade visibility only when all vtables
1893       // have typeinfos.
1894       (!Conf.ValidateAllVtablesHaveTypeInfos || Conf.AllVtablesHaveTypeInfos);
1895   if (hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO))
1896     ThinLTO.CombinedIndex.setWithWholeProgramVisibility();
1897 
1898   // If we're validating, get the vtable symbols that should not be
1899   // upgraded because they correspond to typeIDs outside of index-based
1900   // WPD info.
1901   DenseSet<GlobalValue::GUID> VisibleToRegularObjSymbols;
1902   if (WholeProgramVisibilityEnabledInLTO &&
1903       Conf.ValidateAllVtablesHaveTypeInfos) {
1904     // This returns true when the name is local or not defined. Locals are
1905     // expected to be handled separately.
1906     auto IsVisibleToRegularObj = [&](StringRef name) {
1907       auto It = GlobalResolutions->find(name);
1908       return (It == GlobalResolutions->end() ||
1909               It->second.VisibleOutsideSummary);
1910     };
1911 
1912     getVisibleToRegularObjVtableGUIDs(ThinLTO.CombinedIndex,
1913                                       VisibleToRegularObjSymbols,
1914                                       IsVisibleToRegularObj);
1915   }
1916 
1917   // If allowed, upgrade public vcall visibility to linkage unit visibility in
1918   // the summaries before whole program devirtualization below.
1919   updateVCallVisibilityInIndex(
1920       ThinLTO.CombinedIndex, WholeProgramVisibilityEnabledInLTO,
1921       DynamicExportSymbols, VisibleToRegularObjSymbols);
1922 
1923   // Perform index-based WPD. This will return immediately if there are
1924   // no index entries in the typeIdMetadata map (e.g. if we are instead
1925   // performing IR-based WPD in hybrid regular/thin LTO mode).
1926   std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
1927   runWholeProgramDevirtOnIndex(ThinLTO.CombinedIndex, ExportedGUIDs,
1928                                LocalWPDTargetsMap);
1929 
1930   auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
1931     return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
1932   };
1933   if (EnableMemProfContextDisambiguation) {
1934     MemProfContextDisambiguation ContextDisambiguation;
1935     ContextDisambiguation.run(ThinLTO.CombinedIndex, isPrevailing);
1936   }
1937 
1938   // Figure out which symbols need to be internalized. This also needs to happen
1939   // at -O0 because summary-based DCE is implemented using internalization, and
1940   // we must apply DCE consistently with the full LTO module in order to avoid
1941   // undefined references during the final link.
1942   for (auto &Res : *GlobalResolutions) {
1943     // If the symbol does not have external references or it is not prevailing,
1944     // then not need to mark it as exported from a ThinLTO partition.
1945     if (Res.second.Partition != GlobalResolution::External ||
1946         !Res.second.isPrevailingIRSymbol())
1947       continue;
1948     auto GUID = GlobalValue::getGUID(
1949         GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
1950     // Mark exported unless index-based analysis determined it to be dead.
1951     if (ThinLTO.CombinedIndex.isGUIDLive(GUID))
1952       ExportedGUIDs.insert(GUID);
1953   }
1954 
1955   // Reset the GlobalResolutions to deallocate the associated memory, as there
1956   // are no further accesses. We specifically want to do this before computing
1957   // cross module importing, which adds to peak memory via the computed import
1958   // and export lists.
1959   releaseGlobalResolutionsMemory();
1960 
1961   if (Conf.OptLevel > 0)
1962     ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
1963                              isPrevailing, ImportLists, ExportLists);
1964 
1965   // Any functions referenced by the jump table in the regular LTO object must
1966   // be exported.
1967   for (auto &Def : ThinLTO.CombinedIndex.cfiFunctionDefs())
1968     ExportedGUIDs.insert(
1969         GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Def)));
1970   for (auto &Decl : ThinLTO.CombinedIndex.cfiFunctionDecls())
1971     ExportedGUIDs.insert(
1972         GlobalValue::getGUID(GlobalValue::dropLLVMManglingEscape(Decl)));
1973 
1974   auto isExported = [&](StringRef ModuleIdentifier, ValueInfo VI) {
1975     const auto &ExportList = ExportLists.find(ModuleIdentifier);
1976     return (ExportList != ExportLists.end() && ExportList->second.count(VI)) ||
1977            ExportedGUIDs.count(VI.getGUID());
1978   };
1979 
1980   // Update local devirtualized targets that were exported by cross-module
1981   // importing or by other devirtualizations marked in the ExportedGUIDs set.
1982   updateIndexWPDForExports(ThinLTO.CombinedIndex, isExported,
1983                            LocalWPDTargetsMap);
1984 
1985   thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported,
1986                                       isPrevailing);
1987 
1988   auto recordNewLinkage = [&](StringRef ModuleIdentifier,
1989                               GlobalValue::GUID GUID,
1990                               GlobalValue::LinkageTypes NewLinkage) {
1991     ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
1992   };
1993   thinLTOResolvePrevailingInIndex(Conf, ThinLTO.CombinedIndex, isPrevailing,
1994                                   recordNewLinkage, GUIDPreservedSymbols);
1995 
1996   thinLTOPropagateFunctionAttrs(ThinLTO.CombinedIndex, isPrevailing);
1997 
1998   generateParamAccessSummary(ThinLTO.CombinedIndex);
1999 
2000   if (llvm::timeTraceProfilerEnabled())
2001     llvm::timeTraceProfilerEnd();
2002 
2003   TimeTraceScopeExit.release();
2004 
2005   auto &ModuleMap =
2006       ThinLTO.ModulesToCompile ? *ThinLTO.ModulesToCompile : ThinLTO.ModuleMap;
2007 
2008   auto RunBackends = [&](ThinBackendProc *BackendProcess) -> Error {
2009     auto ProcessOneModule = [&](int I) -> Error {
2010       auto &Mod = *(ModuleMap.begin() + I);
2011       // Tasks 0 through ParallelCodeGenParallelismLevel-1 are reserved for
2012       // combined module and parallel code generation partitions.
2013       return BackendProcess->start(
2014           RegularLTO.ParallelCodeGenParallelismLevel + I, Mod.second,
2015           ImportLists[Mod.first], ExportLists[Mod.first],
2016           ResolvedODR[Mod.first], ThinLTO.ModuleMap);
2017     };
2018 
2019     if (BackendProcess->getThreadCount() == 1 ||
2020         BackendProcess->isSensitiveToInputOrder()) {
2021       // Process the modules in the order they were provided on the
2022       // command-line. It is important for this codepath to be used for
2023       // WriteIndexesThinBackend, to ensure the emitted LinkedObjectsFile lists
2024       // ThinLTO objects in the same order as the inputs, which otherwise would
2025       // affect the final link order.
2026       for (int I = 0, E = ModuleMap.size(); I != E; ++I)
2027         if (Error E = ProcessOneModule(I))
2028           return E;
2029     } else {
2030       // When executing in parallel, process largest bitsize modules first to
2031       // improve parallelism, and avoid starving the thread pool near the end.
2032       // This saves about 15 sec on a 36-core machine while link `clang.exe`
2033       // (out of 100 sec).
2034       std::vector<BitcodeModule *> ModulesVec;
2035       ModulesVec.reserve(ModuleMap.size());
2036       for (auto &Mod : ModuleMap)
2037         ModulesVec.push_back(&Mod.second);
2038       for (int I : generateModulesOrdering(ModulesVec))
2039         if (Error E = ProcessOneModule(I))
2040           return E;
2041     }
2042     return BackendProcess->wait();
2043   };
2044 
2045   if (!CodeGenDataThinLTOTwoRounds) {
2046     std::unique_ptr<ThinBackendProc> BackendProc =
2047         ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
2048                         AddStream, Cache);
2049     return RunBackends(BackendProc.get());
2050   }
2051 
2052   // Perform two rounds of code generation for ThinLTO:
2053   // 1. First round: Perform optimization and code generation, outputting to
2054   // temporary scratch objects.
2055   // 2. Merge code generation data extracted from the temporary scratch objects.
2056   // 3. Second round: Execute code generation again using the merged data.
2057   LLVM_DEBUG(dbgs() << "[TwoRounds] Initializing ThinLTO two-codegen rounds\n");
2058 
2059   unsigned MaxTasks = getMaxTasks();
2060   auto Parallelism = ThinLTO.Backend.getParallelism();
2061   // Set up two additional streams and caches for storing temporary scratch
2062   // objects and optimized IRs, using the same cache directory as the original.
2063   cgdata::StreamCacheData CG(MaxTasks, Cache, "CG"), IR(MaxTasks, Cache, "IR");
2064 
2065   // First round: Execute optimization and code generation, outputting to
2066   // temporary scratch objects. Serialize the optimized IRs before initiating
2067   // code generation.
2068   LLVM_DEBUG(dbgs() << "[TwoRounds] Running the first round of codegen\n");
2069   auto FirstRoundLTO = std::make_unique<FirstRoundThinBackend>(
2070       Conf, ThinLTO.CombinedIndex, Parallelism, ModuleToDefinedGVSummaries,
2071       CG.AddStream, CG.Cache, IR.AddStream, IR.Cache);
2072   if (Error E = RunBackends(FirstRoundLTO.get()))
2073     return E;
2074 
2075   LLVM_DEBUG(dbgs() << "[TwoRounds] Merging codegen data\n");
2076   auto CombinedHashOrErr = cgdata::mergeCodeGenData(*CG.getResult());
2077   if (Error E = CombinedHashOrErr.takeError())
2078     return E;
2079   auto CombinedHash = *CombinedHashOrErr;
2080   LLVM_DEBUG(dbgs() << "[TwoRounds] CGData hash: " << CombinedHash << "\n");
2081 
2082   // Second round: Read the optimized IRs and execute code generation using the
2083   // merged data.
2084   LLVM_DEBUG(dbgs() << "[TwoRounds] Running the second round of codegen\n");
2085   auto SecondRoundLTO = std::make_unique<SecondRoundThinBackend>(
2086       Conf, ThinLTO.CombinedIndex, Parallelism, ModuleToDefinedGVSummaries,
2087       AddStream, Cache, IR.getResult(), CombinedHash);
2088   return RunBackends(SecondRoundLTO.get());
2089 }
2090 
2091 Expected<std::unique_ptr<ToolOutputFile>> lto::setupLLVMOptimizationRemarks(
2092     LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses,
2093     StringRef RemarksFormat, bool RemarksWithHotness,
2094     std::optional<uint64_t> RemarksHotnessThreshold, int Count) {
2095   std::string Filename = std::string(RemarksFilename);
2096   // For ThinLTO, file.opt.<format> becomes
2097   // file.opt.<format>.thin.<num>.<format>.
2098   if (!Filename.empty() && Count != -1)
2099     Filename =
2100         (Twine(Filename) + ".thin." + llvm::utostr(Count) + "." + RemarksFormat)
2101             .str();
2102 
2103   auto ResultOrErr = llvm::setupLLVMOptimizationRemarks(
2104       Context, Filename, RemarksPasses, RemarksFormat, RemarksWithHotness,
2105       RemarksHotnessThreshold);
2106   if (Error E = ResultOrErr.takeError())
2107     return std::move(E);
2108 
2109   if (*ResultOrErr)
2110     (*ResultOrErr)->keep();
2111 
2112   return ResultOrErr;
2113 }
2114 
2115 Expected<std::unique_ptr<ToolOutputFile>>
2116 lto::setupStatsFile(StringRef StatsFilename) {
2117   // Setup output file to emit statistics.
2118   if (StatsFilename.empty())
2119     return nullptr;
2120 
2121   llvm::EnableStatistics(false);
2122   std::error_code EC;
2123   auto StatsFile =
2124       std::make_unique<ToolOutputFile>(StatsFilename, EC, sys::fs::OF_None);
2125   if (EC)
2126     return errorCodeToError(EC);
2127 
2128   StatsFile->keep();
2129   return std::move(StatsFile);
2130 }
2131 
2132 // Compute the ordering we will process the inputs: the rough heuristic here
2133 // is to sort them per size so that the largest module get schedule as soon as
2134 // possible. This is purely a compile-time optimization.
2135 std::vector<int> lto::generateModulesOrdering(ArrayRef<BitcodeModule *> R) {
2136   auto Seq = llvm::seq<int>(0, R.size());
2137   std::vector<int> ModulesOrdering(Seq.begin(), Seq.end());
2138   llvm::sort(ModulesOrdering, [&](int LeftIndex, int RightIndex) {
2139     auto LSize = R[LeftIndex]->getBuffer().size();
2140     auto RSize = R[RightIndex]->getBuffer().size();
2141     return LSize > RSize;
2142   });
2143   return ModulesOrdering;
2144 }
2145