1 //===-ThinLTOCodeGenerator.cpp - LLVM Link Time Optimizer -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/LTO/legacy/ThinLTOCodeGenerator.h"
17 #ifdef HAVE_LLVM_REVISION
18 #include "LLVMLTORevision.h"
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"
62 #define DEBUG_TYPE "thinlto"
65 // Flags -discard-value-names, defined in LTOCodeGenerator.cpp
66 extern cl::opt<bool> LTODiscardValueNames;
67 extern cl::opt<std::string> LTORemarksFilename;
68 extern cl::opt<bool> LTOPassRemarksWithHotness;
74 ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency()));
76 Expected<std::unique_ptr<tool_output_file>>
77 setupOptimizationRemarks(LLVMContext &Ctx, int Count) {
78 if (LTOPassRemarksWithHotness)
79 Ctx.setDiagnosticHotnessRequested(true);
81 if (LTORemarksFilename.empty())
84 std::string FileName =
85 LTORemarksFilename + ".thin." + llvm::utostr(Count) + ".yaml";
87 auto DiagnosticOutputFile =
88 llvm::make_unique<tool_output_file>(FileName, EC, sys::fs::F_None);
90 return errorCodeToError(EC);
91 Ctx.setDiagnosticsOutputFile(
92 llvm::make_unique<yaml::Output>(DiagnosticOutputFile->os()));
93 DiagnosticOutputFile->keep();
94 return std::move(DiagnosticOutputFile);
97 // Simple helper to save temporary files for debug.
98 static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
99 unsigned count, StringRef Suffix) {
102 // User asked to save temps, let dump the bitcode file after import.
103 std::string SaveTempPath = (TempDir + llvm::utostr(count) + Suffix).str();
105 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
107 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
108 " to save optimized bitcode\n");
109 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
112 static const GlobalValueSummary *
113 getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
114 // If there is any strong definition anywhere, get it.
115 auto StrongDefForLinker = llvm::find_if(
116 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
117 auto Linkage = Summary->linkage();
118 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
119 !GlobalValue::isWeakForLinker(Linkage);
121 if (StrongDefForLinker != GVSummaryList.end())
122 return StrongDefForLinker->get();
123 // Get the first *linker visible* definition for this global in the summary
125 auto FirstDefForLinker = llvm::find_if(
126 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
127 auto Linkage = Summary->linkage();
128 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
130 // Extern templates can be emitted as available_externally.
131 if (FirstDefForLinker == GVSummaryList.end())
133 return FirstDefForLinker->get();
136 // Populate map of GUID to the prevailing copy for any multiply defined
137 // symbols. Currently assume first copy is prevailing, or any strong
138 // definition. Can be refined with Linker information in the future.
139 static void computePrevailingCopies(
140 const ModuleSummaryIndex &Index,
141 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
142 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
143 return GVSummaryList.size() > 1;
146 for (auto &I : Index) {
147 if (HasMultipleCopies(I.second))
148 PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second);
152 static StringMap<MemoryBufferRef>
153 generateModuleMap(const std::vector<MemoryBufferRef> &Modules) {
154 StringMap<MemoryBufferRef> ModuleMap;
155 for (auto &ModuleBuffer : Modules) {
156 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
158 "Expect unique Buffer Identifier");
159 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer;
164 static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
165 if (renameModuleForThinLTO(TheModule, Index))
166 report_fatal_error("renameModuleForThinLTO failed");
169 static std::unique_ptr<Module>
170 loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
171 bool Lazy, bool IsImporting) {
173 Expected<std::unique_ptr<Module>> ModuleOrErr =
175 ? getLazyBitcodeModule(Buffer, Context,
176 /* ShouldLazyLoadMetadata */ true, IsImporting)
177 : parseBitcodeFile(Buffer, Context);
179 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
180 SMDiagnostic Err = SMDiagnostic(Buffer.getBufferIdentifier(),
181 SourceMgr::DK_Error, EIB.message());
182 Err.print("ThinLTO", errs());
184 report_fatal_error("Can't load module, abort.");
186 return std::move(ModuleOrErr.get());
190 crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
191 StringMap<MemoryBufferRef> &ModuleMap,
192 const FunctionImporter::ImportMapTy &ImportList) {
193 auto Loader = [&](StringRef Identifier) {
194 return loadModuleFromBuffer(ModuleMap[Identifier], TheModule.getContext(),
195 /*Lazy=*/true, /*IsImporting*/ true);
198 FunctionImporter Importer(Index, Loader);
199 Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
201 handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
202 SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(),
203 SourceMgr::DK_Error, EIB.message());
204 Err.print("ThinLTO", errs());
206 report_fatal_error("importFunctions failed");
210 static void optimizeModule(Module &TheModule, TargetMachine &TM,
212 // Populate the PassManager
213 PassManagerBuilder PMB;
214 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
215 PMB.Inliner = createFunctionInliningPass();
216 // FIXME: should get it from the bitcode?
217 PMB.OptLevel = OptLevel;
218 PMB.LoopVectorize = true;
219 PMB.SLPVectorize = true;
220 PMB.VerifyInput = true;
221 PMB.VerifyOutput = false;
223 legacy::PassManager PM;
225 // Add the TTI (required to inform the vectorizer about register size for
227 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
230 PMB.populateThinLTOPassManager(PM);
235 // Convert the PreservedSymbols map from "Name" based to "GUID" based.
236 static DenseSet<GlobalValue::GUID>
237 computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
238 const Triple &TheTriple) {
239 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
240 for (auto &Entry : PreservedSymbols) {
241 StringRef Name = Entry.first();
242 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
243 Name = Name.drop_front();
244 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
246 return GUIDPreservedSymbols;
249 std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
251 SmallVector<char, 128> OutputBuffer;
255 raw_svector_ostream OS(OutputBuffer);
256 legacy::PassManager PM;
258 // If the bitcode files contain ARC code and were compiled with optimization,
259 // the ObjCARCContractPass must be run, so do it unconditionally here.
260 PM.add(createObjCARCContractPass());
262 // Setup the codegen now.
263 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile,
264 /* DisableVerify */ true))
265 report_fatal_error("Failed to setup codegen");
267 // Run codegen now. resulting binary is in OutputBuffer.
270 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
273 /// Manage caching for a single Module.
274 class ModuleCacheEntry {
275 SmallString<128> EntryPath;
278 // Create a cache entry. This compute a unique hash for the Module considering
279 // the current list of export/import, and offer an interface to query to
280 // access the content in the cache.
282 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
283 const FunctionImporter::ImportMapTy &ImportList,
284 const FunctionImporter::ExportSetTy &ExportList,
285 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
286 const GVSummaryMapTy &DefinedFunctions,
287 const DenseSet<GlobalValue::GUID> &PreservedSymbols) {
288 if (CachePath.empty())
291 if (!Index.modulePaths().count(ModuleID))
292 // The module does not have an entry, it can't have a hash at all
295 // Compute the unique hash for this entry
296 // This is based on the current compiler version, the module itself, the
297 // export list, the hash for every single module in the import list, the
298 // list of ResolvedODR for the module, and the list of preserved symbols.
300 // Include the hash for the current module
301 auto ModHash = Index.getModuleHash(ModuleID);
303 if (all_of(ModHash, [](uint32_t V) { return V == 0; }))
304 // No hash entry, no caching!
309 // Start with the compiler revision
310 Hasher.update(LLVM_VERSION_STRING);
311 #ifdef HAVE_LLVM_REVISION
312 Hasher.update(LLVM_REVISION);
315 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
316 for (auto F : ExportList)
317 // The export list can impact the internalization, be conservative here
318 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
320 // Include the hash for every module we import functions from
321 for (auto &Entry : ImportList) {
322 auto ModHash = Index.getModuleHash(Entry.first());
323 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
326 // Include the hash for the resolved ODR.
327 for (auto &Entry : ResolvedODR) {
328 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
329 sizeof(GlobalValue::GUID)));
330 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
331 sizeof(GlobalValue::LinkageTypes)));
334 // Include the hash for the preserved symbols.
335 for (auto &Entry : PreservedSymbols) {
336 if (DefinedFunctions.count(Entry))
338 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
341 sys::path::append(EntryPath, CachePath, toHex(Hasher.result()));
344 // Access the path to this entry in the cache.
345 StringRef getEntryPath() { return EntryPath; }
347 // Try loading the buffer for this cache entry.
348 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
349 if (EntryPath.empty())
350 return std::error_code();
351 return MemoryBuffer::getFile(EntryPath);
354 // Cache the Produced object file
355 void write(const MemoryBuffer &OutputBuffer) {
356 if (EntryPath.empty())
359 // Write to a temporary to avoid race condition
360 SmallString<128> TempFilename;
363 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
365 errs() << "Error: " << EC.message() << "\n";
366 report_fatal_error("ThinLTO: Can't get a temporary file");
369 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
370 OS << OutputBuffer.getBuffer();
372 // Rename to final destination (hopefully race condition won't matter here)
373 EC = sys::fs::rename(TempFilename, EntryPath);
375 sys::fs::remove(TempFilename);
376 raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
378 report_fatal_error(Twine("Failed to open ") + EntryPath +
379 " to save cached entry\n");
380 OS << OutputBuffer.getBuffer();
385 static std::unique_ptr<MemoryBuffer>
386 ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
387 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
388 const FunctionImporter::ImportMapTy &ImportList,
389 const FunctionImporter::ExportSetTy &ExportList,
390 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
391 const GVSummaryMapTy &DefinedGlobals,
392 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
393 bool DisableCodeGen, StringRef SaveTempsDir,
394 unsigned OptLevel, unsigned count) {
396 // "Benchmark"-like optimization: single-source case
397 bool SingleModule = (ModuleMap.size() == 1);
400 promoteModule(TheModule, Index);
402 // Apply summary-based LinkOnce/Weak resolution decisions.
403 thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
405 // Save temps: after promotion.
406 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
409 // Be friendly and don't nuke totally the module when the client didn't
410 // supply anything to preserve.
411 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
412 // Apply summary-based internalization decisions.
413 thinLTOInternalizeModule(TheModule, DefinedGlobals);
416 // Save internalized bitcode
417 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
420 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
422 // Save temps: after cross-module import.
423 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
426 optimizeModule(TheModule, TM, OptLevel);
428 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
430 if (DisableCodeGen) {
431 // Configured to stop before CodeGen, serialize the bitcode and return.
432 SmallVector<char, 128> OutputBuffer;
434 raw_svector_ostream OS(OutputBuffer);
435 ProfileSummaryInfo PSI(TheModule);
436 auto Index = buildModuleSummaryIndex(TheModule, nullptr, nullptr);
437 WriteBitcodeToFile(&TheModule, OS, true, &Index);
439 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
442 return codegenModule(TheModule, TM);
445 /// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
446 /// for caching, and in the \p Index for application during the ThinLTO
447 /// backends. This is needed for correctness for exported symbols (ensure
448 /// at least one copy kept) and a compile-time optimization (to drop duplicate
449 /// copies when possible).
450 static void resolveWeakForLinkerInIndex(
451 ModuleSummaryIndex &Index,
452 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
455 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
456 computePrevailingCopies(Index, PrevailingCopy);
458 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
459 const auto &Prevailing = PrevailingCopy.find(GUID);
460 // Not in map means that there was only one copy, which must be prevailing.
461 if (Prevailing == PrevailingCopy.end())
463 return Prevailing->second == S;
466 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
467 GlobalValue::GUID GUID,
468 GlobalValue::LinkageTypes NewLinkage) {
469 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
472 thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
475 // Initialize the TargetMachine builder for a given Triple
476 static void initTMBuilder(TargetMachineBuilder &TMBuilder,
477 const Triple &TheTriple) {
478 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
479 // FIXME this looks pretty terrible...
480 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
481 if (TheTriple.getArch() == llvm::Triple::x86_64)
482 TMBuilder.MCpu = "core2";
483 else if (TheTriple.getArch() == llvm::Triple::x86)
484 TMBuilder.MCpu = "yonah";
485 else if (TheTriple.getArch() == llvm::Triple::aarch64)
486 TMBuilder.MCpu = "cyclone";
488 TMBuilder.TheTriple = std::move(TheTriple);
491 } // end anonymous namespace
493 void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
494 MemoryBufferRef Buffer(Data, Identifier);
495 if (Modules.empty()) {
496 // First module added, so initialize the triple and some options
499 ErrorOr<std::string> TripleOrErr =
500 expectedToErrorOrAndEmitErrors(Context, getBitcodeTargetTriple(Buffer));
502 TripleStr = *TripleOrErr;
503 Triple TheTriple(TripleStr);
504 initTMBuilder(TMBuilder, Triple(TheTriple));
510 ErrorOr<std::string> TripleOrErr =
511 expectedToErrorOrAndEmitErrors(Context, getBitcodeTargetTriple(Buffer));
513 TripleStr = *TripleOrErr;
514 assert(TMBuilder.TheTriple.str() == TripleStr &&
515 "ThinLTO modules with different triple not supported");
518 Modules.push_back(Buffer);
521 void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
522 PreservedSymbols.insert(Name);
525 void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
526 // FIXME: At the moment, we don't take advantage of this extra information,
527 // we're conservatively considering cross-references as preserved.
528 // CrossReferencedSymbols.insert(Name);
529 PreservedSymbols.insert(Name);
532 // TargetMachine factory
533 std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
535 const Target *TheTarget =
536 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
538 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
541 // Use MAttr as the default set of features.
542 SubtargetFeatures Features(MAttr);
543 Features.getDefaultSubtargetFeatures(TheTriple);
544 std::string FeatureStr = Features.getString();
546 return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
547 TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
548 CodeModel::Default, CGOptLevel));
552 * Produce the combined summary index from all the bitcode files:
555 std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
556 std::unique_ptr<ModuleSummaryIndex> CombinedIndex;
557 uint64_t NextModuleId = 0;
558 for (auto &ModuleBuffer : Modules) {
559 Expected<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr =
560 object::ModuleSummaryIndexObjectFile::create(ModuleBuffer);
563 logAllUnhandledErrors(
564 ObjOrErr.takeError(), errs(),
565 "error: can't create ModuleSummaryIndexObjectFile for buffer: ");
568 auto Index = (*ObjOrErr)->takeIndex();
570 CombinedIndex->mergeFrom(std::move(Index), ++NextModuleId);
572 CombinedIndex = std::move(Index);
575 return CombinedIndex;
579 * Perform promotion and renaming of exported internal functions.
580 * Index is updated to reflect linkage changes from weak resolution.
582 void ThinLTOCodeGenerator::promote(Module &TheModule,
583 ModuleSummaryIndex &Index) {
584 auto ModuleCount = Index.modulePaths().size();
585 auto ModuleIdentifier = TheModule.getModuleIdentifier();
587 // Collect for each module the list of function it defines (GUID -> Summary).
588 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
589 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
591 // Convert the preserved symbols set from string to GUID
592 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
593 PreservedSymbols, Triple(TheModule.getTargetTriple()));
595 // Compute "dead" symbols, we don't want to import/export these!
596 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols);
598 // Generate import/export list
599 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
600 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
601 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
602 ExportLists, &DeadSymbols);
604 // Resolve LinkOnce/Weak symbols.
605 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
606 resolveWeakForLinkerInIndex(Index, ResolvedODR);
608 thinLTOResolveWeakForLinkerModule(
609 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
611 // Promote the exported values in the index, so that they are promoted
613 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
614 const auto &ExportList = ExportLists.find(ModuleIdentifier);
615 return (ExportList != ExportLists.end() &&
616 ExportList->second.count(GUID)) ||
617 GUIDPreservedSymbols.count(GUID);
619 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
621 promoteModule(TheModule, Index);
625 * Perform cross-module importing for the module identified by ModuleIdentifier.
627 void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
628 ModuleSummaryIndex &Index) {
629 auto ModuleMap = generateModuleMap(Modules);
630 auto ModuleCount = Index.modulePaths().size();
632 // Collect for each module the list of function it defines (GUID -> Summary).
633 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
634 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
636 // Convert the preserved symbols set from string to GUID
637 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
638 PreservedSymbols, Triple(TheModule.getTargetTriple()));
640 // Compute "dead" symbols, we don't want to import/export these!
641 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols);
643 // Generate import/export list
644 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
645 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
646 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
647 ExportLists, &DeadSymbols);
648 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
650 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
654 * Compute the list of summaries needed for importing into module.
656 void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
657 StringRef ModulePath, ModuleSummaryIndex &Index,
658 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
659 auto ModuleCount = Index.modulePaths().size();
661 // Collect for each module the list of function it defines (GUID -> Summary).
662 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
663 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
665 // Generate import/export list
666 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
667 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
668 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
671 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
672 ImportLists[ModulePath],
673 ModuleToSummariesForIndex);
677 * Emit the list of files needed for importing into module.
679 void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
680 StringRef OutputName,
681 ModuleSummaryIndex &Index) {
682 auto ModuleCount = Index.modulePaths().size();
684 // Collect for each module the list of function it defines (GUID -> Summary).
685 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
686 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
688 // Generate import/export list
689 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
690 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
691 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
695 if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath])))
696 report_fatal_error(Twine("Failed to open ") + OutputName +
697 " to save imports lists\n");
701 * Perform internalization. Index is updated to reflect linkage changes.
703 void ThinLTOCodeGenerator::internalize(Module &TheModule,
704 ModuleSummaryIndex &Index) {
705 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
706 auto ModuleCount = Index.modulePaths().size();
707 auto ModuleIdentifier = TheModule.getModuleIdentifier();
709 // Convert the preserved symbols set from string to GUID
710 auto GUIDPreservedSymbols =
711 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
713 // Collect for each module the list of function it defines (GUID -> Summary).
714 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
715 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
717 // Compute "dead" symbols, we don't want to import/export these!
718 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols);
720 // Generate import/export list
721 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
722 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
723 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
724 ExportLists, &DeadSymbols);
725 auto &ExportList = ExportLists[ModuleIdentifier];
727 // Be friendly and don't nuke totally the module when the client didn't
728 // supply anything to preserve.
729 if (ExportList.empty() && GUIDPreservedSymbols.empty())
733 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
734 const auto &ExportList = ExportLists.find(ModuleIdentifier);
735 return (ExportList != ExportLists.end() &&
736 ExportList->second.count(GUID)) ||
737 GUIDPreservedSymbols.count(GUID);
739 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
740 thinLTOInternalizeModule(TheModule,
741 ModuleToDefinedGVSummaries[ModuleIdentifier]);
745 * Perform post-importing ThinLTO optimizations.
747 void ThinLTOCodeGenerator::optimize(Module &TheModule) {
748 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
751 optimizeModule(TheModule, *TMBuilder.create(), OptLevel);
755 * Perform ThinLTO CodeGen.
757 std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
758 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
759 return codegenModule(TheModule, *TMBuilder.create());
762 /// Write out the generated object file, either from CacheEntryPath or from
763 /// OutputBuffer, preferring hard-link when possible.
764 /// Returns the path to the generated file in SavedObjectsDirectoryPath.
765 static std::string writeGeneratedObject(int count, StringRef CacheEntryPath,
766 StringRef SavedObjectsDirectoryPath,
767 const MemoryBuffer &OutputBuffer) {
768 SmallString<128> OutputPath(SavedObjectsDirectoryPath);
769 llvm::sys::path::append(OutputPath, Twine(count) + ".thinlto.o");
770 OutputPath.c_str(); // Ensure the string is null terminated.
771 if (sys::fs::exists(OutputPath))
772 sys::fs::remove(OutputPath);
774 // We don't return a memory buffer to the linker, just a list of files.
775 if (!CacheEntryPath.empty()) {
776 // Cache is enabled, hard-link the entry (or copy if hard-link fails).
777 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
779 return OutputPath.str();
780 // Hard linking failed, try to copy.
781 Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
783 return OutputPath.str();
784 // Copy failed (could be because the CacheEntry was removed from the cache
785 // in the meantime by another process), fall back and try to write down the
786 // buffer to the output.
787 errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
788 << "' to '" << OutputPath << "'\n";
790 // No cache entry, just write out the buffer.
792 raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None);
794 report_fatal_error("Can't open output '" + OutputPath + "'\n");
795 OS << OutputBuffer.getBuffer();
796 return OutputPath.str();
799 // Main entry point for the ThinLTO processing
800 void ThinLTOCodeGenerator::run() {
802 // Perform only parallel codegen and return.
804 assert(ProducedBinaries.empty() && "The generator should not be reused");
805 ProducedBinaries.resize(Modules.size());
807 for (auto &ModuleBuffer : Modules) {
808 Pool.async([&](int count) {
810 Context.setDiscardValueNames(LTODiscardValueNames);
813 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false,
814 /*IsImporting*/ false);
817 ProducedBinaries[count] = codegen(*TheModule);
824 // Sequential linking phase
825 auto Index = linkCombinedIndex();
827 // Save temps: index.
828 if (!SaveTempsDir.empty()) {
829 auto SaveTempPath = SaveTempsDir + "index.bc";
831 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
833 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
834 " to save optimized bitcode\n");
835 WriteIndexToFile(*Index, OS);
838 // Prepare the resulting object vector
839 assert(ProducedBinaries.empty() && "The generator should not be reused");
840 if (SavedObjectsDirectoryPath.empty())
841 ProducedBinaries.resize(Modules.size());
843 sys::fs::create_directories(SavedObjectsDirectoryPath);
845 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
847 report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'");
848 ProducedBinaryFiles.resize(Modules.size());
851 // Prepare the module map.
852 auto ModuleMap = generateModuleMap(Modules);
853 auto ModuleCount = Modules.size();
855 // Collect for each module the list of function it defines (GUID -> Summary).
856 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
857 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
859 // Convert the preserved symbols set from string to GUID, this is needed for
860 // computing the caching hash and the internalization.
861 auto GUIDPreservedSymbols =
862 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
864 // Compute "dead" symbols, we don't want to import/export these!
865 auto DeadSymbols = computeDeadSymbols(*Index, GUIDPreservedSymbols);
867 // Collect the import/export lists for all modules from the call-graph in the
869 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
870 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
871 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
872 ExportLists, &DeadSymbols);
874 // We use a std::map here to be able to have a defined ordering when
875 // producing a hash for the cache entry.
876 // FIXME: we should be able to compute the caching hash for the entry based
877 // on the index, and nuke this map.
878 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
880 // Resolve LinkOnce/Weak symbols, this has to be computed early because it
881 // impacts the caching.
882 resolveWeakForLinkerInIndex(*Index, ResolvedODR);
884 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
885 const auto &ExportList = ExportLists.find(ModuleIdentifier);
886 return (ExportList != ExportLists.end() &&
887 ExportList->second.count(GUID)) ||
888 GUIDPreservedSymbols.count(GUID);
891 // Use global summary-based analysis to identify symbols that can be
892 // internalized (because they aren't exported or preserved as per callback).
893 // Changes are made in the index, consumed in the ThinLTO backends.
894 thinLTOInternalizeAndPromoteInIndex(*Index, isExported);
896 // Make sure that every module has an entry in the ExportLists and
897 // ResolvedODR maps to enable threaded access to these maps below.
898 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
899 ExportLists[DefinedGVSummaries.first()];
900 ResolvedODR[DefinedGVSummaries.first()];
903 // Compute the ordering we will process the inputs: the rough heuristic here
904 // is to sort them per size so that the largest module get schedule as soon as
905 // possible. This is purely a compile-time optimization.
906 std::vector<int> ModulesOrdering;
907 ModulesOrdering.resize(Modules.size());
908 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
909 std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
910 [&](int LeftIndex, int RightIndex) {
911 auto LSize = Modules[LeftIndex].getBufferSize();
912 auto RSize = Modules[RightIndex].getBufferSize();
913 return LSize > RSize;
916 // Parallel optimizer + codegen
918 ThreadPool Pool(ThreadCount);
919 for (auto IndexCount : ModulesOrdering) {
920 auto &ModuleBuffer = Modules[IndexCount];
921 Pool.async([&](int count) {
922 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
923 auto &ExportList = ExportLists[ModuleIdentifier];
925 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
927 // The module may be cached, this helps handling it.
928 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
929 ImportLists[ModuleIdentifier], ExportList,
930 ResolvedODR[ModuleIdentifier],
931 DefinedFunctions, GUIDPreservedSymbols);
932 auto CacheEntryPath = CacheEntry.getEntryPath();
935 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
936 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
937 << CacheEntryPath << "' for buffer " << count << " "
938 << ModuleIdentifier << "\n");
942 if (SavedObjectsDirectoryPath.empty())
943 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
945 ProducedBinaryFiles[count] = writeGeneratedObject(
946 count, CacheEntryPath, SavedObjectsDirectoryPath,
953 Context.setDiscardValueNames(LTODiscardValueNames);
954 Context.enableDebugTypeODRUniquing();
955 auto DiagFileOrErr = setupOptimizationRemarks(Context, count);
956 if (!DiagFileOrErr) {
957 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
958 report_fatal_error("ThinLTO: Can't get an output file for the "
963 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false,
964 /*IsImporting*/ false);
966 // Save temps: original file.
967 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
969 auto &ImportList = ImportLists[ModuleIdentifier];
970 // Run the main process now, and generates a binary
971 auto OutputBuffer = ProcessThinLTOModule(
972 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
973 ExportList, GUIDPreservedSymbols,
974 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
975 DisableCodeGen, SaveTempsDir, OptLevel, count);
977 // Commit to the cache (if enabled)
978 CacheEntry.write(*OutputBuffer);
980 if (SavedObjectsDirectoryPath.empty()) {
981 // We need to generated a memory buffer for the linker.
982 if (!CacheEntryPath.empty()) {
983 // Cache is enabled, reload from the cache
984 // We do this to lower memory pressuree: the buffer is on the heap
985 // and releasing it frees memory that can be used for the next input
986 // file. The final binary link will read from the VFS cache
987 // (hopefully!) or from disk if the memory pressure wasn't too high.
988 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
989 if (auto EC = ReloadedBufferOrErr.getError()) {
990 // On error, keeping the preexisting buffer and printing a
991 // diagnostic is more friendly than just crashing.
992 errs() << "error: can't reload cached file '" << CacheEntryPath
993 << "': " << EC.message() << "\n";
995 OutputBuffer = std::move(*ReloadedBufferOrErr);
998 ProducedBinaries[count] = std::move(OutputBuffer);
1001 ProducedBinaryFiles[count] = writeGeneratedObject(
1002 count, CacheEntryPath, SavedObjectsDirectoryPath, *OutputBuffer);
1007 CachePruning(CacheOptions.Path)
1008 .setPruningInterval(std::chrono::seconds(CacheOptions.PruningInterval))
1009 .setEntryExpiration(std::chrono::seconds(CacheOptions.Expiration))
1010 .setMaxSize(CacheOptions.MaxPercentageOfAvailableSpace)
1013 // If statistics were requested, print them out now.
1014 if (llvm::AreStatisticsEnabled())
1015 llvm::PrintStatistics();