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