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