xref: /llvm-project-15.0.7/llvm/lib/LTO/LTO.cpp (revision e17a155c)
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/LTO/LTOBackend.h"
24 #include "llvm/Linker/IRMover.h"
25 #include "llvm/Object/ModuleSummaryIndexObjectFile.h"
26 #include "llvm/Support/ManagedStatic.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/Path.h"
29 #include "llvm/Support/SHA1.h"
30 #include "llvm/Support/SourceMgr.h"
31 #include "llvm/Support/TargetRegistry.h"
32 #include "llvm/Support/ThreadPool.h"
33 #include "llvm/Support/Threading.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Transforms/IPO.h"
38 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
39 #include "llvm/Transforms/Utils/SplitModule.h"
40 
41 #include <set>
42 
43 using namespace llvm;
44 using namespace lto;
45 using namespace object;
46 
47 #define DEBUG_TYPE "lto"
48 
49 // Returns a unique hash for the Module considering the current list of
50 // export/import and other global analysis results.
51 // The hash is produced in \p Key.
52 static void computeCacheKey(
53     SmallString<40> &Key, const ModuleSummaryIndex &Index, StringRef ModuleID,
54     const FunctionImporter::ImportMapTy &ImportList,
55     const FunctionImporter::ExportSetTy &ExportList,
56     const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
57     const GVSummaryMapTy &DefinedGlobals) {
58   // Compute the unique hash for this entry.
59   // This is based on the current compiler version, the module itself, the
60   // export list, the hash for every single module in the import list, the
61   // list of ResolvedODR for the module, and the list of preserved symbols.
62   SHA1 Hasher;
63 
64   // Start with the compiler revision
65   Hasher.update(LLVM_VERSION_STRING);
66 #ifdef HAVE_LLVM_REVISION
67   Hasher.update(LLVM_REVISION);
68 #endif
69 
70   // Include the hash for the current module
71   auto ModHash = Index.getModuleHash(ModuleID);
72   Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
73   for (auto F : ExportList)
74     // The export list can impact the internalization, be conservative here
75     Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
76 
77   // Include the hash for every module we import functions from
78   for (auto &Entry : ImportList) {
79     auto ModHash = Index.getModuleHash(Entry.first());
80     Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
81   }
82 
83   // Include the hash for the resolved ODR.
84   for (auto &Entry : ResolvedODR) {
85     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
86                                     sizeof(GlobalValue::GUID)));
87     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
88                                     sizeof(GlobalValue::LinkageTypes)));
89   }
90 
91   // Include the hash for the linkage type to reflect internalization and weak
92   // resolution.
93   for (auto &GS : DefinedGlobals) {
94     GlobalValue::LinkageTypes Linkage = GS.second->linkage();
95     Hasher.update(
96         ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
97   }
98 
99   Key = toHex(Hasher.result());
100 }
101 
102 static void thinLTOResolveWeakForLinkerGUID(
103     GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
104     DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
105     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
106         isPrevailing,
107     function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
108         recordNewLinkage) {
109   for (auto &S : GVSummaryList) {
110     GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
111     if (!GlobalValue::isWeakForLinker(OriginalLinkage))
112       continue;
113     // We need to emit only one of these. The prevailing module will keep it,
114     // but turned into a weak, while the others will drop it when possible.
115     // This is both a compile-time optimization and a correctness
116     // transformation. This is necessary for correctness when we have exported
117     // a reference - we need to convert the linkonce to weak to
118     // ensure a copy is kept to satisfy the exported reference.
119     // FIXME: We may want to split the compile time and correctness
120     // aspects into separate routines.
121     if (isPrevailing(GUID, S.get())) {
122       if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
123         S->setLinkage(GlobalValue::getWeakLinkage(
124             GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
125     }
126     // Alias and aliasee can't be turned into available_externally.
127     else if (!isa<AliasSummary>(S.get()) &&
128              !GlobalInvolvedWithAlias.count(S.get()) &&
129              (GlobalValue::isLinkOnceODRLinkage(OriginalLinkage) ||
130               GlobalValue::isWeakODRLinkage(OriginalLinkage)))
131       S->setLinkage(GlobalValue::AvailableExternallyLinkage);
132     if (S->linkage() != OriginalLinkage)
133       recordNewLinkage(S->modulePath(), GUID, S->linkage());
134   }
135 }
136 
137 // Resolve Weak and LinkOnce values in the \p Index.
138 //
139 // We'd like to drop these functions if they are no longer referenced in the
140 // current module. However there is a chance that another module is still
141 // referencing them because of the import. We make sure we always emit at least
142 // one copy.
143 void llvm::thinLTOResolveWeakForLinkerInIndex(
144     ModuleSummaryIndex &Index,
145     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
146         isPrevailing,
147     function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
148         recordNewLinkage) {
149   // We won't optimize the globals that are referenced by an alias for now
150   // Ideally we should turn the alias into a global and duplicate the definition
151   // when needed.
152   DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
153   for (auto &I : Index)
154     for (auto &S : I.second)
155       if (auto AS = dyn_cast<AliasSummary>(S.get()))
156         GlobalInvolvedWithAlias.insert(&AS->getAliasee());
157 
158   for (auto &I : Index)
159     thinLTOResolveWeakForLinkerGUID(I.second, I.first, GlobalInvolvedWithAlias,
160                                     isPrevailing, recordNewLinkage);
161 }
162 
163 static void thinLTOInternalizeAndPromoteGUID(
164     GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
165     function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
166   for (auto &S : GVSummaryList) {
167     if (isExported(S->modulePath(), GUID)) {
168       if (GlobalValue::isLocalLinkage(S->linkage()))
169         S->setLinkage(GlobalValue::ExternalLinkage);
170     } else if (!GlobalValue::isLocalLinkage(S->linkage()))
171       S->setLinkage(GlobalValue::InternalLinkage);
172   }
173 }
174 
175 // Update the linkages in the given \p Index to mark exported values
176 // as external and non-exported values as internal.
177 void llvm::thinLTOInternalizeAndPromoteInIndex(
178     ModuleSummaryIndex &Index,
179     function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
180   for (auto &I : Index)
181     thinLTOInternalizeAndPromoteGUID(I.second, I.first, isExported);
182 }
183 
184 Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
185   std::unique_ptr<InputFile> File(new InputFile);
186 
187   Expected<std::unique_ptr<object::IRObjectFile>> IRObj =
188       IRObjectFile::create(Object, File->Ctx);
189   if (!IRObj)
190     return IRObj.takeError();
191   File->Obj = std::move(*IRObj);
192 
193   for (const auto &C : File->Obj->getModule().getComdatSymbolTable()) {
194     auto P =
195         File->ComdatMap.insert(std::make_pair(&C.second, File->Comdats.size()));
196     assert(P.second);
197     (void)P;
198     File->Comdats.push_back(C.first());
199   }
200 
201   return std::move(File);
202 }
203 
204 Expected<int> InputFile::Symbol::getComdatIndex() const {
205   if (!GV)
206     return -1;
207   const GlobalObject *GO;
208   if (auto *GA = dyn_cast<GlobalAlias>(GV)) {
209     GO = GA->getBaseObject();
210     if (!GO)
211       return make_error<StringError>("Unable to determine comdat of alias!",
212                                      inconvertibleErrorCode());
213   } else {
214     GO = cast<GlobalObject>(GV);
215   }
216   if (const Comdat *C = GO->getComdat()) {
217     auto I = File->ComdatMap.find(C);
218     assert(I != File->ComdatMap.end());
219     return I->second;
220   }
221   return -1;
222 }
223 
224 LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
225                                       Config &Conf)
226     : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
227       Ctx(Conf) {}
228 
229 LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) : Backend(Backend) {
230   if (!Backend)
231     this->Backend =
232         createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
233 }
234 
235 LTO::LTO(Config Conf, ThinBackend Backend,
236          unsigned ParallelCodeGenParallelismLevel)
237     : Conf(std::move(Conf)),
238       RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
239       ThinLTO(std::move(Backend)) {}
240 
241 // Add the given symbol to the GlobalResolutions map, and resolve its partition.
242 void LTO::addSymbolToGlobalRes(IRObjectFile *Obj,
243                                SmallPtrSet<GlobalValue *, 8> &Used,
244                                const InputFile::Symbol &Sym,
245                                SymbolResolution Res, unsigned Partition) {
246   GlobalValue *GV = Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
247 
248   auto &GlobalRes = GlobalResolutions[Sym.getName()];
249   if (GV) {
250     GlobalRes.UnnamedAddr &= GV->hasGlobalUnnamedAddr();
251     if (Res.Prevailing)
252       GlobalRes.IRName = GV->getName();
253   }
254   if (Res.VisibleToRegularObj || (GV && Used.count(GV)) ||
255       (GlobalRes.Partition != GlobalResolution::Unknown &&
256        GlobalRes.Partition != Partition))
257     GlobalRes.Partition = GlobalResolution::External;
258   else
259     GlobalRes.Partition = Partition;
260 }
261 
262 static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
263                                   ArrayRef<SymbolResolution> Res) {
264   StringRef Path = Input->getMemoryBufferRef().getBufferIdentifier();
265   OS << Path << '\n';
266   auto ResI = Res.begin();
267   for (const InputFile::Symbol &Sym : Input->symbols()) {
268     assert(ResI != Res.end());
269     SymbolResolution Res = *ResI++;
270 
271     OS << "-r=" << Path << ',' << Sym.getName() << ',';
272     if (Res.Prevailing)
273       OS << 'p';
274     if (Res.FinalDefinitionInLinkageUnit)
275       OS << 'l';
276     if (Res.VisibleToRegularObj)
277       OS << 'x';
278     OS << '\n';
279   }
280   assert(ResI == Res.end());
281 }
282 
283 Error LTO::add(std::unique_ptr<InputFile> Input,
284                ArrayRef<SymbolResolution> Res) {
285   assert(!CalledGetMaxTasks);
286 
287   if (Conf.ResolutionFile)
288     writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
289 
290   // FIXME: move to backend
291   Module &M = Input->Obj->getModule();
292   if (!Conf.OverrideTriple.empty())
293     M.setTargetTriple(Conf.OverrideTriple);
294   else if (M.getTargetTriple().empty())
295     M.setTargetTriple(Conf.DefaultTriple);
296 
297   MemoryBufferRef MBRef = Input->Obj->getMemoryBufferRef();
298   Expected<bool> HasThinLTOSummary = hasGlobalValueSummary(MBRef);
299   if (!HasThinLTOSummary)
300     return HasThinLTOSummary.takeError();
301 
302   if (*HasThinLTOSummary)
303     return addThinLTO(std::move(Input), Res);
304   else
305     return addRegularLTO(std::move(Input), Res);
306 }
307 
308 // Add a regular LTO object to the link.
309 Error LTO::addRegularLTO(std::unique_ptr<InputFile> Input,
310                          ArrayRef<SymbolResolution> Res) {
311   if (!RegularLTO.CombinedModule) {
312     RegularLTO.CombinedModule =
313         llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
314     RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
315   }
316   Expected<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
317       IRObjectFile::create(Input->Obj->getMemoryBufferRef(), RegularLTO.Ctx);
318   if (!ObjOrErr)
319     return ObjOrErr.takeError();
320   std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
321 
322   Module &M = Obj->getModule();
323   if (Error Err = M.materializeMetadata())
324     return Err;
325   UpgradeDebugInfo(M);
326 
327   SmallPtrSet<GlobalValue *, 8> Used;
328   collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
329 
330   std::vector<GlobalValue *> Keep;
331 
332   for (GlobalVariable &GV : M.globals())
333     if (GV.hasAppendingLinkage())
334       Keep.push_back(&GV);
335 
336   auto ResI = Res.begin();
337   for (const InputFile::Symbol &Sym :
338        make_range(InputFile::symbol_iterator(Obj->symbol_begin(), nullptr),
339                   InputFile::symbol_iterator(Obj->symbol_end(), nullptr))) {
340     assert(ResI != Res.end());
341     SymbolResolution Res = *ResI++;
342     addSymbolToGlobalRes(Obj.get(), Used, Sym, Res, 0);
343 
344     GlobalValue *GV = Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
345     if (Sym.getFlags() & object::BasicSymbolRef::SF_Undefined)
346       continue;
347     if (Res.Prevailing && GV) {
348       Keep.push_back(GV);
349       switch (GV->getLinkage()) {
350       default:
351         break;
352       case GlobalValue::LinkOnceAnyLinkage:
353         GV->setLinkage(GlobalValue::WeakAnyLinkage);
354         break;
355       case GlobalValue::LinkOnceODRLinkage:
356         GV->setLinkage(GlobalValue::WeakODRLinkage);
357         break;
358       }
359     }
360     // Common resolution: collect the maximum size/alignment over all commons.
361     // We also record if we see an instance of a common as prevailing, so that
362     // if none is prevailing we can ignore it later.
363     if (Sym.getFlags() & object::BasicSymbolRef::SF_Common) {
364       // FIXME: We should figure out what to do about commons defined by asm.
365       // For now they aren't reported correctly by ModuleSymbolTable.
366       assert(GV);
367       auto &CommonRes = RegularLTO.Commons[GV->getName()];
368       CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
369       CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
370       CommonRes.Prevailing |= Res.Prevailing;
371     }
372 
373     // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
374   }
375   assert(ResI == Res.end());
376 
377   return RegularLTO.Mover->move(Obj->takeModule(), Keep,
378                                 [](GlobalValue &, IRMover::ValueAdder) {},
379                                 /* LinkModuleInlineAsm */ true);
380 }
381 
382 // Add a ThinLTO object to the link.
383 Error LTO::addThinLTO(std::unique_ptr<InputFile> Input,
384                       ArrayRef<SymbolResolution> Res) {
385   Module &M = Input->Obj->getModule();
386   SmallPtrSet<GlobalValue *, 8> Used;
387   collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
388 
389   MemoryBufferRef MBRef = Input->Obj->getMemoryBufferRef();
390   Expected<std::unique_ptr<object::ModuleSummaryIndexObjectFile>>
391       SummaryObjOrErr = object::ModuleSummaryIndexObjectFile::create(MBRef);
392   if (!SummaryObjOrErr)
393     return SummaryObjOrErr.takeError();
394   ThinLTO.CombinedIndex.mergeFrom((*SummaryObjOrErr)->takeIndex(),
395                                   ThinLTO.ModuleMap.size());
396 
397   auto ResI = Res.begin();
398   for (const InputFile::Symbol &Sym : Input->symbols()) {
399     assert(ResI != Res.end());
400     SymbolResolution Res = *ResI++;
401     addSymbolToGlobalRes(Input->Obj.get(), Used, Sym, Res,
402                          ThinLTO.ModuleMap.size() + 1);
403 
404     GlobalValue *GV = Input->Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
405     if (Res.Prevailing && GV)
406       ThinLTO.PrevailingModuleForGUID[GV->getGUID()] =
407           MBRef.getBufferIdentifier();
408   }
409   assert(ResI == Res.end());
410 
411   ThinLTO.ModuleMap[MBRef.getBufferIdentifier()] = MBRef;
412   return Error::success();
413 }
414 
415 unsigned LTO::getMaxTasks() const {
416   CalledGetMaxTasks = true;
417   return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
418 }
419 
420 Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
421   // Save the status of having a regularLTO combined module, as
422   // this is needed for generating the ThinLTO Task ID, and
423   // the CombinedModule will be moved at the end of runRegularLTO.
424   bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
425   // Invoke regular LTO if there was a regular LTO module to start with.
426   if (HasRegularLTO)
427     if (auto E = runRegularLTO(AddStream))
428       return E;
429   return runThinLTO(AddStream, Cache, HasRegularLTO);
430 }
431 
432 Error LTO::runRegularLTO(AddStreamFn AddStream) {
433   // Make sure commons have the right size/alignment: we kept the largest from
434   // all the prevailing when adding the inputs, and we apply it here.
435   const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
436   for (auto &I : RegularLTO.Commons) {
437     if (!I.second.Prevailing)
438       // Don't do anything if no instance of this common was prevailing.
439       continue;
440     GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
441     if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
442       // Don't create a new global if the type is already correct, just make
443       // sure the alignment is correct.
444       OldGV->setAlignment(I.second.Align);
445       continue;
446     }
447     ArrayType *Ty =
448         ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
449     auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
450                                   GlobalValue::CommonLinkage,
451                                   ConstantAggregateZero::get(Ty), "");
452     GV->setAlignment(I.second.Align);
453     if (OldGV) {
454       OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
455       GV->takeName(OldGV);
456       OldGV->eraseFromParent();
457     } else {
458       GV->setName(I.first);
459     }
460   }
461 
462   if (Conf.PreOptModuleHook &&
463       !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
464     return Error::success();
465 
466   if (!Conf.CodeGenOnly) {
467     for (const auto &R : GlobalResolutions) {
468       if (R.second.IRName.empty())
469         continue;
470       if (R.second.Partition != 0 &&
471           R.second.Partition != GlobalResolution::External)
472         continue;
473 
474       GlobalValue *GV =
475           RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
476       // Ignore symbols defined in other partitions.
477       if (!GV || GV->hasLocalLinkage())
478         continue;
479       GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
480                                               : GlobalValue::UnnamedAddr::None);
481       if (R.second.Partition == 0)
482         GV->setLinkage(GlobalValue::InternalLinkage);
483     }
484 
485     if (Conf.PostInternalizeModuleHook &&
486         !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
487       return Error::success();
488   }
489   return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
490                  std::move(RegularLTO.CombinedModule));
491 }
492 
493 /// This class defines the interface to the ThinLTO backend.
494 class lto::ThinBackendProc {
495 protected:
496   Config &Conf;
497   ModuleSummaryIndex &CombinedIndex;
498   const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
499 
500 public:
501   ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
502                   const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
503       : Conf(Conf), CombinedIndex(CombinedIndex),
504         ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
505 
506   virtual ~ThinBackendProc() {}
507   virtual Error start(
508       unsigned Task, MemoryBufferRef MBRef,
509       const FunctionImporter::ImportMapTy &ImportList,
510       const FunctionImporter::ExportSetTy &ExportList,
511       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
512       MapVector<StringRef, MemoryBufferRef> &ModuleMap) = 0;
513   virtual Error wait() = 0;
514 };
515 
516 namespace {
517 class InProcessThinBackend : public ThinBackendProc {
518   ThreadPool BackendThreadPool;
519   AddStreamFn AddStream;
520   NativeObjectCache Cache;
521 
522   Optional<Error> Err;
523   std::mutex ErrMu;
524 
525 public:
526   InProcessThinBackend(
527       Config &Conf, ModuleSummaryIndex &CombinedIndex,
528       unsigned ThinLTOParallelismLevel,
529       const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
530       AddStreamFn AddStream, NativeObjectCache Cache)
531       : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
532         BackendThreadPool(ThinLTOParallelismLevel),
533         AddStream(std::move(AddStream)), Cache(std::move(Cache)) {}
534 
535   Error runThinLTOBackendThread(
536       AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
537       MemoryBufferRef MBRef, ModuleSummaryIndex &CombinedIndex,
538       const FunctionImporter::ImportMapTy &ImportList,
539       const FunctionImporter::ExportSetTy &ExportList,
540       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
541       const GVSummaryMapTy &DefinedGlobals,
542       MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
543     auto RunThinBackend = [&](AddStreamFn AddStream) {
544       LTOLLVMContext BackendContext(Conf);
545       Expected<std::unique_ptr<Module>> MOrErr =
546           parseBitcodeFile(MBRef, BackendContext);
547       if (!MOrErr)
548         return MOrErr.takeError();
549 
550       return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
551                          ImportList, DefinedGlobals, ModuleMap);
552     };
553 
554     auto ModuleID = MBRef.getBufferIdentifier();
555 
556     if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
557         all_of(CombinedIndex.getModuleHash(ModuleID),
558                [](uint32_t V) { return V == 0; }))
559       // Cache disabled or no entry for this module in the combined index or
560       // no module hash.
561       return RunThinBackend(AddStream);
562 
563     SmallString<40> Key;
564     // The module may be cached, this helps handling it.
565     computeCacheKey(Key, CombinedIndex, ModuleID, ImportList, ExportList,
566                     ResolvedODR, DefinedGlobals);
567     if (AddStreamFn CacheAddStream = Cache(Task, Key))
568       return RunThinBackend(CacheAddStream);
569 
570     return Error::success();
571   }
572 
573   Error start(
574       unsigned Task, MemoryBufferRef MBRef,
575       const FunctionImporter::ImportMapTy &ImportList,
576       const FunctionImporter::ExportSetTy &ExportList,
577       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
578       MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
579     StringRef ModulePath = MBRef.getBufferIdentifier();
580     assert(ModuleToDefinedGVSummaries.count(ModulePath));
581     const GVSummaryMapTy &DefinedGlobals =
582         ModuleToDefinedGVSummaries.find(ModulePath)->second;
583     BackendThreadPool.async(
584         [=](MemoryBufferRef MBRef, ModuleSummaryIndex &CombinedIndex,
585             const FunctionImporter::ImportMapTy &ImportList,
586             const FunctionImporter::ExportSetTy &ExportList,
587             const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
588                 &ResolvedODR,
589             const GVSummaryMapTy &DefinedGlobals,
590             MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
591           Error E = runThinLTOBackendThread(
592               AddStream, Cache, Task, MBRef, CombinedIndex, ImportList,
593               ExportList, ResolvedODR, DefinedGlobals, ModuleMap);
594           if (E) {
595             std::unique_lock<std::mutex> L(ErrMu);
596             if (Err)
597               Err = joinErrors(std::move(*Err), std::move(E));
598             else
599               Err = std::move(E);
600           }
601         },
602         MBRef, std::ref(CombinedIndex), std::ref(ImportList),
603         std::ref(ExportList), std::ref(ResolvedODR), std::ref(DefinedGlobals),
604         std::ref(ModuleMap));
605     return Error::success();
606   }
607 
608   Error wait() override {
609     BackendThreadPool.wait();
610     if (Err)
611       return std::move(*Err);
612     else
613       return Error::success();
614   }
615 };
616 } // end anonymous namespace
617 
618 ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
619   return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
620              const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
621              AddStreamFn AddStream, NativeObjectCache Cache) {
622     return llvm::make_unique<InProcessThinBackend>(
623         Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
624         AddStream, Cache);
625   };
626 }
627 
628 // Given the original \p Path to an output file, replace any path
629 // prefix matching \p OldPrefix with \p NewPrefix. Also, create the
630 // resulting directory if it does not yet exist.
631 std::string lto::getThinLTOOutputFile(const std::string &Path,
632                                       const std::string &OldPrefix,
633                                       const std::string &NewPrefix) {
634   if (OldPrefix.empty() && NewPrefix.empty())
635     return Path;
636   SmallString<128> NewPath(Path);
637   llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
638   StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
639   if (!ParentPath.empty()) {
640     // Make sure the new directory exists, creating it if necessary.
641     if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
642       llvm::errs() << "warning: could not create directory '" << ParentPath
643                    << "': " << EC.message() << '\n';
644   }
645   return NewPath.str();
646 }
647 
648 namespace {
649 class WriteIndexesThinBackend : public ThinBackendProc {
650   std::string OldPrefix, NewPrefix;
651   bool ShouldEmitImportsFiles;
652 
653   std::string LinkedObjectsFileName;
654   std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
655 
656 public:
657   WriteIndexesThinBackend(
658       Config &Conf, ModuleSummaryIndex &CombinedIndex,
659       const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
660       std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
661       std::string LinkedObjectsFileName)
662       : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
663         OldPrefix(OldPrefix), NewPrefix(NewPrefix),
664         ShouldEmitImportsFiles(ShouldEmitImportsFiles),
665         LinkedObjectsFileName(LinkedObjectsFileName) {}
666 
667   Error start(
668       unsigned Task, MemoryBufferRef MBRef,
669       const FunctionImporter::ImportMapTy &ImportList,
670       const FunctionImporter::ExportSetTy &ExportList,
671       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
672       MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
673     StringRef ModulePath = MBRef.getBufferIdentifier();
674     std::string NewModulePath =
675         getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
676 
677     std::error_code EC;
678     if (!LinkedObjectsFileName.empty()) {
679       if (!LinkedObjectsFile) {
680         LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
681             LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
682         if (EC)
683           return errorCodeToError(EC);
684       }
685       *LinkedObjectsFile << NewModulePath << '\n';
686     }
687 
688     std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
689     gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
690                                      ImportList, ModuleToSummariesForIndex);
691 
692     raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
693                       sys::fs::OpenFlags::F_None);
694     if (EC)
695       return errorCodeToError(EC);
696     WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
697 
698     if (ShouldEmitImportsFiles)
699       return errorCodeToError(
700           EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
701     return Error::success();
702   }
703 
704   Error wait() override { return Error::success(); }
705 };
706 } // end anonymous namespace
707 
708 ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
709                                                std::string NewPrefix,
710                                                bool ShouldEmitImportsFiles,
711                                                std::string LinkedObjectsFile) {
712   return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
713              const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
714              AddStreamFn AddStream, NativeObjectCache Cache) {
715     return llvm::make_unique<WriteIndexesThinBackend>(
716         Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
717         ShouldEmitImportsFiles, LinkedObjectsFile);
718   };
719 }
720 
721 Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
722                       bool HasRegularLTO) {
723   if (ThinLTO.ModuleMap.empty())
724     return Error::success();
725 
726   if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
727     return Error::success();
728 
729   // Collect for each module the list of function it defines (GUID ->
730   // Summary).
731   StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
732       ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
733   ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
734       ModuleToDefinedGVSummaries);
735   // Create entries for any modules that didn't have any GV summaries
736   // (either they didn't have any GVs to start with, or we suppressed
737   // generation of the summaries because they e.g. had inline assembly
738   // uses that couldn't be promoted/renamed on export). This is so
739   // InProcessThinBackend::start can still launch a backend thread, which
740   // is passed the map of summaries for the module, without any special
741   // handling for this case.
742   for (auto &Mod : ThinLTO.ModuleMap)
743     if (!ModuleToDefinedGVSummaries.count(Mod.first))
744       ModuleToDefinedGVSummaries.try_emplace(Mod.first);
745 
746   StringMap<FunctionImporter::ImportMapTy> ImportLists(
747       ThinLTO.ModuleMap.size());
748   StringMap<FunctionImporter::ExportSetTy> ExportLists(
749       ThinLTO.ModuleMap.size());
750   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
751 
752   if (Conf.OptLevel > 0) {
753     ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
754                              ImportLists, ExportLists);
755 
756     std::set<GlobalValue::GUID> ExportedGUIDs;
757     for (auto &Res : GlobalResolutions) {
758       if (!Res.second.IRName.empty() &&
759           Res.second.Partition == GlobalResolution::External)
760         ExportedGUIDs.insert(GlobalValue::getGUID(Res.second.IRName));
761     }
762 
763     auto isPrevailing = [&](GlobalValue::GUID GUID,
764                             const GlobalValueSummary *S) {
765       return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
766     };
767     auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
768       const auto &ExportList = ExportLists.find(ModuleIdentifier);
769       return (ExportList != ExportLists.end() &&
770               ExportList->second.count(GUID)) ||
771              ExportedGUIDs.count(GUID);
772     };
773     thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
774 
775     auto recordNewLinkage = [&](StringRef ModuleIdentifier,
776                                 GlobalValue::GUID GUID,
777                                 GlobalValue::LinkageTypes NewLinkage) {
778       ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
779     };
780 
781     thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
782                                        recordNewLinkage);
783   }
784 
785   std::unique_ptr<ThinBackendProc> BackendProc =
786       ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
787                       AddStream, Cache);
788 
789   // Partition numbers for ThinLTO jobs start at 1 (see comments for
790   // GlobalResolution in LTO.h). Task numbers, however, start at
791   // ParallelCodeGenParallelismLevel if an LTO module is present, as tasks 0
792   // through ParallelCodeGenParallelismLevel-1 are reserved for parallel code
793   // generation partitions.
794   unsigned Task =
795       HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
796   unsigned Partition = 1;
797 
798   for (auto &Mod : ThinLTO.ModuleMap) {
799     if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
800                                      ExportLists[Mod.first],
801                                      ResolvedODR[Mod.first], ThinLTO.ModuleMap))
802       return E;
803 
804     ++Task;
805     ++Partition;
806   }
807 
808   return BackendProc->wait();
809 }
810