1 //===-ThinLTOCodeGenerator.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 the Thin Link Time Optimization library. This library is
11 // intended to be used by linker to optimize code at link time.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/LTO/legacy/ThinLTOCodeGenerator.h"
16 
17 #ifdef HAVE_LLVM_REVISION
18 #include "LLVMLTORevision.h"
19 #endif
20 
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
24 #include "llvm/Analysis/ProfileSummaryInfo.h"
25 #include "llvm/Analysis/TargetLibraryInfo.h"
26 #include "llvm/Analysis/TargetTransformInfo.h"
27 #include "llvm/Bitcode/BitcodeReader.h"
28 #include "llvm/Bitcode/BitcodeWriter.h"
29 #include "llvm/Bitcode/BitcodeWriterPass.h"
30 #include "llvm/ExecutionEngine/ObjectMemoryBuffer.h"
31 #include "llvm/IR/DiagnosticPrinter.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/LegacyPassManager.h"
34 #include "llvm/IR/Mangler.h"
35 #include "llvm/IRReader/IRReader.h"
36 #include "llvm/LTO/LTO.h"
37 #include "llvm/Linker/Linker.h"
38 #include "llvm/MC/SubtargetFeature.h"
39 #include "llvm/Object/IRObjectFile.h"
40 #include "llvm/Object/ModuleSummaryIndexObjectFile.h"
41 #include "llvm/Support/CachePruning.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/Error.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/SHA1.h"
46 #include "llvm/Support/TargetRegistry.h"
47 #include "llvm/Support/ThreadPool.h"
48 #include "llvm/Support/Threading.h"
49 #include "llvm/Support/ToolOutputFile.h"
50 #include "llvm/Target/TargetMachine.h"
51 #include "llvm/Transforms/IPO.h"
52 #include "llvm/Transforms/IPO/FunctionImport.h"
53 #include "llvm/Transforms/IPO/Internalize.h"
54 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
55 #include "llvm/Transforms/ObjCARC.h"
56 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
57 
58 #include <numeric>
59 
60 using namespace llvm;
61 
62 #define DEBUG_TYPE "thinlto"
63 
64 namespace llvm {
65 // Flags -discard-value-names, defined in LTOCodeGenerator.cpp
66 extern cl::opt<bool> LTODiscardValueNames;
67 extern cl::opt<std::string> LTORemarksFilename;
68 }
69 
70 namespace {
71 
72 static cl::opt<int>
73     ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency()));
74 
75 Expected<std::unique_ptr<tool_output_file>>
76 setupOptimizationRemarks(LLVMContext &Ctx, int Count) {
77   if (LTORemarksFilename.empty())
78     return nullptr;
79 
80   std::string FileName =
81       LTORemarksFilename + ".thin." + llvm::utostr(Count) + ".yaml";
82   std::error_code EC;
83   auto DiagnosticOutputFile =
84       llvm::make_unique<tool_output_file>(FileName, EC, sys::fs::F_None);
85   if (EC)
86     return errorCodeToError(EC);
87   Ctx.setDiagnosticsOutputFile(
88       llvm::make_unique<yaml::Output>(DiagnosticOutputFile->os()));
89   DiagnosticOutputFile->keep();
90   return std::move(DiagnosticOutputFile);
91 }
92 
93 // Simple helper to save temporary files for debug.
94 static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
95                             unsigned count, StringRef Suffix) {
96   if (TempDir.empty())
97     return;
98   // User asked to save temps, let dump the bitcode file after import.
99   std::string SaveTempPath = (TempDir + llvm::utostr(count) + Suffix).str();
100   std::error_code EC;
101   raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
102   if (EC)
103     report_fatal_error(Twine("Failed to open ") + SaveTempPath +
104                        " to save optimized bitcode\n");
105   WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
106 }
107 
108 static const GlobalValueSummary *
109 getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
110   // If there is any strong definition anywhere, get it.
111   auto StrongDefForLinker = llvm::find_if(
112       GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
113         auto Linkage = Summary->linkage();
114         return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
115                !GlobalValue::isWeakForLinker(Linkage);
116       });
117   if (StrongDefForLinker != GVSummaryList.end())
118     return StrongDefForLinker->get();
119   // Get the first *linker visible* definition for this global in the summary
120   // list.
121   auto FirstDefForLinker = llvm::find_if(
122       GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
123         auto Linkage = Summary->linkage();
124         return !GlobalValue::isAvailableExternallyLinkage(Linkage);
125       });
126   // Extern templates can be emitted as available_externally.
127   if (FirstDefForLinker == GVSummaryList.end())
128     return nullptr;
129   return FirstDefForLinker->get();
130 }
131 
132 // Populate map of GUID to the prevailing copy for any multiply defined
133 // symbols. Currently assume first copy is prevailing, or any strong
134 // definition. Can be refined with Linker information in the future.
135 static void computePrevailingCopies(
136     const ModuleSummaryIndex &Index,
137     DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
138   auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
139     return GVSummaryList.size() > 1;
140   };
141 
142   for (auto &I : Index) {
143     if (HasMultipleCopies(I.second))
144       PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second);
145   }
146 }
147 
148 static StringMap<MemoryBufferRef>
149 generateModuleMap(const std::vector<MemoryBufferRef> &Modules) {
150   StringMap<MemoryBufferRef> ModuleMap;
151   for (auto &ModuleBuffer : Modules) {
152     assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
153                ModuleMap.end() &&
154            "Expect unique Buffer Identifier");
155     ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer;
156   }
157   return ModuleMap;
158 }
159 
160 static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
161   if (renameModuleForThinLTO(TheModule, Index))
162     report_fatal_error("renameModuleForThinLTO failed");
163 }
164 
165 static void
166 crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
167                       StringMap<MemoryBufferRef> &ModuleMap,
168                       const FunctionImporter::ImportMapTy &ImportList) {
169   ModuleLoader Loader(TheModule.getContext(), ModuleMap);
170   FunctionImporter Importer(Index, Loader);
171   if (!Importer.importFunctions(TheModule, ImportList))
172     report_fatal_error("importFunctions failed");
173 }
174 
175 static void optimizeModule(Module &TheModule, TargetMachine &TM) {
176   // Populate the PassManager
177   PassManagerBuilder PMB;
178   PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
179   PMB.Inliner = createFunctionInliningPass();
180   // FIXME: should get it from the bitcode?
181   PMB.OptLevel = 3;
182   PMB.LoopVectorize = true;
183   PMB.SLPVectorize = true;
184   PMB.VerifyInput = true;
185   PMB.VerifyOutput = false;
186 
187   legacy::PassManager PM;
188 
189   // Add the TTI (required to inform the vectorizer about register size for
190   // instance)
191   PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
192 
193   // Add optimizations
194   PMB.populateThinLTOPassManager(PM);
195 
196   PM.run(TheModule);
197 }
198 
199 // Convert the PreservedSymbols map from "Name" based to "GUID" based.
200 static DenseSet<GlobalValue::GUID>
201 computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
202                             const Triple &TheTriple) {
203   DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
204   for (auto &Entry : PreservedSymbols) {
205     StringRef Name = Entry.first();
206     if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
207       Name = Name.drop_front();
208     GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
209   }
210   return GUIDPreservedSymbols;
211 }
212 
213 std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
214                                             TargetMachine &TM) {
215   SmallVector<char, 128> OutputBuffer;
216 
217   // CodeGen
218   {
219     raw_svector_ostream OS(OutputBuffer);
220     legacy::PassManager PM;
221 
222     // If the bitcode files contain ARC code and were compiled with optimization,
223     // the ObjCARCContractPass must be run, so do it unconditionally here.
224     PM.add(createObjCARCContractPass());
225 
226     // Setup the codegen now.
227     if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
228                                /* DisableVerify */ true))
229       report_fatal_error("Failed to setup codegen");
230 
231     // Run codegen now. resulting binary is in OutputBuffer.
232     PM.run(TheModule);
233   }
234   return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
235 }
236 
237 /// Manage caching for a single Module.
238 class ModuleCacheEntry {
239   SmallString<128> EntryPath;
240 
241 public:
242   // Create a cache entry. This compute a unique hash for the Module considering
243   // the current list of export/import, and offer an interface to query to
244   // access the content in the cache.
245   ModuleCacheEntry(
246       StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
247       const FunctionImporter::ImportMapTy &ImportList,
248       const FunctionImporter::ExportSetTy &ExportList,
249       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
250       const GVSummaryMapTy &DefinedFunctions,
251       const DenseSet<GlobalValue::GUID> &PreservedSymbols) {
252     if (CachePath.empty())
253       return;
254 
255     if (!Index.modulePaths().count(ModuleID))
256       // The module does not have an entry, it can't have a hash at all
257       return;
258 
259     // Compute the unique hash for this entry
260     // This is based on the current compiler version, the module itself, the
261     // export list, the hash for every single module in the import list, the
262     // list of ResolvedODR for the module, and the list of preserved symbols.
263 
264     // Include the hash for the current module
265     auto ModHash = Index.getModuleHash(ModuleID);
266 
267     if (all_of(ModHash, [](uint32_t V) { return V == 0; }))
268       // No hash entry, no caching!
269       return;
270 
271     SHA1 Hasher;
272 
273     // Start with the compiler revision
274     Hasher.update(LLVM_VERSION_STRING);
275 #ifdef HAVE_LLVM_REVISION
276     Hasher.update(LLVM_REVISION);
277 #endif
278 
279     Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
280     for (auto F : ExportList)
281       // The export list can impact the internalization, be conservative here
282       Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
283 
284     // Include the hash for every module we import functions from
285     for (auto &Entry : ImportList) {
286       auto ModHash = Index.getModuleHash(Entry.first());
287       Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
288     }
289 
290     // Include the hash for the resolved ODR.
291     for (auto &Entry : ResolvedODR) {
292       Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
293                                       sizeof(GlobalValue::GUID)));
294       Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
295                                       sizeof(GlobalValue::LinkageTypes)));
296     }
297 
298     // Include the hash for the preserved symbols.
299     for (auto &Entry : PreservedSymbols) {
300       if (DefinedFunctions.count(Entry))
301         Hasher.update(
302             ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
303     }
304 
305     sys::path::append(EntryPath, CachePath, toHex(Hasher.result()));
306   }
307 
308   // Access the path to this entry in the cache.
309   StringRef getEntryPath() { return EntryPath; }
310 
311   // Try loading the buffer for this cache entry.
312   ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
313     if (EntryPath.empty())
314       return std::error_code();
315     return MemoryBuffer::getFile(EntryPath);
316   }
317 
318   // Cache the Produced object file
319   std::unique_ptr<MemoryBuffer>
320   write(std::unique_ptr<MemoryBuffer> OutputBuffer) {
321     if (EntryPath.empty())
322       return OutputBuffer;
323 
324     // Write to a temporary to avoid race condition
325     SmallString<128> TempFilename;
326     int TempFD;
327     std::error_code EC =
328         sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
329     if (EC) {
330       errs() << "Error: " << EC.message() << "\n";
331       report_fatal_error("ThinLTO: Can't get a temporary file");
332     }
333     {
334       raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
335       OS << OutputBuffer->getBuffer();
336     }
337     // Rename to final destination (hopefully race condition won't matter here)
338     EC = sys::fs::rename(TempFilename, EntryPath);
339     if (EC) {
340       sys::fs::remove(TempFilename);
341       raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
342       if (EC)
343         report_fatal_error(Twine("Failed to open ") + EntryPath +
344                            " to save cached entry\n");
345       OS << OutputBuffer->getBuffer();
346     }
347     auto ReloadedBufferOrErr = MemoryBuffer::getFile(EntryPath);
348     if (auto EC = ReloadedBufferOrErr.getError()) {
349       // FIXME diagnose
350       errs() << "error: can't reload cached file '" << EntryPath
351              << "': " << EC.message() << "\n";
352       return OutputBuffer;
353     }
354     return std::move(*ReloadedBufferOrErr);
355   }
356 };
357 
358 static std::unique_ptr<MemoryBuffer>
359 ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
360                      StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
361                      const FunctionImporter::ImportMapTy &ImportList,
362                      const FunctionImporter::ExportSetTy &ExportList,
363                      const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
364                      const GVSummaryMapTy &DefinedGlobals,
365                      const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
366                      bool DisableCodeGen, StringRef SaveTempsDir,
367                      unsigned count) {
368 
369   // "Benchmark"-like optimization: single-source case
370   bool SingleModule = (ModuleMap.size() == 1);
371 
372   if (!SingleModule) {
373     promoteModule(TheModule, Index);
374 
375     // Apply summary-based LinkOnce/Weak resolution decisions.
376     thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
377 
378     // Save temps: after promotion.
379     saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
380   }
381 
382   // Be friendly and don't nuke totally the module when the client didn't
383   // supply anything to preserve.
384   if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
385     // Apply summary-based internalization decisions.
386     thinLTOInternalizeModule(TheModule, DefinedGlobals);
387   }
388 
389   // Save internalized bitcode
390   saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
391 
392   if (!SingleModule) {
393     crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
394 
395     // Save temps: after cross-module import.
396     saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
397   }
398 
399   optimizeModule(TheModule, TM);
400 
401   saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
402 
403   if (DisableCodeGen) {
404     // Configured to stop before CodeGen, serialize the bitcode and return.
405     SmallVector<char, 128> OutputBuffer;
406     {
407       raw_svector_ostream OS(OutputBuffer);
408       ProfileSummaryInfo PSI(TheModule);
409       auto Index = buildModuleSummaryIndex(TheModule, nullptr, nullptr);
410       WriteBitcodeToFile(&TheModule, OS, true, &Index);
411     }
412     return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
413   }
414 
415   return codegenModule(TheModule, TM);
416 }
417 
418 /// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
419 /// for caching, and in the \p Index for application during the ThinLTO
420 /// backends. This is needed for correctness for exported symbols (ensure
421 /// at least one copy kept) and a compile-time optimization (to drop duplicate
422 /// copies when possible).
423 static void resolveWeakForLinkerInIndex(
424     ModuleSummaryIndex &Index,
425     StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
426         &ResolvedODR) {
427 
428   DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
429   computePrevailingCopies(Index, PrevailingCopy);
430 
431   auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
432     const auto &Prevailing = PrevailingCopy.find(GUID);
433     // Not in map means that there was only one copy, which must be prevailing.
434     if (Prevailing == PrevailingCopy.end())
435       return true;
436     return Prevailing->second == S;
437   };
438 
439   auto recordNewLinkage = [&](StringRef ModuleIdentifier,
440                               GlobalValue::GUID GUID,
441                               GlobalValue::LinkageTypes NewLinkage) {
442     ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
443   };
444 
445   thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
446 }
447 
448 // Initialize the TargetMachine builder for a given Triple
449 static void initTMBuilder(TargetMachineBuilder &TMBuilder,
450                           const Triple &TheTriple) {
451   // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
452   // FIXME this looks pretty terrible...
453   if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
454     if (TheTriple.getArch() == llvm::Triple::x86_64)
455       TMBuilder.MCpu = "core2";
456     else if (TheTriple.getArch() == llvm::Triple::x86)
457       TMBuilder.MCpu = "yonah";
458     else if (TheTriple.getArch() == llvm::Triple::aarch64)
459       TMBuilder.MCpu = "cyclone";
460   }
461   TMBuilder.TheTriple = std::move(TheTriple);
462 }
463 
464 } // end anonymous namespace
465 
466 void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
467   MemoryBufferRef Buffer(Data, Identifier);
468   if (Modules.empty()) {
469     // First module added, so initialize the triple and some options
470     LLVMContext Context;
471     StringRef TripleStr;
472     ErrorOr<std::string> TripleOrErr =
473         expectedToErrorOrAndEmitErrors(Context, getBitcodeTargetTriple(Buffer));
474     if (TripleOrErr)
475       TripleStr = *TripleOrErr;
476     Triple TheTriple(TripleStr);
477     initTMBuilder(TMBuilder, Triple(TheTriple));
478   }
479 #ifndef NDEBUG
480   else {
481     LLVMContext Context;
482     StringRef TripleStr;
483     ErrorOr<std::string> TripleOrErr =
484         expectedToErrorOrAndEmitErrors(Context, getBitcodeTargetTriple(Buffer));
485     if (TripleOrErr)
486       TripleStr = *TripleOrErr;
487     assert(TMBuilder.TheTriple.str() == TripleStr &&
488            "ThinLTO modules with different triple not supported");
489   }
490 #endif
491   Modules.push_back(Buffer);
492 }
493 
494 void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
495   PreservedSymbols.insert(Name);
496 }
497 
498 void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
499   // FIXME: At the moment, we don't take advantage of this extra information,
500   // we're conservatively considering cross-references as preserved.
501   //  CrossReferencedSymbols.insert(Name);
502   PreservedSymbols.insert(Name);
503 }
504 
505 // TargetMachine factory
506 std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
507   std::string ErrMsg;
508   const Target *TheTarget =
509       TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
510   if (!TheTarget) {
511     report_fatal_error("Can't load target for this Triple: " + ErrMsg);
512   }
513 
514   // Use MAttr as the default set of features.
515   SubtargetFeatures Features(MAttr);
516   Features.getDefaultSubtargetFeatures(TheTriple);
517   std::string FeatureStr = Features.getString();
518   return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
519       TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
520       CodeModel::Default, CGOptLevel));
521 }
522 
523 /**
524  * Produce the combined summary index from all the bitcode files:
525  * "thin-link".
526  */
527 std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
528   std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
529   uint64_t NextModuleId = 0;
530   for (auto &ModuleBuffer : Modules) {
531     Expected<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
532         object::ModuleSummaryIndexObjectFile::create(ModuleBuffer);
533     if (!ObjOrErr) {
534       // FIXME diagnose
535       logAllUnhandledErrors(
536           ObjOrErr.takeError(), errs(),
537           "error: can't create ModuleSummaryIndexObjectFile for buffer: ");
538       return nullptr;
539     }
540     auto Index = (*ObjOrErr)->takeIndex();
541     if (CombinedIndex) {
542       CombinedIndex->mergeFrom(std::move(Index), ++NextModuleId);
543     } else {
544       CombinedIndex = std::move(Index);
545     }
546   }
547   return CombinedIndex;
548 }
549 
550 /**
551  * Perform promotion and renaming of exported internal functions.
552  * Index is updated to reflect linkage changes from weak resolution.
553  */
554 void ThinLTOCodeGenerator::promote(Module &TheModule,
555                                    ModuleSummaryIndex &Index) {
556   auto ModuleCount = Index.modulePaths().size();
557   auto ModuleIdentifier = TheModule.getModuleIdentifier();
558 
559   // Collect for each module the list of function it defines (GUID -> Summary).
560   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
561   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
562 
563   // Generate import/export list
564   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
565   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
566   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
567                            ExportLists);
568 
569   // Resolve LinkOnce/Weak symbols.
570   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
571   resolveWeakForLinkerInIndex(Index, ResolvedODR);
572 
573   thinLTOResolveWeakForLinkerModule(
574       TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
575 
576   // Convert the preserved symbols set from string to GUID
577   auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
578       PreservedSymbols, Triple(TheModule.getTargetTriple()));
579 
580   // Promote the exported values in the index, so that they are promoted
581   // in the module.
582   auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
583     const auto &ExportList = ExportLists.find(ModuleIdentifier);
584     return (ExportList != ExportLists.end() &&
585             ExportList->second.count(GUID)) ||
586            GUIDPreservedSymbols.count(GUID);
587   };
588   thinLTOInternalizeAndPromoteInIndex(Index, isExported);
589 
590   promoteModule(TheModule, Index);
591 }
592 
593 /**
594  * Perform cross-module importing for the module identified by ModuleIdentifier.
595  */
596 void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
597                                              ModuleSummaryIndex &Index) {
598   auto ModuleMap = generateModuleMap(Modules);
599   auto ModuleCount = Index.modulePaths().size();
600 
601   // Collect for each module the list of function it defines (GUID -> Summary).
602   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
603   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
604 
605   // Generate import/export list
606   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
607   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
608   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
609                            ExportLists);
610   auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
611 
612   crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
613 }
614 
615 /**
616  * Compute the list of summaries needed for importing into module.
617  */
618 void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
619     StringRef ModulePath, ModuleSummaryIndex &Index,
620     std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
621   auto ModuleCount = Index.modulePaths().size();
622 
623   // Collect for each module the list of function it defines (GUID -> Summary).
624   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
625   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
626 
627   // Generate import/export list
628   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
629   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
630   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
631                            ExportLists);
632 
633   llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
634                                          ImportLists[ModulePath],
635                                          ModuleToSummariesForIndex);
636 }
637 
638 /**
639  * Emit the list of files needed for importing into module.
640  */
641 void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
642                                        StringRef OutputName,
643                                        ModuleSummaryIndex &Index) {
644   auto ModuleCount = Index.modulePaths().size();
645 
646   // Collect for each module the list of function it defines (GUID -> Summary).
647   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
648   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
649 
650   // Generate import/export list
651   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
652   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
653   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
654                            ExportLists);
655 
656   std::error_code EC;
657   if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath])))
658     report_fatal_error(Twine("Failed to open ") + OutputName +
659                        " to save imports lists\n");
660 }
661 
662 /**
663  * Perform internalization. Index is updated to reflect linkage changes.
664  */
665 void ThinLTOCodeGenerator::internalize(Module &TheModule,
666                                        ModuleSummaryIndex &Index) {
667   initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
668   auto ModuleCount = Index.modulePaths().size();
669   auto ModuleIdentifier = TheModule.getModuleIdentifier();
670 
671   // Convert the preserved symbols set from string to GUID
672   auto GUIDPreservedSymbols =
673       computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
674 
675   // Collect for each module the list of function it defines (GUID -> Summary).
676   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
677   Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
678 
679   // Generate import/export list
680   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
681   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
682   ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
683                            ExportLists);
684   auto &ExportList = ExportLists[ModuleIdentifier];
685 
686   // Be friendly and don't nuke totally the module when the client didn't
687   // supply anything to preserve.
688   if (ExportList.empty() && GUIDPreservedSymbols.empty())
689     return;
690 
691   // Internalization
692   auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
693     const auto &ExportList = ExportLists.find(ModuleIdentifier);
694     return (ExportList != ExportLists.end() &&
695             ExportList->second.count(GUID)) ||
696            GUIDPreservedSymbols.count(GUID);
697   };
698   thinLTOInternalizeAndPromoteInIndex(Index, isExported);
699   thinLTOInternalizeModule(TheModule,
700                            ModuleToDefinedGVSummaries[ModuleIdentifier]);
701 }
702 
703 /**
704  * Perform post-importing ThinLTO optimizations.
705  */
706 void ThinLTOCodeGenerator::optimize(Module &TheModule) {
707   initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
708 
709   // Optimize now
710   optimizeModule(TheModule, *TMBuilder.create());
711 }
712 
713 /**
714  * Perform ThinLTO CodeGen.
715  */
716 std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
717   initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
718   return codegenModule(TheModule, *TMBuilder.create());
719 }
720 
721 // Main entry point for the ThinLTO processing
722 void ThinLTOCodeGenerator::run() {
723   if (CodeGenOnly) {
724     // Perform only parallel codegen and return.
725     ThreadPool Pool;
726     assert(ProducedBinaries.empty() && "The generator should not be reused");
727     ProducedBinaries.resize(Modules.size());
728     int count = 0;
729     for (auto &ModuleBuffer : Modules) {
730       Pool.async([&](int count) {
731         LLVMContext Context;
732         Context.setDiscardValueNames(LTODiscardValueNames);
733 
734         // Parse module now
735         auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
736 
737         // CodeGen
738         ProducedBinaries[count] = codegen(*TheModule);
739       }, count++);
740     }
741 
742     return;
743   }
744 
745   // Sequential linking phase
746   auto Index = linkCombinedIndex();
747 
748   // Save temps: index.
749   if (!SaveTempsDir.empty()) {
750     auto SaveTempPath = SaveTempsDir + "index.bc";
751     std::error_code EC;
752     raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
753     if (EC)
754       report_fatal_error(Twine("Failed to open ") + SaveTempPath +
755                          " to save optimized bitcode\n");
756     WriteIndexToFile(*Index, OS);
757   }
758 
759   // Prepare the resulting object vector
760   assert(ProducedBinaries.empty() && "The generator should not be reused");
761   ProducedBinaries.resize(Modules.size());
762 
763   // Prepare the module map.
764   auto ModuleMap = generateModuleMap(Modules);
765   auto ModuleCount = Modules.size();
766 
767   // Collect for each module the list of function it defines (GUID -> Summary).
768   StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
769   Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
770 
771   // Collect the import/export lists for all modules from the call-graph in the
772   // combined index.
773   StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
774   StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
775   ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
776                            ExportLists);
777 
778   // Convert the preserved symbols set from string to GUID, this is needed for
779   // computing the caching hash and the internalization.
780   auto GUIDPreservedSymbols =
781       computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
782 
783   // We use a std::map here to be able to have a defined ordering when
784   // producing a hash for the cache entry.
785   // FIXME: we should be able to compute the caching hash for the entry based
786   // on the index, and nuke this map.
787   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
788 
789   // Resolve LinkOnce/Weak symbols, this has to be computed early because it
790   // impacts the caching.
791   resolveWeakForLinkerInIndex(*Index, ResolvedODR);
792 
793   auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
794     const auto &ExportList = ExportLists.find(ModuleIdentifier);
795     return (ExportList != ExportLists.end() &&
796             ExportList->second.count(GUID)) ||
797            GUIDPreservedSymbols.count(GUID);
798   };
799 
800   // Use global summary-based analysis to identify symbols that can be
801   // internalized (because they aren't exported or preserved as per callback).
802   // Changes are made in the index, consumed in the ThinLTO backends.
803   thinLTOInternalizeAndPromoteInIndex(*Index, isExported);
804 
805   // Make sure that every module has an entry in the ExportLists and
806   // ResolvedODR maps to enable threaded access to these maps below.
807   for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
808     ExportLists[DefinedGVSummaries.first()];
809     ResolvedODR[DefinedGVSummaries.first()];
810   }
811 
812   // Compute the ordering we will process the inputs: the rough heuristic here
813   // is to sort them per size so that the largest module get schedule as soon as
814   // possible. This is purely a compile-time optimization.
815   std::vector<int> ModulesOrdering;
816   ModulesOrdering.resize(Modules.size());
817   std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
818   std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
819             [&](int LeftIndex, int RightIndex) {
820               auto LSize = Modules[LeftIndex].getBufferSize();
821               auto RSize = Modules[RightIndex].getBufferSize();
822               return LSize > RSize;
823             });
824 
825   // Parallel optimizer + codegen
826   {
827     ThreadPool Pool(ThreadCount);
828     for (auto IndexCount : ModulesOrdering) {
829       auto &ModuleBuffer = Modules[IndexCount];
830       Pool.async([&](int count) {
831         auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
832         auto &ExportList = ExportLists[ModuleIdentifier];
833 
834         auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
835 
836         // The module may be cached, this helps handling it.
837         ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
838                                     ImportLists[ModuleIdentifier], ExportList,
839                                     ResolvedODR[ModuleIdentifier],
840                                     DefinedFunctions, GUIDPreservedSymbols);
841 
842         {
843           auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
844           DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
845                        << CacheEntry.getEntryPath() << "' for buffer " << count
846                        << " " << ModuleIdentifier << "\n");
847 
848           if (ErrOrBuffer) {
849             // Cache Hit!
850             ProducedBinaries[count] = std::move(ErrOrBuffer.get());
851             return;
852           }
853         }
854 
855         LLVMContext Context;
856         Context.setDiscardValueNames(LTODiscardValueNames);
857         Context.enableDebugTypeODRUniquing();
858         auto DiagFileOrErr = setupOptimizationRemarks(Context, count);
859         if (!DiagFileOrErr) {
860           errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
861           report_fatal_error("ThinLTO: Can't get an output file for the "
862                              "remarks");
863         }
864 
865         // Parse module now
866         auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false);
867 
868         // Save temps: original file.
869         saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
870 
871         auto &ImportList = ImportLists[ModuleIdentifier];
872         // Run the main process now, and generates a binary
873         auto OutputBuffer = ProcessThinLTOModule(
874             *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
875             ExportList, GUIDPreservedSymbols,
876             ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
877             DisableCodeGen, SaveTempsDir, count);
878 
879         OutputBuffer = CacheEntry.write(std::move(OutputBuffer));
880         ProducedBinaries[count] = std::move(OutputBuffer);
881       }, IndexCount);
882     }
883   }
884 
885   CachePruning(CacheOptions.Path)
886       .setPruningInterval(std::chrono::seconds(CacheOptions.PruningInterval))
887       .setEntryExpiration(std::chrono::seconds(CacheOptions.Expiration))
888       .setMaxSize(CacheOptions.MaxPercentageOfAvailableSpace)
889       .prune();
890 
891   // If statistics were requested, print them out now.
892   if (llvm::AreStatisticsEnabled())
893     llvm::PrintStatistics();
894 }
895