xref: /llvm-project-15.0.7/llvm/lib/LTO/LTO.cpp (revision ee123223)
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/CodeGen/TargetLoweringObjectFileImpl.h"
21 #include "llvm/IR/AutoUpgrade.h"
22 #include "llvm/IR/DiagnosticPrinter.h"
23 #include "llvm/IR/LegacyPassManager.h"
24 #include "llvm/IR/Mangler.h"
25 #include "llvm/IR/Metadata.h"
26 #include "llvm/LTO/LTOBackend.h"
27 #include "llvm/Linker/IRMover.h"
28 #include "llvm/Object/ModuleSummaryIndexObjectFile.h"
29 #include "llvm/Support/Error.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/Path.h"
33 #include "llvm/Support/SHA1.h"
34 #include "llvm/Support/SourceMgr.h"
35 #include "llvm/Support/TargetRegistry.h"
36 #include "llvm/Support/ThreadPool.h"
37 #include "llvm/Support/Threading.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 // Returns a unique hash for the Module considering the current list of
54 // export/import and other global analysis results.
55 // The hash is produced in \p Key.
56 static void computeCacheKey(
57     SmallString<40> &Key, const Config &Conf, const ModuleSummaryIndex &Index,
58     StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList,
59     const FunctionImporter::ExportSetTy &ExportList,
60     const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
61     const GVSummaryMapTy &DefinedGlobals) {
62   // Compute the unique hash for this entry.
63   // This is based on the current compiler version, the module itself, the
64   // export list, the hash for every single module in the import list, the
65   // list of ResolvedODR for the module, and the list of preserved symbols.
66   SHA1 Hasher;
67 
68   // Start with the compiler revision
69   Hasher.update(LLVM_VERSION_STRING);
70 #ifdef HAVE_LLVM_REVISION
71   Hasher.update(LLVM_REVISION);
72 #endif
73 
74   // Include the parts of the LTO configuration that affect code generation.
75   auto AddString = [&](StringRef Str) {
76     Hasher.update(Str);
77     Hasher.update(ArrayRef<uint8_t>{0});
78   };
79   auto AddUnsigned = [&](unsigned I) {
80     uint8_t Data[4];
81     Data[0] = I;
82     Data[1] = I >> 8;
83     Data[2] = I >> 16;
84     Data[3] = I >> 24;
85     Hasher.update(ArrayRef<uint8_t>{Data, 4});
86   };
87   AddString(Conf.CPU);
88   // FIXME: Hash more of Options. For now all clients initialize Options from
89   // command-line flags (which is unsupported in production), but may set
90   // RelaxELFRelocations. The clang driver can also pass FunctionSections,
91   // DataSections and DebuggerTuning via command line flags.
92   AddUnsigned(Conf.Options.RelaxELFRelocations);
93   AddUnsigned(Conf.Options.FunctionSections);
94   AddUnsigned(Conf.Options.DataSections);
95   AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
96   for (auto &A : Conf.MAttrs)
97     AddString(A);
98   AddUnsigned(Conf.RelocModel);
99   AddUnsigned(Conf.CodeModel);
100   AddUnsigned(Conf.CGOptLevel);
101   AddUnsigned(Conf.OptLevel);
102   AddString(Conf.OptPipeline);
103   AddString(Conf.AAPipeline);
104   AddString(Conf.OverrideTriple);
105   AddString(Conf.DefaultTriple);
106 
107   // Include the hash for the current module
108   auto ModHash = Index.getModuleHash(ModuleID);
109   Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
110   for (auto F : ExportList)
111     // The export list can impact the internalization, be conservative here
112     Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
113 
114   // Include the hash for every module we import functions from
115   for (auto &Entry : ImportList) {
116     auto ModHash = Index.getModuleHash(Entry.first());
117     Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
118   }
119 
120   // Include the hash for the resolved ODR.
121   for (auto &Entry : ResolvedODR) {
122     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
123                                     sizeof(GlobalValue::GUID)));
124     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
125                                     sizeof(GlobalValue::LinkageTypes)));
126   }
127 
128   // Include the hash for the linkage type to reflect internalization and weak
129   // resolution.
130   for (auto &GS : DefinedGlobals) {
131     GlobalValue::LinkageTypes Linkage = GS.second->linkage();
132     Hasher.update(
133         ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
134   }
135 
136   if (!Conf.SampleProfile.empty()) {
137     auto FileOrErr = MemoryBuffer::getFile(Conf.SampleProfile);
138     if (FileOrErr)
139       Hasher.update(FileOrErr.get()->getBuffer());
140   }
141 
142   Key = toHex(Hasher.result());
143 }
144 
145 static void thinLTOResolveWeakForLinkerGUID(
146     GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
147     DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
148     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
149         isPrevailing,
150     function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
151         recordNewLinkage) {
152   for (auto &S : GVSummaryList) {
153     GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
154     if (!GlobalValue::isWeakForLinker(OriginalLinkage))
155       continue;
156     // We need to emit only one of these. The prevailing module will keep it,
157     // but turned into a weak, while the others will drop it when possible.
158     // This is both a compile-time optimization and a correctness
159     // transformation. This is necessary for correctness when we have exported
160     // a reference - we need to convert the linkonce to weak to
161     // ensure a copy is kept to satisfy the exported reference.
162     // FIXME: We may want to split the compile time and correctness
163     // aspects into separate routines.
164     if (isPrevailing(GUID, S.get())) {
165       if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
166         S->setLinkage(GlobalValue::getWeakLinkage(
167             GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
168     }
169     // Alias and aliasee can't be turned into available_externally.
170     else if (!isa<AliasSummary>(S.get()) &&
171              !GlobalInvolvedWithAlias.count(S.get()))
172       S->setLinkage(GlobalValue::AvailableExternallyLinkage);
173     if (S->linkage() != OriginalLinkage)
174       recordNewLinkage(S->modulePath(), GUID, S->linkage());
175   }
176 }
177 
178 // Resolve Weak and LinkOnce values in the \p Index.
179 //
180 // We'd like to drop these functions if they are no longer referenced in the
181 // current module. However there is a chance that another module is still
182 // referencing them because of the import. We make sure we always emit at least
183 // one copy.
184 void llvm::thinLTOResolveWeakForLinkerInIndex(
185     ModuleSummaryIndex &Index,
186     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
187         isPrevailing,
188     function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
189         recordNewLinkage) {
190   // We won't optimize the globals that are referenced by an alias for now
191   // Ideally we should turn the alias into a global and duplicate the definition
192   // when needed.
193   DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
194   for (auto &I : Index)
195     for (auto &S : I.second)
196       if (auto AS = dyn_cast<AliasSummary>(S.get()))
197         GlobalInvolvedWithAlias.insert(&AS->getAliasee());
198 
199   for (auto &I : Index)
200     thinLTOResolveWeakForLinkerGUID(I.second, I.first, GlobalInvolvedWithAlias,
201                                     isPrevailing, recordNewLinkage);
202 }
203 
204 static void thinLTOInternalizeAndPromoteGUID(
205     GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
206     function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
207   for (auto &S : GVSummaryList) {
208     if (isExported(S->modulePath(), GUID)) {
209       if (GlobalValue::isLocalLinkage(S->linkage()))
210         S->setLinkage(GlobalValue::ExternalLinkage);
211     } else if (!GlobalValue::isLocalLinkage(S->linkage()))
212       S->setLinkage(GlobalValue::InternalLinkage);
213   }
214 }
215 
216 // Update the linkages in the given \p Index to mark exported values
217 // as external and non-exported values as internal.
218 void llvm::thinLTOInternalizeAndPromoteInIndex(
219     ModuleSummaryIndex &Index,
220     function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
221   for (auto &I : Index)
222     thinLTOInternalizeAndPromoteGUID(I.second, I.first, isExported);
223 }
224 
225 struct InputFile::InputModule {
226   BitcodeModule BM;
227   std::unique_ptr<Module> Mod;
228 
229   // The range of ModuleSymbolTable entries for this input module.
230   size_t SymBegin, SymEnd;
231 };
232 
233 // Requires a destructor for std::vector<InputModule>.
234 InputFile::~InputFile() = default;
235 
236 Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
237   std::unique_ptr<InputFile> File(new InputFile);
238 
239   ErrorOr<MemoryBufferRef> BCOrErr =
240       IRObjectFile::findBitcodeInMemBuffer(Object);
241   if (!BCOrErr)
242     return errorCodeToError(BCOrErr.getError());
243 
244   Expected<std::vector<BitcodeModule>> BMsOrErr =
245       getBitcodeModuleList(*BCOrErr);
246   if (!BMsOrErr)
247     return BMsOrErr.takeError();
248 
249   if (BMsOrErr->empty())
250     return make_error<StringError>("Bitcode file does not contain any modules",
251                                    inconvertibleErrorCode());
252 
253   // Create an InputModule for each module in the InputFile, and add it to the
254   // ModuleSymbolTable.
255   for (auto BM : *BMsOrErr) {
256     Expected<std::unique_ptr<Module>> MOrErr =
257         BM.getLazyModule(File->Ctx, /*ShouldLazyLoadMetadata*/ true,
258                          /*IsImporting*/ false);
259     if (!MOrErr)
260       return MOrErr.takeError();
261 
262     size_t SymBegin = File->SymTab.symbols().size();
263     File->SymTab.addModule(MOrErr->get());
264     size_t SymEnd = File->SymTab.symbols().size();
265 
266     for (const auto &C : (*MOrErr)->getComdatSymbolTable()) {
267       auto P = File->ComdatMap.insert(
268           std::make_pair(&C.second, File->Comdats.size()));
269       assert(P.second);
270       (void)P;
271       File->Comdats.push_back(C.first());
272     }
273 
274     File->Mods.push_back({BM, std::move(*MOrErr), SymBegin, SymEnd});
275   }
276 
277   return std::move(File);
278 }
279 
280 Expected<int> InputFile::Symbol::getComdatIndex() const {
281   if (!isGV())
282     return -1;
283   const GlobalObject *GO = getGV()->getBaseObject();
284   if (!GO)
285     return make_error<StringError>("Unable to determine comdat of alias!",
286                                    inconvertibleErrorCode());
287   if (const Comdat *C = GO->getComdat()) {
288     auto I = File->ComdatMap.find(C);
289     assert(I != File->ComdatMap.end());
290     return I->second;
291   }
292   return -1;
293 }
294 
295 Expected<std::string> InputFile::getLinkerOpts() {
296   std::string LinkerOpts;
297   raw_string_ostream LOS(LinkerOpts);
298   // Extract linker options from module metadata.
299   for (InputModule &Mod : Mods) {
300     std::unique_ptr<Module> &M = Mod.Mod;
301     if (auto E = M->materializeMetadata())
302       return std::move(E);
303     if (Metadata *Val = M->getModuleFlag("Linker Options")) {
304       MDNode *LinkerOptions = cast<MDNode>(Val);
305       for (const MDOperand &MDOptions : LinkerOptions->operands())
306         for (const MDOperand &MDOption : cast<MDNode>(MDOptions)->operands())
307           LOS << " " << cast<MDString>(MDOption)->getString();
308     }
309   }
310 
311   // Synthesize export flags for symbols with dllexport storage.
312   const Triple TT(Mods[0].Mod->getTargetTriple());
313   Mangler M;
314   for (const ModuleSymbolTable::Symbol &Sym : SymTab.symbols())
315     if (auto *GV = Sym.dyn_cast<GlobalValue*>())
316       emitLinkerFlagsForGlobalCOFF(LOS, GV, TT, M);
317   LOS.flush();
318   return LinkerOpts;
319 }
320 
321 StringRef InputFile::getName() const {
322   return Mods[0].BM.getModuleIdentifier();
323 }
324 
325 StringRef InputFile::getSourceFileName() const {
326   return Mods[0].Mod->getSourceFileName();
327 }
328 
329 iterator_range<InputFile::symbol_iterator>
330 InputFile::module_symbols(InputModule &IM) {
331   return llvm::make_range(
332       symbol_iterator(SymTab.symbols().data() + IM.SymBegin, SymTab, this),
333       symbol_iterator(SymTab.symbols().data() + IM.SymEnd, SymTab, this));
334 }
335 
336 LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
337                                       Config &Conf)
338     : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
339       Ctx(Conf) {}
340 
341 LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) : Backend(Backend) {
342   if (!Backend)
343     this->Backend =
344         createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
345 }
346 
347 LTO::LTO(Config Conf, ThinBackend Backend,
348          unsigned ParallelCodeGenParallelismLevel)
349     : Conf(std::move(Conf)),
350       RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
351       ThinLTO(std::move(Backend)) {}
352 
353 // Requires a destructor for MapVector<BitcodeModule>.
354 LTO::~LTO() = default;
355 
356 // Add the given symbol to the GlobalResolutions map, and resolve its partition.
357 void LTO::addSymbolToGlobalRes(SmallPtrSet<GlobalValue *, 8> &Used,
358                                const InputFile::Symbol &Sym,
359                                SymbolResolution Res, unsigned Partition) {
360   GlobalValue *GV = Sym.isGV() ? Sym.getGV() : nullptr;
361 
362   auto &GlobalRes = GlobalResolutions[Sym.getName()];
363   if (GV) {
364     GlobalRes.UnnamedAddr &= GV->hasGlobalUnnamedAddr();
365     if (Res.Prevailing)
366       GlobalRes.IRName = GV->getName();
367   }
368   // Set the partition to external if we know it is used elsewhere, e.g.
369   // it is visible to a regular object, is referenced from llvm.compiler_used,
370   // or was already recorded as being referenced from a different partition.
371   if (Res.VisibleToRegularObj || (GV && Used.count(GV)) ||
372       (GlobalRes.Partition != GlobalResolution::Unknown &&
373        GlobalRes.Partition != Partition)) {
374     GlobalRes.Partition = GlobalResolution::External;
375   } else
376     // First recorded reference, save the current partition.
377     GlobalRes.Partition = Partition;
378 
379   // Flag as visible outside of ThinLTO if visible from a regular object or
380   // if this is a reference in the regular LTO partition.
381   GlobalRes.VisibleOutsideThinLTO |=
382       (Res.VisibleToRegularObj || (Partition == GlobalResolution::RegularLTO));
383 }
384 
385 static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
386                                   ArrayRef<SymbolResolution> Res) {
387   StringRef Path = Input->getName();
388   OS << Path << '\n';
389   auto ResI = Res.begin();
390   for (const InputFile::Symbol &Sym : Input->symbols()) {
391     assert(ResI != Res.end());
392     SymbolResolution Res = *ResI++;
393 
394     OS << "-r=" << Path << ',' << Sym.getName() << ',';
395     if (Res.Prevailing)
396       OS << 'p';
397     if (Res.FinalDefinitionInLinkageUnit)
398       OS << 'l';
399     if (Res.VisibleToRegularObj)
400       OS << 'x';
401     OS << '\n';
402   }
403   OS.flush();
404   assert(ResI == Res.end());
405 }
406 
407 Error LTO::add(std::unique_ptr<InputFile> Input,
408                ArrayRef<SymbolResolution> Res) {
409   assert(!CalledGetMaxTasks);
410 
411   if (Conf.ResolutionFile)
412     writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
413 
414   const SymbolResolution *ResI = Res.begin();
415   for (InputFile::InputModule &IM : Input->Mods)
416     if (Error Err = addModule(*Input, IM, ResI, Res.end()))
417       return Err;
418 
419   assert(ResI == Res.end());
420   return Error::success();
421 }
422 
423 Error LTO::addModule(InputFile &Input, InputFile::InputModule &IM,
424                      const SymbolResolution *&ResI,
425                      const SymbolResolution *ResE) {
426   // FIXME: move to backend
427   Module &M = *IM.Mod;
428 
429   if (M.getDataLayoutStr().empty())
430     return make_error<StringError>("input module has no datalayout",
431                                     inconvertibleErrorCode());
432 
433   if (!Conf.OverrideTriple.empty())
434     M.setTargetTriple(Conf.OverrideTriple);
435   else if (M.getTargetTriple().empty())
436     M.setTargetTriple(Conf.DefaultTriple);
437 
438   Expected<bool> HasThinLTOSummary = IM.BM.hasSummary();
439   if (!HasThinLTOSummary)
440     return HasThinLTOSummary.takeError();
441 
442   if (*HasThinLTOSummary)
443     return addThinLTO(IM.BM, M, Input.module_symbols(IM), ResI, ResE);
444   else
445     return addRegularLTO(IM.BM, ResI, ResE);
446 }
447 
448 // Add a regular LTO object to the link.
449 Error LTO::addRegularLTO(BitcodeModule BM, const SymbolResolution *&ResI,
450                          const SymbolResolution *ResE) {
451   if (!RegularLTO.CombinedModule) {
452     RegularLTO.CombinedModule =
453         llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
454     RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
455   }
456   Expected<std::unique_ptr<Module>> MOrErr =
457       BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
458                        /*IsImporting*/ false);
459   if (!MOrErr)
460     return MOrErr.takeError();
461 
462   Module &M = **MOrErr;
463   if (Error Err = M.materializeMetadata())
464     return Err;
465   UpgradeDebugInfo(M);
466 
467   ModuleSymbolTable SymTab;
468   SymTab.addModule(&M);
469 
470   SmallPtrSet<GlobalValue *, 8> Used;
471   collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
472 
473   std::vector<GlobalValue *> Keep;
474 
475   for (GlobalVariable &GV : M.globals())
476     if (GV.hasAppendingLinkage())
477       Keep.push_back(&GV);
478 
479   DenseSet<GlobalObject *> AliasedGlobals;
480   for (auto &GA : M.aliases())
481     if (GlobalObject *GO = GA.getBaseObject())
482       AliasedGlobals.insert(GO);
483 
484   for (const InputFile::Symbol &Sym :
485        make_range(InputFile::symbol_iterator(SymTab.symbols().begin(), SymTab,
486                                              nullptr),
487                   InputFile::symbol_iterator(SymTab.symbols().end(), SymTab,
488                                              nullptr))) {
489     assert(ResI != ResE);
490     SymbolResolution Res = *ResI++;
491     addSymbolToGlobalRes(Used, Sym, Res, 0);
492 
493     if (Sym.isGV()) {
494       GlobalValue *GV = Sym.getGV();
495       if (Res.Prevailing) {
496         if (Sym.getFlags() & object::BasicSymbolRef::SF_Undefined)
497           continue;
498         Keep.push_back(GV);
499         switch (GV->getLinkage()) {
500         default:
501           break;
502         case GlobalValue::LinkOnceAnyLinkage:
503           GV->setLinkage(GlobalValue::WeakAnyLinkage);
504           break;
505         case GlobalValue::LinkOnceODRLinkage:
506           GV->setLinkage(GlobalValue::WeakODRLinkage);
507           break;
508         }
509       } else if (isa<GlobalObject>(GV) &&
510                  (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
511                   GV->hasAvailableExternallyLinkage()) &&
512                  !AliasedGlobals.count(cast<GlobalObject>(GV))) {
513         // Either of the above three types of linkage indicates that the
514         // chosen prevailing symbol will have the same semantics as this copy of
515         // the symbol, so we can link it with available_externally linkage. We
516         // only need to do this if the symbol is undefined.
517         GlobalValue *CombinedGV =
518             RegularLTO.CombinedModule->getNamedValue(GV->getName());
519         if (!CombinedGV || CombinedGV->isDeclaration()) {
520           Keep.push_back(GV);
521           GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
522           cast<GlobalObject>(GV)->setComdat(nullptr);
523         }
524       }
525     }
526     // Common resolution: collect the maximum size/alignment over all commons.
527     // We also record if we see an instance of a common as prevailing, so that
528     // if none is prevailing we can ignore it later.
529     if (Sym.getFlags() & object::BasicSymbolRef::SF_Common) {
530       // FIXME: We should figure out what to do about commons defined by asm.
531       // For now they aren't reported correctly by ModuleSymbolTable.
532       auto &CommonRes = RegularLTO.Commons[Sym.getGV()->getName()];
533       CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
534       CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
535       CommonRes.Prevailing |= Res.Prevailing;
536     }
537 
538     // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
539   }
540 
541   return RegularLTO.Mover->move(std::move(*MOrErr), Keep,
542                                 [](GlobalValue &, IRMover::ValueAdder) {},
543                                 /* IsPerformingImport */ false);
544 }
545 
546 // Add a ThinLTO object to the link.
547 // FIXME: This function should not need to take as many parameters once we have
548 // a bitcode symbol table.
549 Error LTO::addThinLTO(BitcodeModule BM, Module &M,
550                       iterator_range<InputFile::symbol_iterator> Syms,
551                       const SymbolResolution *&ResI,
552                       const SymbolResolution *ResE) {
553   SmallPtrSet<GlobalValue *, 8> Used;
554   collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
555 
556   Expected<std::unique_ptr<ModuleSummaryIndex>> SummaryOrErr = BM.getSummary();
557   if (!SummaryOrErr)
558     return SummaryOrErr.takeError();
559   ThinLTO.CombinedIndex.mergeFrom(std::move(*SummaryOrErr),
560                                   ThinLTO.ModuleMap.size());
561 
562   for (const InputFile::Symbol &Sym : Syms) {
563     assert(ResI != ResE);
564     SymbolResolution Res = *ResI++;
565     addSymbolToGlobalRes(Used, Sym, Res, ThinLTO.ModuleMap.size() + 1);
566 
567     if (Res.Prevailing && Sym.isGV())
568       ThinLTO.PrevailingModuleForGUID[Sym.getGV()->getGUID()] =
569           BM.getModuleIdentifier();
570   }
571 
572   if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
573     return make_error<StringError>(
574         "Expected at most one ThinLTO module per bitcode file",
575         inconvertibleErrorCode());
576 
577   return Error::success();
578 }
579 
580 unsigned LTO::getMaxTasks() const {
581   CalledGetMaxTasks = true;
582   return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
583 }
584 
585 Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
586   // Save the status of having a regularLTO combined module, as
587   // this is needed for generating the ThinLTO Task ID, and
588   // the CombinedModule will be moved at the end of runRegularLTO.
589   bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
590   // Invoke regular LTO if there was a regular LTO module to start with.
591   if (HasRegularLTO)
592     if (auto E = runRegularLTO(AddStream))
593       return E;
594   return runThinLTO(AddStream, Cache, HasRegularLTO);
595 }
596 
597 Error LTO::runRegularLTO(AddStreamFn AddStream) {
598   // Make sure commons have the right size/alignment: we kept the largest from
599   // all the prevailing when adding the inputs, and we apply it here.
600   const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
601   for (auto &I : RegularLTO.Commons) {
602     if (!I.second.Prevailing)
603       // Don't do anything if no instance of this common was prevailing.
604       continue;
605     GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
606     if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
607       // Don't create a new global if the type is already correct, just make
608       // sure the alignment is correct.
609       OldGV->setAlignment(I.second.Align);
610       continue;
611     }
612     ArrayType *Ty =
613         ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
614     auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
615                                   GlobalValue::CommonLinkage,
616                                   ConstantAggregateZero::get(Ty), "");
617     GV->setAlignment(I.second.Align);
618     if (OldGV) {
619       OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
620       GV->takeName(OldGV);
621       OldGV->eraseFromParent();
622     } else {
623       GV->setName(I.first);
624     }
625   }
626 
627   if (Conf.PreOptModuleHook &&
628       !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
629     return Error::success();
630 
631   if (!Conf.CodeGenOnly) {
632     for (const auto &R : GlobalResolutions) {
633       if (R.second.IRName.empty())
634         continue;
635       if (R.second.Partition != 0 &&
636           R.second.Partition != GlobalResolution::External)
637         continue;
638 
639       GlobalValue *GV =
640           RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
641       // Ignore symbols defined in other partitions.
642       if (!GV || GV->hasLocalLinkage())
643         continue;
644       GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
645                                               : GlobalValue::UnnamedAddr::None);
646       if (R.second.Partition == 0)
647         GV->setLinkage(GlobalValue::InternalLinkage);
648     }
649 
650     if (Conf.PostInternalizeModuleHook &&
651         !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
652       return Error::success();
653   }
654   return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
655                  std::move(RegularLTO.CombinedModule), ThinLTO.CombinedIndex);
656 }
657 
658 /// This class defines the interface to the ThinLTO backend.
659 class lto::ThinBackendProc {
660 protected:
661   Config &Conf;
662   ModuleSummaryIndex &CombinedIndex;
663   const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
664 
665 public:
666   ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
667                   const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
668       : Conf(Conf), CombinedIndex(CombinedIndex),
669         ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
670 
671   virtual ~ThinBackendProc() {}
672   virtual Error start(
673       unsigned Task, BitcodeModule BM,
674       const FunctionImporter::ImportMapTy &ImportList,
675       const FunctionImporter::ExportSetTy &ExportList,
676       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
677       MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
678   virtual Error wait() = 0;
679 };
680 
681 namespace {
682 class InProcessThinBackend : public ThinBackendProc {
683   ThreadPool BackendThreadPool;
684   AddStreamFn AddStream;
685   NativeObjectCache Cache;
686 
687   Optional<Error> Err;
688   std::mutex ErrMu;
689 
690 public:
691   InProcessThinBackend(
692       Config &Conf, ModuleSummaryIndex &CombinedIndex,
693       unsigned ThinLTOParallelismLevel,
694       const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
695       AddStreamFn AddStream, NativeObjectCache Cache)
696       : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
697         BackendThreadPool(ThinLTOParallelismLevel),
698         AddStream(std::move(AddStream)), Cache(std::move(Cache)) {}
699 
700   Error runThinLTOBackendThread(
701       AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
702       BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
703       const FunctionImporter::ImportMapTy &ImportList,
704       const FunctionImporter::ExportSetTy &ExportList,
705       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
706       const GVSummaryMapTy &DefinedGlobals,
707       MapVector<StringRef, BitcodeModule> &ModuleMap) {
708     auto RunThinBackend = [&](AddStreamFn AddStream) {
709       LTOLLVMContext BackendContext(Conf);
710       Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
711       if (!MOrErr)
712         return MOrErr.takeError();
713 
714       return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
715                          ImportList, DefinedGlobals, ModuleMap);
716     };
717 
718     auto ModuleID = BM.getModuleIdentifier();
719 
720     if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
721         all_of(CombinedIndex.getModuleHash(ModuleID),
722                [](uint32_t V) { return V == 0; }))
723       // Cache disabled or no entry for this module in the combined index or
724       // no module hash.
725       return RunThinBackend(AddStream);
726 
727     SmallString<40> Key;
728     // The module may be cached, this helps handling it.
729     computeCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList, ExportList,
730                     ResolvedODR, DefinedGlobals);
731     if (AddStreamFn CacheAddStream = Cache(Task, Key))
732       return RunThinBackend(CacheAddStream);
733 
734     return Error::success();
735   }
736 
737   Error start(
738       unsigned Task, BitcodeModule BM,
739       const FunctionImporter::ImportMapTy &ImportList,
740       const FunctionImporter::ExportSetTy &ExportList,
741       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
742       MapVector<StringRef, BitcodeModule> &ModuleMap) override {
743     StringRef ModulePath = BM.getModuleIdentifier();
744     assert(ModuleToDefinedGVSummaries.count(ModulePath));
745     const GVSummaryMapTy &DefinedGlobals =
746         ModuleToDefinedGVSummaries.find(ModulePath)->second;
747     BackendThreadPool.async(
748         [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
749             const FunctionImporter::ImportMapTy &ImportList,
750             const FunctionImporter::ExportSetTy &ExportList,
751             const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
752                 &ResolvedODR,
753             const GVSummaryMapTy &DefinedGlobals,
754             MapVector<StringRef, BitcodeModule> &ModuleMap) {
755           Error E = runThinLTOBackendThread(
756               AddStream, Cache, Task, BM, CombinedIndex, ImportList,
757               ExportList, ResolvedODR, DefinedGlobals, ModuleMap);
758           if (E) {
759             std::unique_lock<std::mutex> L(ErrMu);
760             if (Err)
761               Err = joinErrors(std::move(*Err), std::move(E));
762             else
763               Err = std::move(E);
764           }
765         },
766         BM, std::ref(CombinedIndex), std::ref(ImportList),
767         std::ref(ExportList), std::ref(ResolvedODR), std::ref(DefinedGlobals),
768         std::ref(ModuleMap));
769     return Error::success();
770   }
771 
772   Error wait() override {
773     BackendThreadPool.wait();
774     if (Err)
775       return std::move(*Err);
776     else
777       return Error::success();
778   }
779 };
780 } // end anonymous namespace
781 
782 ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
783   return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
784              const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
785              AddStreamFn AddStream, NativeObjectCache Cache) {
786     return llvm::make_unique<InProcessThinBackend>(
787         Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
788         AddStream, Cache);
789   };
790 }
791 
792 // Given the original \p Path to an output file, replace any path
793 // prefix matching \p OldPrefix with \p NewPrefix. Also, create the
794 // resulting directory if it does not yet exist.
795 std::string lto::getThinLTOOutputFile(const std::string &Path,
796                                       const std::string &OldPrefix,
797                                       const std::string &NewPrefix) {
798   if (OldPrefix.empty() && NewPrefix.empty())
799     return Path;
800   SmallString<128> NewPath(Path);
801   llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
802   StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
803   if (!ParentPath.empty()) {
804     // Make sure the new directory exists, creating it if necessary.
805     if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
806       llvm::errs() << "warning: could not create directory '" << ParentPath
807                    << "': " << EC.message() << '\n';
808   }
809   return NewPath.str();
810 }
811 
812 namespace {
813 class WriteIndexesThinBackend : public ThinBackendProc {
814   std::string OldPrefix, NewPrefix;
815   bool ShouldEmitImportsFiles;
816 
817   std::string LinkedObjectsFileName;
818   std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
819 
820 public:
821   WriteIndexesThinBackend(
822       Config &Conf, ModuleSummaryIndex &CombinedIndex,
823       const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
824       std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
825       std::string LinkedObjectsFileName)
826       : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
827         OldPrefix(OldPrefix), NewPrefix(NewPrefix),
828         ShouldEmitImportsFiles(ShouldEmitImportsFiles),
829         LinkedObjectsFileName(LinkedObjectsFileName) {}
830 
831   Error start(
832       unsigned Task, BitcodeModule BM,
833       const FunctionImporter::ImportMapTy &ImportList,
834       const FunctionImporter::ExportSetTy &ExportList,
835       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
836       MapVector<StringRef, BitcodeModule> &ModuleMap) override {
837     StringRef ModulePath = BM.getModuleIdentifier();
838     std::string NewModulePath =
839         getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
840 
841     std::error_code EC;
842     if (!LinkedObjectsFileName.empty()) {
843       if (!LinkedObjectsFile) {
844         LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
845             LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
846         if (EC)
847           return errorCodeToError(EC);
848       }
849       *LinkedObjectsFile << NewModulePath << '\n';
850     }
851 
852     std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
853     gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
854                                      ImportList, ModuleToSummariesForIndex);
855 
856     raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
857                       sys::fs::OpenFlags::F_None);
858     if (EC)
859       return errorCodeToError(EC);
860     WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
861 
862     if (ShouldEmitImportsFiles)
863       return errorCodeToError(
864           EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
865     return Error::success();
866   }
867 
868   Error wait() override { return Error::success(); }
869 };
870 } // end anonymous namespace
871 
872 ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
873                                                std::string NewPrefix,
874                                                bool ShouldEmitImportsFiles,
875                                                std::string LinkedObjectsFile) {
876   return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
877              const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
878              AddStreamFn AddStream, NativeObjectCache Cache) {
879     return llvm::make_unique<WriteIndexesThinBackend>(
880         Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
881         ShouldEmitImportsFiles, LinkedObjectsFile);
882   };
883 }
884 
885 Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
886                       bool HasRegularLTO) {
887   if (ThinLTO.ModuleMap.empty())
888     return Error::success();
889 
890   if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
891     return Error::success();
892 
893   // Collect for each module the list of function it defines (GUID ->
894   // Summary).
895   StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
896       ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
897   ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
898       ModuleToDefinedGVSummaries);
899   // Create entries for any modules that didn't have any GV summaries
900   // (either they didn't have any GVs to start with, or we suppressed
901   // generation of the summaries because they e.g. had inline assembly
902   // uses that couldn't be promoted/renamed on export). This is so
903   // InProcessThinBackend::start can still launch a backend thread, which
904   // is passed the map of summaries for the module, without any special
905   // handling for this case.
906   for (auto &Mod : ThinLTO.ModuleMap)
907     if (!ModuleToDefinedGVSummaries.count(Mod.first))
908       ModuleToDefinedGVSummaries.try_emplace(Mod.first);
909 
910   StringMap<FunctionImporter::ImportMapTy> ImportLists(
911       ThinLTO.ModuleMap.size());
912   StringMap<FunctionImporter::ExportSetTy> ExportLists(
913       ThinLTO.ModuleMap.size());
914   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
915 
916   if (Conf.OptLevel > 0) {
917     // Compute "dead" symbols, we don't want to import/export these!
918     DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
919     for (auto &Res : GlobalResolutions) {
920       if (Res.second.VisibleOutsideThinLTO &&
921           // IRName will be defined if we have seen the prevailing copy of
922           // this value. If not, no need to preserve any ThinLTO copies.
923           !Res.second.IRName.empty())
924         GUIDPreservedSymbols.insert(GlobalValue::getGUID(Res.second.IRName));
925     }
926 
927     auto DeadSymbols =
928         computeDeadSymbols(ThinLTO.CombinedIndex, GUIDPreservedSymbols);
929 
930     ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
931                              ImportLists, ExportLists, &DeadSymbols);
932 
933     std::set<GlobalValue::GUID> ExportedGUIDs;
934     for (auto &Res : GlobalResolutions) {
935       // First check if the symbol was flagged as having external references.
936       if (Res.second.Partition != GlobalResolution::External)
937         continue;
938       // IRName will be defined if we have seen the prevailing copy of
939       // this value. If not, no need to mark as exported from a ThinLTO
940       // partition (and we can't get the GUID).
941       if (Res.second.IRName.empty())
942         continue;
943       auto GUID = GlobalValue::getGUID(Res.second.IRName);
944       // Mark exported unless index-based analysis determined it to be dead.
945       if (!DeadSymbols.count(GUID))
946         ExportedGUIDs.insert(GlobalValue::getGUID(Res.second.IRName));
947     }
948 
949     auto isPrevailing = [&](GlobalValue::GUID GUID,
950                             const GlobalValueSummary *S) {
951       return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
952     };
953     auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
954       const auto &ExportList = ExportLists.find(ModuleIdentifier);
955       return (ExportList != ExportLists.end() &&
956               ExportList->second.count(GUID)) ||
957              ExportedGUIDs.count(GUID);
958     };
959     thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
960 
961     auto recordNewLinkage = [&](StringRef ModuleIdentifier,
962                                 GlobalValue::GUID GUID,
963                                 GlobalValue::LinkageTypes NewLinkage) {
964       ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
965     };
966 
967     thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
968                                        recordNewLinkage);
969   }
970 
971   std::unique_ptr<ThinBackendProc> BackendProc =
972       ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
973                       AddStream, Cache);
974 
975   // Task numbers start at ParallelCodeGenParallelismLevel if an LTO
976   // module is present, as tasks 0 through ParallelCodeGenParallelismLevel-1
977   // are reserved for parallel code generation partitions.
978   unsigned Task =
979       HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
980   for (auto &Mod : ThinLTO.ModuleMap) {
981     if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
982                                      ExportLists[Mod.first],
983                                      ResolvedODR[Mod.first], ThinLTO.ModuleMap))
984       return E;
985     ++Task;
986   }
987 
988   return BackendProc->wait();
989 }
990