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