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