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 #include "llvm/ADT/Statistic.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
20 #include "llvm/Analysis/ProfileSummaryInfo.h"
21 #include "llvm/Analysis/TargetLibraryInfo.h"
22 #include "llvm/Analysis/TargetTransformInfo.h"
23 #include "llvm/Bitcode/BitcodeReader.h"
24 #include "llvm/Bitcode/BitcodeWriter.h"
25 #include "llvm/Bitcode/BitcodeWriterPass.h"
26 #include "llvm/Config/llvm-config.h"
27 #include "llvm/IR/DebugInfo.h"
28 #include "llvm/IR/DiagnosticPrinter.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/LegacyPassManager.h"
31 #include "llvm/IR/Mangler.h"
32 #include "llvm/IR/Verifier.h"
33 #include "llvm/IRReader/IRReader.h"
34 #include "llvm/LTO/LTO.h"
35 #include "llvm/MC/SubtargetFeature.h"
36 #include "llvm/Object/IRObjectFile.h"
37 #include "llvm/Support/CachePruning.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/Error.h"
40 #include "llvm/Support/Path.h"
41 #include "llvm/Support/SHA1.h"
42 #include "llvm/Support/SmallVectorMemoryBuffer.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Support/ThreadPool.h"
45 #include "llvm/Support/Threading.h"
46 #include "llvm/Support/ToolOutputFile.h"
47 #include "llvm/Support/VCSRevision.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include "llvm/Transforms/IPO.h"
50 #include "llvm/Transforms/IPO/FunctionImport.h"
51 #include "llvm/Transforms/IPO/Internalize.h"
52 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
53 #include "llvm/Transforms/ObjCARC.h"
54 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
58 #if !defined(_MSC_VER) && !defined(__MINGW32__)
66 #define DEBUG_TYPE "thinlto"
69 // Flags -discard-value-names, defined in LTOCodeGenerator.cpp
70 extern cl::opt<bool> LTODiscardValueNames;
71 extern cl::opt<std::string> LTORemarksFilename;
72 extern cl::opt<bool> LTOPassRemarksWithHotness;
78 ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency()));
80 // Simple helper to save temporary files for debug.
81 static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
82 unsigned count, StringRef Suffix) {
85 // User asked to save temps, let dump the bitcode file after import.
86 std::string SaveTempPath = (TempDir + llvm::Twine(count) + Suffix).str();
88 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
90 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
91 " to save optimized bitcode\n");
92 WriteBitcodeToFile(TheModule, OS, /* ShouldPreserveUseListOrder */ true);
95 static const GlobalValueSummary *
96 getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
97 // If there is any strong definition anywhere, get it.
98 auto StrongDefForLinker = llvm::find_if(
99 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
100 auto Linkage = Summary->linkage();
101 return !GlobalValue::isAvailableExternallyLinkage(Linkage) &&
102 !GlobalValue::isWeakForLinker(Linkage);
104 if (StrongDefForLinker != GVSummaryList.end())
105 return StrongDefForLinker->get();
106 // Get the first *linker visible* definition for this global in the summary
108 auto FirstDefForLinker = llvm::find_if(
109 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
110 auto Linkage = Summary->linkage();
111 return !GlobalValue::isAvailableExternallyLinkage(Linkage);
113 // Extern templates can be emitted as available_externally.
114 if (FirstDefForLinker == GVSummaryList.end())
116 return FirstDefForLinker->get();
119 // Populate map of GUID to the prevailing copy for any multiply defined
120 // symbols. Currently assume first copy is prevailing, or any strong
121 // definition. Can be refined with Linker information in the future.
122 static void computePrevailingCopies(
123 const ModuleSummaryIndex &Index,
124 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) {
125 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
126 return GVSummaryList.size() > 1;
129 for (auto &I : Index) {
130 if (HasMultipleCopies(I.second.SummaryList))
131 PrevailingCopy[I.first] =
132 getFirstDefinitionForLinker(I.second.SummaryList);
136 static StringMap<MemoryBufferRef>
137 generateModuleMap(const std::vector<ThinLTOBuffer> &Modules) {
138 StringMap<MemoryBufferRef> ModuleMap;
139 for (auto &ModuleBuffer : Modules) {
140 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
142 "Expect unique Buffer Identifier");
143 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer.getMemBuffer();
148 static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
149 if (renameModuleForThinLTO(TheModule, Index))
150 report_fatal_error("renameModuleForThinLTO failed");
154 class ThinLTODiagnosticInfo : public DiagnosticInfo {
157 ThinLTODiagnosticInfo(const Twine &DiagMsg,
158 DiagnosticSeverity Severity = DS_Error)
159 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
160 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
164 /// Verify the module and strip broken debug info.
165 static void verifyLoadedModule(Module &TheModule) {
166 bool BrokenDebugInfo = false;
167 if (verifyModule(TheModule, &dbgs(), &BrokenDebugInfo))
168 report_fatal_error("Broken module found, compilation aborted!");
169 if (BrokenDebugInfo) {
170 TheModule.getContext().diagnose(ThinLTODiagnosticInfo(
171 "Invalid debug info found, debug info will be stripped", DS_Warning));
172 StripDebugInfo(TheModule);
176 static std::unique_ptr<Module>
177 loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
178 bool Lazy, bool IsImporting) {
180 Expected<std::unique_ptr<Module>> ModuleOrErr =
182 ? getLazyBitcodeModule(Buffer, Context,
183 /* ShouldLazyLoadMetadata */ true, IsImporting)
184 : parseBitcodeFile(Buffer, Context);
186 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
187 SMDiagnostic Err = SMDiagnostic(Buffer.getBufferIdentifier(),
188 SourceMgr::DK_Error, EIB.message());
189 Err.print("ThinLTO", errs());
191 report_fatal_error("Can't load module, abort.");
194 verifyLoadedModule(*ModuleOrErr.get());
195 return std::move(ModuleOrErr.get());
199 crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
200 StringMap<MemoryBufferRef> &ModuleMap,
201 const FunctionImporter::ImportMapTy &ImportList) {
202 auto Loader = [&](StringRef Identifier) {
203 return loadModuleFromBuffer(ModuleMap[Identifier], TheModule.getContext(),
204 /*Lazy=*/true, /*IsImporting*/ true);
207 FunctionImporter Importer(Index, Loader);
208 Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
210 handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
211 SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(),
212 SourceMgr::DK_Error, EIB.message());
213 Err.print("ThinLTO", errs());
215 report_fatal_error("importFunctions failed");
217 // Verify again after cross-importing.
218 verifyLoadedModule(TheModule);
221 static void optimizeModule(Module &TheModule, TargetMachine &TM,
222 unsigned OptLevel, bool Freestanding) {
223 // Populate the PassManager
224 PassManagerBuilder PMB;
225 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple());
227 PMB.LibraryInfo->disableAllFunctions();
228 PMB.Inliner = createFunctionInliningPass();
229 // FIXME: should get it from the bitcode?
230 PMB.OptLevel = OptLevel;
231 PMB.LoopVectorize = true;
232 PMB.SLPVectorize = true;
233 // Already did this in verifyLoadedModule().
234 PMB.VerifyInput = false;
235 PMB.VerifyOutput = false;
237 legacy::PassManager PM;
239 // Add the TTI (required to inform the vectorizer about register size for
241 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis()));
244 PMB.populateThinLTOPassManager(PM);
249 // Convert the PreservedSymbols map from "Name" based to "GUID" based.
250 static DenseSet<GlobalValue::GUID>
251 computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
252 const Triple &TheTriple) {
253 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
254 for (auto &Entry : PreservedSymbols) {
255 StringRef Name = Entry.first();
256 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
257 Name = Name.drop_front();
258 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
260 return GUIDPreservedSymbols;
263 std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
265 SmallVector<char, 128> OutputBuffer;
269 raw_svector_ostream OS(OutputBuffer);
270 legacy::PassManager PM;
272 // If the bitcode files contain ARC code and were compiled with optimization,
273 // the ObjCARCContractPass must be run, so do it unconditionally here.
274 PM.add(createObjCARCContractPass());
276 // Setup the codegen now.
277 if (TM.addPassesToEmitFile(PM, OS, nullptr, TargetMachine::CGFT_ObjectFile,
278 /* DisableVerify */ true))
279 report_fatal_error("Failed to setup codegen");
281 // Run codegen now. resulting binary is in OutputBuffer.
284 return make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer));
287 /// Manage caching for a single Module.
288 class ModuleCacheEntry {
289 SmallString<128> EntryPath;
292 // Create a cache entry. This compute a unique hash for the Module considering
293 // the current list of export/import, and offer an interface to query to
294 // access the content in the cache.
296 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
297 const FunctionImporter::ImportMapTy &ImportList,
298 const FunctionImporter::ExportSetTy &ExportList,
299 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
300 const GVSummaryMapTy &DefinedFunctions,
301 const DenseSet<GlobalValue::GUID> &PreservedSymbols, unsigned OptLevel,
302 bool Freestanding, const TargetMachineBuilder &TMBuilder) {
303 if (CachePath.empty())
306 if (!Index.modulePaths().count(ModuleID))
307 // The module does not have an entry, it can't have a hash at all
310 // Compute the unique hash for this entry
311 // This is based on the current compiler version, the module itself, the
312 // export list, the hash for every single module in the import list, the
313 // list of ResolvedODR for the module, and the list of preserved symbols.
315 // Include the hash for the current module
316 auto ModHash = Index.getModuleHash(ModuleID);
318 if (all_of(ModHash, [](uint32_t V) { return V == 0; }))
319 // No hash entry, no caching!
324 // Include the parts of the LTO configuration that affect code generation.
325 auto AddString = [&](StringRef Str) {
327 Hasher.update(ArrayRef<uint8_t>{0});
329 auto AddUnsigned = [&](unsigned I) {
335 Hasher.update(ArrayRef<uint8_t>{Data, 4});
338 // Start with the compiler revision
339 Hasher.update(LLVM_VERSION_STRING);
341 Hasher.update(LLVM_REVISION);
344 // Hash the optimization level and the target machine settings.
345 AddString(TMBuilder.MCpu);
346 // FIXME: Hash more of Options. For now all clients initialize Options from
347 // command-line flags (which is unsupported in production), but may set
348 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
349 // DataSections and DebuggerTuning via command line flags.
350 AddUnsigned(TMBuilder.Options.RelaxELFRelocations);
351 AddUnsigned(TMBuilder.Options.FunctionSections);
352 AddUnsigned(TMBuilder.Options.DataSections);
353 AddUnsigned((unsigned)TMBuilder.Options.DebuggerTuning);
354 AddString(TMBuilder.MAttr);
355 if (TMBuilder.RelocModel)
356 AddUnsigned(*TMBuilder.RelocModel);
357 AddUnsigned(TMBuilder.CGOptLevel);
358 AddUnsigned(OptLevel);
359 AddUnsigned(Freestanding);
361 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
362 for (auto F : ExportList)
363 // The export list can impact the internalization, be conservative here
364 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
366 // Include the hash for every module we import functions from
367 for (auto &Entry : ImportList) {
368 auto ModHash = Index.getModuleHash(Entry.first());
369 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
372 // Include the hash for the resolved ODR.
373 for (auto &Entry : ResolvedODR) {
374 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
375 sizeof(GlobalValue::GUID)));
376 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
377 sizeof(GlobalValue::LinkageTypes)));
380 // Include the hash for the preserved symbols.
381 for (auto &Entry : PreservedSymbols) {
382 if (DefinedFunctions.count(Entry))
384 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
387 // This choice of file name allows the cache to be pruned (see pruneCache()
388 // in include/llvm/Support/CachePruning.h).
389 sys::path::append(EntryPath, CachePath,
390 "llvmcache-" + toHex(Hasher.result()));
393 // Access the path to this entry in the cache.
394 StringRef getEntryPath() { return EntryPath; }
396 // Try loading the buffer for this cache entry.
397 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
398 if (EntryPath.empty())
399 return std::error_code();
401 SmallString<64> ResultPath;
402 std::error_code EC = sys::fs::openFileForRead(
403 Twine(EntryPath), FD, sys::fs::OF_UpdateAtime, &ResultPath);
406 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
407 MemoryBuffer::getOpenFile(FD, EntryPath,
409 /*RequiresNullTerminator*/ false);
414 // Cache the Produced object file
415 void write(const MemoryBuffer &OutputBuffer) {
416 if (EntryPath.empty())
419 // Write to a temporary to avoid race condition
420 SmallString<128> TempFilename;
421 SmallString<128> CachePath(EntryPath);
423 llvm::sys::path::remove_filename(CachePath);
424 sys::path::append(TempFilename, CachePath, "Thin-%%%%%%.tmp.o");
426 sys::fs::createUniqueFile(TempFilename, TempFD, TempFilename);
428 errs() << "Error: " << EC.message() << "\n";
429 report_fatal_error("ThinLTO: Can't get a temporary file");
432 raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
433 OS << OutputBuffer.getBuffer();
435 // Rename temp file to final destination; rename is atomic
436 EC = sys::fs::rename(TempFilename, EntryPath);
438 sys::fs::remove(TempFilename);
442 static std::unique_ptr<MemoryBuffer>
443 ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
444 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM,
445 const FunctionImporter::ImportMapTy &ImportList,
446 const FunctionImporter::ExportSetTy &ExportList,
447 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
448 const GVSummaryMapTy &DefinedGlobals,
449 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
450 bool DisableCodeGen, StringRef SaveTempsDir,
451 bool Freestanding, unsigned OptLevel, unsigned count) {
453 // "Benchmark"-like optimization: single-source case
454 bool SingleModule = (ModuleMap.size() == 1);
457 promoteModule(TheModule, Index);
459 // Apply summary-based LinkOnce/Weak resolution decisions.
460 thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
462 // Save temps: after promotion.
463 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
466 // Be friendly and don't nuke totally the module when the client didn't
467 // supply anything to preserve.
468 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
469 // Apply summary-based internalization decisions.
470 thinLTOInternalizeModule(TheModule, DefinedGlobals);
473 // Save internalized bitcode
474 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
477 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
479 // Save temps: after cross-module import.
480 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
483 optimizeModule(TheModule, TM, OptLevel, Freestanding);
485 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
487 if (DisableCodeGen) {
488 // Configured to stop before CodeGen, serialize the bitcode and return.
489 SmallVector<char, 128> OutputBuffer;
491 raw_svector_ostream OS(OutputBuffer);
492 ProfileSummaryInfo PSI(TheModule);
493 auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI);
494 WriteBitcodeToFile(TheModule, OS, true, &Index);
496 return make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer));
499 return codegenModule(TheModule, TM);
502 /// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
503 /// for caching, and in the \p Index for application during the ThinLTO
504 /// backends. This is needed for correctness for exported symbols (ensure
505 /// at least one copy kept) and a compile-time optimization (to drop duplicate
506 /// copies when possible).
507 static void resolveWeakForLinkerInIndex(
508 ModuleSummaryIndex &Index,
509 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
512 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy;
513 computePrevailingCopies(Index, PrevailingCopy);
515 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
516 const auto &Prevailing = PrevailingCopy.find(GUID);
517 // Not in map means that there was only one copy, which must be prevailing.
518 if (Prevailing == PrevailingCopy.end())
520 return Prevailing->second == S;
523 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
524 GlobalValue::GUID GUID,
525 GlobalValue::LinkageTypes NewLinkage) {
526 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
529 thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
532 // Initialize the TargetMachine builder for a given Triple
533 static void initTMBuilder(TargetMachineBuilder &TMBuilder,
534 const Triple &TheTriple) {
535 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
536 // FIXME this looks pretty terrible...
537 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
538 if (TheTriple.getArch() == llvm::Triple::x86_64)
539 TMBuilder.MCpu = "core2";
540 else if (TheTriple.getArch() == llvm::Triple::x86)
541 TMBuilder.MCpu = "yonah";
542 else if (TheTriple.getArch() == llvm::Triple::aarch64)
543 TMBuilder.MCpu = "cyclone";
545 TMBuilder.TheTriple = std::move(TheTriple);
548 } // end anonymous namespace
550 void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) {
551 ThinLTOBuffer Buffer(Data, Identifier);
554 ErrorOr<std::string> TripleOrErr = expectedToErrorOrAndEmitErrors(
555 Context, getBitcodeTargetTriple(Buffer.getMemBuffer()));
558 TripleStr = *TripleOrErr;
560 Triple TheTriple(TripleStr);
563 initTMBuilder(TMBuilder, Triple(TheTriple));
564 else if (TMBuilder.TheTriple != TheTriple) {
565 if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
566 report_fatal_error("ThinLTO modules with incompatible triples not "
568 initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple)));
571 Modules.push_back(Buffer);
574 void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) {
575 PreservedSymbols.insert(Name);
578 void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) {
579 // FIXME: At the moment, we don't take advantage of this extra information,
580 // we're conservatively considering cross-references as preserved.
581 // CrossReferencedSymbols.insert(Name);
582 PreservedSymbols.insert(Name);
585 // TargetMachine factory
586 std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
588 const Target *TheTarget =
589 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg);
591 report_fatal_error("Can't load target for this Triple: " + ErrMsg);
594 // Use MAttr as the default set of features.
595 SubtargetFeatures Features(MAttr);
596 Features.getDefaultSubtargetFeatures(TheTriple);
597 std::string FeatureStr = Features.getString();
599 return std::unique_ptr<TargetMachine>(
600 TheTarget->createTargetMachine(TheTriple.str(), MCpu, FeatureStr, Options,
601 RelocModel, None, CGOptLevel));
605 * Produce the combined summary index from all the bitcode files:
608 std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
609 std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
610 llvm::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
611 uint64_t NextModuleId = 0;
612 for (auto &ModuleBuffer : Modules) {
613 if (Error Err = readModuleSummaryIndex(ModuleBuffer.getMemBuffer(),
614 *CombinedIndex, NextModuleId++)) {
616 logAllUnhandledErrors(
617 std::move(Err), errs(),
618 "error: can't create module summary index for buffer: ");
622 return CombinedIndex;
625 static void internalizeAndPromoteInIndex(
626 const StringMap<FunctionImporter::ExportSetTy> &ExportLists,
627 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
628 ModuleSummaryIndex &Index) {
629 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
630 const auto &ExportList = ExportLists.find(ModuleIdentifier);
631 return (ExportList != ExportLists.end() &&
632 ExportList->second.count(GUID)) ||
633 GUIDPreservedSymbols.count(GUID);
636 thinLTOInternalizeAndPromoteInIndex(Index, isExported);
639 static void computeDeadSymbolsInIndex(
640 ModuleSummaryIndex &Index,
641 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
642 // We have no symbols resolution available. And can't do any better now in the
643 // case where the prevailing symbol is in a native object. It can be refined
644 // with linker information in the future.
645 auto isPrevailing = [&](GlobalValue::GUID G) {
646 return PrevailingType::Unknown;
648 computeDeadSymbols(Index, GUIDPreservedSymbols, isPrevailing);
652 * Perform promotion and renaming of exported internal functions.
653 * Index is updated to reflect linkage changes from weak resolution.
655 void ThinLTOCodeGenerator::promote(Module &TheModule,
656 ModuleSummaryIndex &Index) {
657 auto ModuleCount = Index.modulePaths().size();
658 auto ModuleIdentifier = TheModule.getModuleIdentifier();
660 // Collect for each module the list of function it defines (GUID -> Summary).
661 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
662 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
664 // Convert the preserved symbols set from string to GUID
665 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
666 PreservedSymbols, Triple(TheModule.getTargetTriple()));
668 // Compute "dead" symbols, we don't want to import/export these!
669 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
671 // Generate import/export list
672 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
673 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
674 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
677 // Resolve LinkOnce/Weak symbols.
678 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
679 resolveWeakForLinkerInIndex(Index, ResolvedODR);
681 thinLTOResolveWeakForLinkerModule(
682 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
684 // Promote the exported values in the index, so that they are promoted
686 internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, Index);
688 promoteModule(TheModule, Index);
692 * Perform cross-module importing for the module identified by ModuleIdentifier.
694 void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule,
695 ModuleSummaryIndex &Index) {
696 auto ModuleMap = generateModuleMap(Modules);
697 auto ModuleCount = Index.modulePaths().size();
699 // Collect for each module the list of function it defines (GUID -> Summary).
700 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
701 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
703 // Convert the preserved symbols set from string to GUID
704 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
705 PreservedSymbols, Triple(TheModule.getTargetTriple()));
707 // Compute "dead" symbols, we don't want to import/export these!
708 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
710 // Generate import/export list
711 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
712 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
713 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
715 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
717 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
721 * Compute the list of summaries needed for importing into module.
723 void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
724 StringRef ModulePath, ModuleSummaryIndex &Index,
725 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
726 auto ModuleCount = Index.modulePaths().size();
728 // Collect for each module the list of function it defines (GUID -> Summary).
729 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
730 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
732 // Generate import/export list
733 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
734 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
735 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
738 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
739 ImportLists[ModulePath],
740 ModuleToSummariesForIndex);
744 * Emit the list of files needed for importing into module.
746 void ThinLTOCodeGenerator::emitImports(StringRef ModulePath,
747 StringRef OutputName,
748 ModuleSummaryIndex &Index) {
749 auto ModuleCount = Index.modulePaths().size();
751 // Collect for each module the list of function it defines (GUID -> Summary).
752 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
753 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
755 // Generate import/export list
756 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
757 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
758 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
761 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
762 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
763 ImportLists[ModulePath],
764 ModuleToSummariesForIndex);
768 EmitImportsFiles(ModulePath, OutputName, ModuleToSummariesForIndex)))
769 report_fatal_error(Twine("Failed to open ") + OutputName +
770 " to save imports lists\n");
774 * Perform internalization. Index is updated to reflect linkage changes.
776 void ThinLTOCodeGenerator::internalize(Module &TheModule,
777 ModuleSummaryIndex &Index) {
778 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
779 auto ModuleCount = Index.modulePaths().size();
780 auto ModuleIdentifier = TheModule.getModuleIdentifier();
782 // Convert the preserved symbols set from string to GUID
783 auto GUIDPreservedSymbols =
784 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
786 // Collect for each module the list of function it defines (GUID -> Summary).
787 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
788 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
790 // Compute "dead" symbols, we don't want to import/export these!
791 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
793 // Generate import/export list
794 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
795 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
796 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
798 auto &ExportList = ExportLists[ModuleIdentifier];
800 // Be friendly and don't nuke totally the module when the client didn't
801 // supply anything to preserve.
802 if (ExportList.empty() && GUIDPreservedSymbols.empty())
806 internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, Index);
807 thinLTOInternalizeModule(TheModule,
808 ModuleToDefinedGVSummaries[ModuleIdentifier]);
812 * Perform post-importing ThinLTO optimizations.
814 void ThinLTOCodeGenerator::optimize(Module &TheModule) {
815 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
818 optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding);
822 * Perform ThinLTO CodeGen.
824 std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
825 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
826 return codegenModule(TheModule, *TMBuilder.create());
829 /// Write out the generated object file, either from CacheEntryPath or from
830 /// OutputBuffer, preferring hard-link when possible.
831 /// Returns the path to the generated file in SavedObjectsDirectoryPath.
832 static std::string writeGeneratedObject(int count, StringRef CacheEntryPath,
833 StringRef SavedObjectsDirectoryPath,
834 const MemoryBuffer &OutputBuffer) {
835 SmallString<128> OutputPath(SavedObjectsDirectoryPath);
836 llvm::sys::path::append(OutputPath, Twine(count) + ".thinlto.o");
837 OutputPath.c_str(); // Ensure the string is null terminated.
838 if (sys::fs::exists(OutputPath))
839 sys::fs::remove(OutputPath);
841 // We don't return a memory buffer to the linker, just a list of files.
842 if (!CacheEntryPath.empty()) {
843 // Cache is enabled, hard-link the entry (or copy if hard-link fails).
844 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
846 return OutputPath.str();
847 // Hard linking failed, try to copy.
848 Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
850 return OutputPath.str();
851 // Copy failed (could be because the CacheEntry was removed from the cache
852 // in the meantime by another process), fall back and try to write down the
853 // buffer to the output.
854 errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
855 << "' to '" << OutputPath << "'\n";
857 // No cache entry, just write out the buffer.
859 raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None);
861 report_fatal_error("Can't open output '" + OutputPath + "'\n");
862 OS << OutputBuffer.getBuffer();
863 return OutputPath.str();
866 // Main entry point for the ThinLTO processing
867 void ThinLTOCodeGenerator::run() {
868 // Prepare the resulting object vector
869 assert(ProducedBinaries.empty() && "The generator should not be reused");
870 if (SavedObjectsDirectoryPath.empty())
871 ProducedBinaries.resize(Modules.size());
873 sys::fs::create_directories(SavedObjectsDirectoryPath);
875 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
877 report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'");
878 ProducedBinaryFiles.resize(Modules.size());
882 // Perform only parallel codegen and return.
885 for (auto &ModuleBuffer : Modules) {
886 Pool.async([&](int count) {
888 Context.setDiscardValueNames(LTODiscardValueNames);
892 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
893 /*IsImporting*/ false);
896 auto OutputBuffer = codegen(*TheModule);
897 if (SavedObjectsDirectoryPath.empty())
898 ProducedBinaries[count] = std::move(OutputBuffer);
900 ProducedBinaryFiles[count] = writeGeneratedObject(
901 count, "", SavedObjectsDirectoryPath, *OutputBuffer);
908 // Sequential linking phase
909 auto Index = linkCombinedIndex();
911 // Save temps: index.
912 if (!SaveTempsDir.empty()) {
913 auto SaveTempPath = SaveTempsDir + "index.bc";
915 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
917 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
918 " to save optimized bitcode\n");
919 WriteIndexToFile(*Index, OS);
923 // Prepare the module map.
924 auto ModuleMap = generateModuleMap(Modules);
925 auto ModuleCount = Modules.size();
927 // Collect for each module the list of function it defines (GUID -> Summary).
928 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
929 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
931 // Convert the preserved symbols set from string to GUID, this is needed for
932 // computing the caching hash and the internalization.
933 auto GUIDPreservedSymbols =
934 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
936 // Compute "dead" symbols, we don't want to import/export these!
937 computeDeadSymbolsInIndex(*Index, GUIDPreservedSymbols);
939 // Collect the import/export lists for all modules from the call-graph in the
941 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
942 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
943 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
946 // We use a std::map here to be able to have a defined ordering when
947 // producing a hash for the cache entry.
948 // FIXME: we should be able to compute the caching hash for the entry based
949 // on the index, and nuke this map.
950 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
952 // Resolve LinkOnce/Weak symbols, this has to be computed early because it
953 // impacts the caching.
954 resolveWeakForLinkerInIndex(*Index, ResolvedODR);
956 // Use global summary-based analysis to identify symbols that can be
957 // internalized (because they aren't exported or preserved as per callback).
958 // Changes are made in the index, consumed in the ThinLTO backends.
959 internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, *Index);
961 // Make sure that every module has an entry in the ExportLists and
962 // ResolvedODR maps to enable threaded access to these maps below.
963 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
964 ExportLists[DefinedGVSummaries.first()];
965 ResolvedODR[DefinedGVSummaries.first()];
968 // Compute the ordering we will process the inputs: the rough heuristic here
969 // is to sort them per size so that the largest module get schedule as soon as
970 // possible. This is purely a compile-time optimization.
971 std::vector<int> ModulesOrdering;
972 ModulesOrdering.resize(Modules.size());
973 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
974 llvm::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
975 [&](int LeftIndex, int RightIndex) {
976 auto LSize = Modules[LeftIndex].getBuffer().size();
977 auto RSize = Modules[RightIndex].getBuffer().size();
978 return LSize > RSize;
981 // Parallel optimizer + codegen
983 ThreadPool Pool(ThreadCount);
984 for (auto IndexCount : ModulesOrdering) {
985 auto &ModuleBuffer = Modules[IndexCount];
986 Pool.async([&](int count) {
987 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
988 auto &ExportList = ExportLists[ModuleIdentifier];
990 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
992 // The module may be cached, this helps handling it.
993 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
994 ImportLists[ModuleIdentifier], ExportList,
995 ResolvedODR[ModuleIdentifier],
996 DefinedFunctions, GUIDPreservedSymbols,
997 OptLevel, Freestanding, TMBuilder);
998 auto CacheEntryPath = CacheEntry.getEntryPath();
1001 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
1002 LLVM_DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss")
1003 << " '" << CacheEntryPath << "' for buffer "
1004 << count << " " << ModuleIdentifier << "\n");
1008 if (SavedObjectsDirectoryPath.empty())
1009 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
1011 ProducedBinaryFiles[count] = writeGeneratedObject(
1012 count, CacheEntryPath, SavedObjectsDirectoryPath,
1013 *ErrOrBuffer.get());
1018 LLVMContext Context;
1019 Context.setDiscardValueNames(LTODiscardValueNames);
1020 Context.enableDebugTypeODRUniquing();
1021 auto DiagFileOrErr = lto::setupOptimizationRemarks(
1022 Context, LTORemarksFilename, LTOPassRemarksWithHotness, count);
1023 if (!DiagFileOrErr) {
1024 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
1025 report_fatal_error("ThinLTO: Can't get an output file for the "
1031 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
1032 /*IsImporting*/ false);
1034 // Save temps: original file.
1035 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
1037 auto &ImportList = ImportLists[ModuleIdentifier];
1038 // Run the main process now, and generates a binary
1039 auto OutputBuffer = ProcessThinLTOModule(
1040 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
1041 ExportList, GUIDPreservedSymbols,
1042 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
1043 DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count);
1045 // Commit to the cache (if enabled)
1046 CacheEntry.write(*OutputBuffer);
1048 if (SavedObjectsDirectoryPath.empty()) {
1049 // We need to generated a memory buffer for the linker.
1050 if (!CacheEntryPath.empty()) {
1051 // When cache is enabled, reload from the cache if possible.
1052 // Releasing the buffer from the heap and reloading it from the
1053 // cache file with mmap helps us to lower memory pressure.
1054 // The freed memory can be used for the next input file.
1055 // The final binary link will read from the VFS cache (hopefully!)
1056 // or from disk (if the memory pressure was too high).
1057 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1058 if (auto EC = ReloadedBufferOrErr.getError()) {
1059 // On error, keep the preexisting buffer and print a diagnostic.
1060 errs() << "error: can't reload cached file '" << CacheEntryPath
1061 << "': " << EC.message() << "\n";
1063 OutputBuffer = std::move(*ReloadedBufferOrErr);
1066 ProducedBinaries[count] = std::move(OutputBuffer);
1069 ProducedBinaryFiles[count] = writeGeneratedObject(
1070 count, CacheEntryPath, SavedObjectsDirectoryPath, *OutputBuffer);
1075 pruneCache(CacheOptions.Path, CacheOptions.Policy);
1077 // If statistics were requested, print them out now.
1078 if (llvm::AreStatisticsEnabled())
1079 llvm::PrintStatistics();
1080 reportAndResetTimings();