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