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