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