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