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