1 //===-ThinLTOCodeGenerator.cpp - LLVM Link Time Optimizer -----------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the Thin Link Time Optimization library. This library is
10 // intended to be used by linker to optimize code at link time.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/LTO/legacy/ThinLTOCodeGenerator.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
19 #include "llvm/Analysis/ProfileSummaryInfo.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/Bitcode/BitcodeReader.h"
23 #include "llvm/Bitcode/BitcodeWriter.h"
24 #include "llvm/Bitcode/BitcodeWriterPass.h"
25 #include "llvm/Config/llvm-config.h"
26 #include "llvm/IR/DebugInfo.h"
27 #include "llvm/IR/DiagnosticPrinter.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/LegacyPassManager.h"
30 #include "llvm/IR/Mangler.h"
31 #include "llvm/IR/PassTimingInfo.h"
32 #include "llvm/IR/Verifier.h"
33 #include "llvm/IRReader/IRReader.h"
34 #include "llvm/LTO/LTO.h"
35 #include "llvm/LTO/SummaryBasedOptimizations.h"
36 #include "llvm/MC/SubtargetFeature.h"
37 #include "llvm/Object/IRObjectFile.h"
38 #include "llvm/Support/CachePruning.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Error.h"
41 #include "llvm/Support/Path.h"
42 #include "llvm/Support/SHA1.h"
43 #include "llvm/Support/SmallVectorMemoryBuffer.h"
44 #include "llvm/Support/TargetRegistry.h"
45 #include "llvm/Support/ThreadPool.h"
46 #include "llvm/Support/Threading.h"
47 #include "llvm/Support/ToolOutputFile.h"
48 #include "llvm/Support/VCSRevision.h"
49 #include "llvm/Target/TargetMachine.h"
50 #include "llvm/Transforms/IPO.h"
51 #include "llvm/Transforms/IPO/FunctionImport.h"
52 #include "llvm/Transforms/IPO/Internalize.h"
53 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
54 #include "llvm/Transforms/ObjCARC.h"
55 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
59 #if !defined(_MSC_VER) && !defined(__MINGW32__)
67 #define DEBUG_TYPE "thinlto"
70 // Flags -discard-value-names, defined in LTOCodeGenerator.cpp
71 extern cl::opt
<bool> LTODiscardValueNames
;
72 extern cl::opt
<std::string
> LTORemarksFilename
;
73 extern cl::opt
<bool> LTOPassRemarksWithHotness
;
79 ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency()));
81 // Simple helper to save temporary files for debug.
82 static void saveTempBitcode(const Module
&TheModule
, StringRef TempDir
,
83 unsigned count
, StringRef Suffix
) {
86 // User asked to save temps, let dump the bitcode file after import.
87 std::string SaveTempPath
= (TempDir
+ llvm::Twine(count
) + Suffix
).str();
89 raw_fd_ostream
OS(SaveTempPath
, EC
, sys::fs::F_None
);
91 report_fatal_error(Twine("Failed to open ") + SaveTempPath
+
92 " to save optimized bitcode\n");
93 WriteBitcodeToFile(TheModule
, OS
, /* ShouldPreserveUseListOrder */ true);
96 static const GlobalValueSummary
*
97 getFirstDefinitionForLinker(const GlobalValueSummaryList
&GVSummaryList
) {
98 // If there is any strong definition anywhere, get it.
99 auto StrongDefForLinker
= llvm::find_if(
100 GVSummaryList
, [](const std::unique_ptr
<GlobalValueSummary
> &Summary
) {
101 auto Linkage
= Summary
->linkage();
102 return !GlobalValue::isAvailableExternallyLinkage(Linkage
) &&
103 !GlobalValue::isWeakForLinker(Linkage
);
105 if (StrongDefForLinker
!= GVSummaryList
.end())
106 return StrongDefForLinker
->get();
107 // Get the first *linker visible* definition for this global in the summary
109 auto FirstDefForLinker
= llvm::find_if(
110 GVSummaryList
, [](const std::unique_ptr
<GlobalValueSummary
> &Summary
) {
111 auto Linkage
= Summary
->linkage();
112 return !GlobalValue::isAvailableExternallyLinkage(Linkage
);
114 // Extern templates can be emitted as available_externally.
115 if (FirstDefForLinker
== GVSummaryList
.end())
117 return FirstDefForLinker
->get();
120 // Populate map of GUID to the prevailing copy for any multiply defined
121 // symbols. Currently assume first copy is prevailing, or any strong
122 // definition. Can be refined with Linker information in the future.
123 static void computePrevailingCopies(
124 const ModuleSummaryIndex
&Index
,
125 DenseMap
<GlobalValue::GUID
, const GlobalValueSummary
*> &PrevailingCopy
) {
126 auto HasMultipleCopies
= [&](const GlobalValueSummaryList
&GVSummaryList
) {
127 return GVSummaryList
.size() > 1;
130 for (auto &I
: Index
) {
131 if (HasMultipleCopies(I
.second
.SummaryList
))
132 PrevailingCopy
[I
.first
] =
133 getFirstDefinitionForLinker(I
.second
.SummaryList
);
137 static StringMap
<MemoryBufferRef
>
138 generateModuleMap(const std::vector
<ThinLTOBuffer
> &Modules
) {
139 StringMap
<MemoryBufferRef
> ModuleMap
;
140 for (auto &ModuleBuffer
: Modules
) {
141 assert(ModuleMap
.find(ModuleBuffer
.getBufferIdentifier()) ==
143 "Expect unique Buffer Identifier");
144 ModuleMap
[ModuleBuffer
.getBufferIdentifier()] = ModuleBuffer
.getMemBuffer();
149 static void promoteModule(Module
&TheModule
, const ModuleSummaryIndex
&Index
) {
150 if (renameModuleForThinLTO(TheModule
, Index
))
151 report_fatal_error("renameModuleForThinLTO failed");
155 class ThinLTODiagnosticInfo
: public DiagnosticInfo
{
158 ThinLTODiagnosticInfo(const Twine
&DiagMsg
,
159 DiagnosticSeverity Severity
= DS_Error
)
160 : DiagnosticInfo(DK_Linker
, Severity
), Msg(DiagMsg
) {}
161 void print(DiagnosticPrinter
&DP
) const override
{ DP
<< Msg
; }
165 /// Verify the module and strip broken debug info.
166 static void verifyLoadedModule(Module
&TheModule
) {
167 bool BrokenDebugInfo
= false;
168 if (verifyModule(TheModule
, &dbgs(), &BrokenDebugInfo
))
169 report_fatal_error("Broken module found, compilation aborted!");
170 if (BrokenDebugInfo
) {
171 TheModule
.getContext().diagnose(ThinLTODiagnosticInfo(
172 "Invalid debug info found, debug info will be stripped", DS_Warning
));
173 StripDebugInfo(TheModule
);
177 static std::unique_ptr
<Module
>
178 loadModuleFromBuffer(const MemoryBufferRef
&Buffer
, LLVMContext
&Context
,
179 bool Lazy
, bool IsImporting
) {
181 Expected
<std::unique_ptr
<Module
>> ModuleOrErr
=
183 ? getLazyBitcodeModule(Buffer
, Context
,
184 /* ShouldLazyLoadMetadata */ true, IsImporting
)
185 : parseBitcodeFile(Buffer
, Context
);
187 handleAllErrors(ModuleOrErr
.takeError(), [&](ErrorInfoBase
&EIB
) {
188 SMDiagnostic Err
= SMDiagnostic(Buffer
.getBufferIdentifier(),
189 SourceMgr::DK_Error
, EIB
.message());
190 Err
.print("ThinLTO", errs());
192 report_fatal_error("Can't load module, abort.");
195 verifyLoadedModule(*ModuleOrErr
.get());
196 return std::move(ModuleOrErr
.get());
200 crossImportIntoModule(Module
&TheModule
, const ModuleSummaryIndex
&Index
,
201 StringMap
<MemoryBufferRef
> &ModuleMap
,
202 const FunctionImporter::ImportMapTy
&ImportList
) {
203 auto Loader
= [&](StringRef Identifier
) {
204 return loadModuleFromBuffer(ModuleMap
[Identifier
], TheModule
.getContext(),
205 /*Lazy=*/true, /*IsImporting*/ true);
208 FunctionImporter
Importer(Index
, Loader
);
209 Expected
<bool> Result
= Importer
.importFunctions(TheModule
, ImportList
);
211 handleAllErrors(Result
.takeError(), [&](ErrorInfoBase
&EIB
) {
212 SMDiagnostic Err
= SMDiagnostic(TheModule
.getModuleIdentifier(),
213 SourceMgr::DK_Error
, EIB
.message());
214 Err
.print("ThinLTO", errs());
216 report_fatal_error("importFunctions failed");
218 // Verify again after cross-importing.
219 verifyLoadedModule(TheModule
);
222 static void optimizeModule(Module
&TheModule
, TargetMachine
&TM
,
223 unsigned OptLevel
, bool Freestanding
) {
224 // Populate the PassManager
225 PassManagerBuilder PMB
;
226 PMB
.LibraryInfo
= new TargetLibraryInfoImpl(TM
.getTargetTriple());
228 PMB
.LibraryInfo
->disableAllFunctions();
229 PMB
.Inliner
= createFunctionInliningPass();
230 // FIXME: should get it from the bitcode?
231 PMB
.OptLevel
= OptLevel
;
232 PMB
.LoopVectorize
= true;
233 PMB
.SLPVectorize
= true;
234 // Already did this in verifyLoadedModule().
235 PMB
.VerifyInput
= false;
236 PMB
.VerifyOutput
= false;
238 legacy::PassManager PM
;
240 // Add the TTI (required to inform the vectorizer about register size for
242 PM
.add(createTargetTransformInfoWrapperPass(TM
.getTargetIRAnalysis()));
245 PMB
.populateThinLTOPassManager(PM
);
250 // Convert the PreservedSymbols map from "Name" based to "GUID" based.
251 static DenseSet
<GlobalValue::GUID
>
252 computeGUIDPreservedSymbols(const StringSet
<> &PreservedSymbols
,
253 const Triple
&TheTriple
) {
254 DenseSet
<GlobalValue::GUID
> GUIDPreservedSymbols(PreservedSymbols
.size());
255 for (auto &Entry
: PreservedSymbols
) {
256 StringRef Name
= Entry
.first();
257 if (TheTriple
.isOSBinFormatMachO() && Name
.size() > 0 && Name
[0] == '_')
258 Name
= Name
.drop_front();
259 GUIDPreservedSymbols
.insert(GlobalValue::getGUID(Name
));
261 return GUIDPreservedSymbols
;
264 std::unique_ptr
<MemoryBuffer
> codegenModule(Module
&TheModule
,
266 SmallVector
<char, 128> OutputBuffer
;
270 raw_svector_ostream
OS(OutputBuffer
);
271 legacy::PassManager PM
;
273 // If the bitcode files contain ARC code and were compiled with optimization,
274 // the ObjCARCContractPass must be run, so do it unconditionally here.
275 PM
.add(createObjCARCContractPass());
277 // Setup the codegen now.
278 if (TM
.addPassesToEmitFile(PM
, OS
, nullptr, TargetMachine::CGFT_ObjectFile
,
279 /* DisableVerify */ true))
280 report_fatal_error("Failed to setup codegen");
282 // Run codegen now. resulting binary is in OutputBuffer.
285 return make_unique
<SmallVectorMemoryBuffer
>(std::move(OutputBuffer
));
288 /// Manage caching for a single Module.
289 class ModuleCacheEntry
{
290 SmallString
<128> EntryPath
;
293 // Create a cache entry. This compute a unique hash for the Module considering
294 // the current list of export/import, and offer an interface to query to
295 // access the content in the cache.
297 StringRef CachePath
, const ModuleSummaryIndex
&Index
, StringRef ModuleID
,
298 const FunctionImporter::ImportMapTy
&ImportList
,
299 const FunctionImporter::ExportSetTy
&ExportList
,
300 const std::map
<GlobalValue::GUID
, GlobalValue::LinkageTypes
> &ResolvedODR
,
301 const GVSummaryMapTy
&DefinedGVSummaries
, 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 if (all_of(Index
.getModuleHash(ModuleID
),
311 [](uint32_t V
) { return V
== 0; }))
312 // No hash entry, no caching!
315 llvm::lto::Config Conf
;
316 Conf
.OptLevel
= OptLevel
;
317 Conf
.Options
= TMBuilder
.Options
;
318 Conf
.CPU
= TMBuilder
.MCpu
;
319 Conf
.MAttrs
.push_back(TMBuilder
.MAttr
);
320 Conf
.RelocModel
= TMBuilder
.RelocModel
;
321 Conf
.CGOptLevel
= TMBuilder
.CGOptLevel
;
322 Conf
.Freestanding
= Freestanding
;
324 computeLTOCacheKey(Key
, Conf
, Index
, ModuleID
, ImportList
, ExportList
,
325 ResolvedODR
, DefinedGVSummaries
);
327 // This choice of file name allows the cache to be pruned (see pruneCache()
328 // in include/llvm/Support/CachePruning.h).
329 sys::path::append(EntryPath
, CachePath
, "llvmcache-" + Key
);
332 // Access the path to this entry in the cache.
333 StringRef
getEntryPath() { return EntryPath
; }
335 // Try loading the buffer for this cache entry.
336 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> tryLoadingBuffer() {
337 if (EntryPath
.empty())
338 return std::error_code();
340 SmallString
<64> ResultPath
;
341 std::error_code EC
= sys::fs::openFileForRead(
342 Twine(EntryPath
), FD
, sys::fs::OF_UpdateAtime
, &ResultPath
);
345 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> MBOrErr
=
346 MemoryBuffer::getOpenFile(FD
, EntryPath
,
348 /*RequiresNullTerminator*/ false);
353 // Cache the Produced object file
354 void write(const MemoryBuffer
&OutputBuffer
) {
355 if (EntryPath
.empty())
358 // Write to a temporary to avoid race condition
359 SmallString
<128> TempFilename
;
360 SmallString
<128> CachePath(EntryPath
);
362 llvm::sys::path::remove_filename(CachePath
);
363 sys::path::append(TempFilename
, CachePath
, "Thin-%%%%%%.tmp.o");
365 sys::fs::createUniqueFile(TempFilename
, TempFD
, TempFilename
);
367 errs() << "Error: " << EC
.message() << "\n";
368 report_fatal_error("ThinLTO: Can't get a temporary file");
371 raw_fd_ostream
OS(TempFD
, /* ShouldClose */ true);
372 OS
<< OutputBuffer
.getBuffer();
374 // Rename temp file to final destination; rename is atomic
375 EC
= sys::fs::rename(TempFilename
, EntryPath
);
377 sys::fs::remove(TempFilename
);
381 static std::unique_ptr
<MemoryBuffer
>
382 ProcessThinLTOModule(Module
&TheModule
, ModuleSummaryIndex
&Index
,
383 StringMap
<MemoryBufferRef
> &ModuleMap
, TargetMachine
&TM
,
384 const FunctionImporter::ImportMapTy
&ImportList
,
385 const FunctionImporter::ExportSetTy
&ExportList
,
386 const DenseSet
<GlobalValue::GUID
> &GUIDPreservedSymbols
,
387 const GVSummaryMapTy
&DefinedGlobals
,
388 const ThinLTOCodeGenerator::CachingOptions
&CacheOptions
,
389 bool DisableCodeGen
, StringRef SaveTempsDir
,
390 bool Freestanding
, unsigned OptLevel
, unsigned count
) {
392 // "Benchmark"-like optimization: single-source case
393 bool SingleModule
= (ModuleMap
.size() == 1);
396 promoteModule(TheModule
, Index
);
398 // Apply summary-based prevailing-symbol resolution decisions.
399 thinLTOResolvePrevailingInModule(TheModule
, DefinedGlobals
);
401 // Save temps: after promotion.
402 saveTempBitcode(TheModule
, SaveTempsDir
, count
, ".1.promoted.bc");
405 // Be friendly and don't nuke totally the module when the client didn't
406 // supply anything to preserve.
407 if (!ExportList
.empty() || !GUIDPreservedSymbols
.empty()) {
408 // Apply summary-based internalization decisions.
409 thinLTOInternalizeModule(TheModule
, DefinedGlobals
);
412 // Save internalized bitcode
413 saveTempBitcode(TheModule
, SaveTempsDir
, count
, ".2.internalized.bc");
416 crossImportIntoModule(TheModule
, Index
, ModuleMap
, ImportList
);
418 // Save temps: after cross-module import.
419 saveTempBitcode(TheModule
, SaveTempsDir
, count
, ".3.imported.bc");
422 optimizeModule(TheModule
, TM
, OptLevel
, Freestanding
);
424 saveTempBitcode(TheModule
, SaveTempsDir
, count
, ".4.opt.bc");
426 if (DisableCodeGen
) {
427 // Configured to stop before CodeGen, serialize the bitcode and return.
428 SmallVector
<char, 128> OutputBuffer
;
430 raw_svector_ostream
OS(OutputBuffer
);
431 ProfileSummaryInfo
PSI(TheModule
);
432 auto Index
= buildModuleSummaryIndex(TheModule
, nullptr, &PSI
);
433 WriteBitcodeToFile(TheModule
, OS
, true, &Index
);
435 return make_unique
<SmallVectorMemoryBuffer
>(std::move(OutputBuffer
));
438 return codegenModule(TheModule
, TM
);
441 /// Resolve prevailing symbols. Record resolutions in the \p ResolvedODR map
442 /// for caching, and in the \p Index for application during the ThinLTO
443 /// backends. This is needed for correctness for exported symbols (ensure
444 /// at least one copy kept) and a compile-time optimization (to drop duplicate
445 /// copies when possible).
446 static void resolvePrevailingInIndex(
447 ModuleSummaryIndex
&Index
,
448 StringMap
<std::map
<GlobalValue::GUID
, GlobalValue::LinkageTypes
>>
451 DenseMap
<GlobalValue::GUID
, const GlobalValueSummary
*> PrevailingCopy
;
452 computePrevailingCopies(Index
, PrevailingCopy
);
454 auto isPrevailing
= [&](GlobalValue::GUID GUID
, const GlobalValueSummary
*S
) {
455 const auto &Prevailing
= PrevailingCopy
.find(GUID
);
456 // Not in map means that there was only one copy, which must be prevailing.
457 if (Prevailing
== PrevailingCopy
.end())
459 return Prevailing
->second
== S
;
462 auto recordNewLinkage
= [&](StringRef ModuleIdentifier
,
463 GlobalValue::GUID GUID
,
464 GlobalValue::LinkageTypes NewLinkage
) {
465 ResolvedODR
[ModuleIdentifier
][GUID
] = NewLinkage
;
468 thinLTOResolvePrevailingInIndex(Index
, isPrevailing
, recordNewLinkage
);
471 // Initialize the TargetMachine builder for a given Triple
472 static void initTMBuilder(TargetMachineBuilder
&TMBuilder
,
473 const Triple
&TheTriple
) {
474 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
475 // FIXME this looks pretty terrible...
476 if (TMBuilder
.MCpu
.empty() && TheTriple
.isOSDarwin()) {
477 if (TheTriple
.getArch() == llvm::Triple::x86_64
)
478 TMBuilder
.MCpu
= "core2";
479 else if (TheTriple
.getArch() == llvm::Triple::x86
)
480 TMBuilder
.MCpu
= "yonah";
481 else if (TheTriple
.getArch() == llvm::Triple::aarch64
)
482 TMBuilder
.MCpu
= "cyclone";
484 TMBuilder
.TheTriple
= std::move(TheTriple
);
487 } // end anonymous namespace
489 void ThinLTOCodeGenerator::addModule(StringRef Identifier
, StringRef Data
) {
490 ThinLTOBuffer
Buffer(Data
, Identifier
);
493 ErrorOr
<std::string
> TripleOrErr
= expectedToErrorOrAndEmitErrors(
494 Context
, getBitcodeTargetTriple(Buffer
.getMemBuffer()));
497 TripleStr
= *TripleOrErr
;
499 Triple
TheTriple(TripleStr
);
502 initTMBuilder(TMBuilder
, Triple(TheTriple
));
503 else if (TMBuilder
.TheTriple
!= TheTriple
) {
504 if (!TMBuilder
.TheTriple
.isCompatibleWith(TheTriple
))
505 report_fatal_error("ThinLTO modules with incompatible triples not "
507 initTMBuilder(TMBuilder
, Triple(TMBuilder
.TheTriple
.merge(TheTriple
)));
510 Modules
.push_back(Buffer
);
513 void ThinLTOCodeGenerator::preserveSymbol(StringRef Name
) {
514 PreservedSymbols
.insert(Name
);
517 void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name
) {
518 // FIXME: At the moment, we don't take advantage of this extra information,
519 // we're conservatively considering cross-references as preserved.
520 // CrossReferencedSymbols.insert(Name);
521 PreservedSymbols
.insert(Name
);
524 // TargetMachine factory
525 std::unique_ptr
<TargetMachine
> TargetMachineBuilder::create() const {
527 const Target
*TheTarget
=
528 TargetRegistry::lookupTarget(TheTriple
.str(), ErrMsg
);
530 report_fatal_error("Can't load target for this Triple: " + ErrMsg
);
533 // Use MAttr as the default set of features.
534 SubtargetFeatures
Features(MAttr
);
535 Features
.getDefaultSubtargetFeatures(TheTriple
);
536 std::string FeatureStr
= Features
.getString();
538 return std::unique_ptr
<TargetMachine
>(
539 TheTarget
->createTargetMachine(TheTriple
.str(), MCpu
, FeatureStr
, Options
,
540 RelocModel
, None
, CGOptLevel
));
544 * Produce the combined summary index from all the bitcode files:
547 std::unique_ptr
<ModuleSummaryIndex
> ThinLTOCodeGenerator::linkCombinedIndex() {
548 std::unique_ptr
<ModuleSummaryIndex
> CombinedIndex
=
549 llvm::make_unique
<ModuleSummaryIndex
>(/*HaveGVs=*/false);
550 uint64_t NextModuleId
= 0;
551 for (auto &ModuleBuffer
: Modules
) {
552 if (Error Err
= readModuleSummaryIndex(ModuleBuffer
.getMemBuffer(),
553 *CombinedIndex
, NextModuleId
++)) {
555 logAllUnhandledErrors(
556 std::move(Err
), errs(),
557 "error: can't create module summary index for buffer: ");
561 return CombinedIndex
;
564 static void internalizeAndPromoteInIndex(
565 const StringMap
<FunctionImporter::ExportSetTy
> &ExportLists
,
566 const DenseSet
<GlobalValue::GUID
> &GUIDPreservedSymbols
,
567 ModuleSummaryIndex
&Index
) {
568 auto isExported
= [&](StringRef ModuleIdentifier
, GlobalValue::GUID GUID
) {
569 const auto &ExportList
= ExportLists
.find(ModuleIdentifier
);
570 return (ExportList
!= ExportLists
.end() &&
571 ExportList
->second
.count(GUID
)) ||
572 GUIDPreservedSymbols
.count(GUID
);
575 thinLTOInternalizeAndPromoteInIndex(Index
, isExported
);
578 static void computeDeadSymbolsInIndex(
579 ModuleSummaryIndex
&Index
,
580 const DenseSet
<GlobalValue::GUID
> &GUIDPreservedSymbols
) {
581 // We have no symbols resolution available. And can't do any better now in the
582 // case where the prevailing symbol is in a native object. It can be refined
583 // with linker information in the future.
584 auto isPrevailing
= [&](GlobalValue::GUID G
) {
585 return PrevailingType::Unknown
;
587 computeDeadSymbolsWithConstProp(Index
, GUIDPreservedSymbols
, isPrevailing
,
588 /* ImportEnabled = */ true);
592 * Perform promotion and renaming of exported internal functions.
593 * Index is updated to reflect linkage changes from weak resolution.
595 void ThinLTOCodeGenerator::promote(Module
&TheModule
,
596 ModuleSummaryIndex
&Index
) {
597 auto ModuleCount
= Index
.modulePaths().size();
598 auto ModuleIdentifier
= TheModule
.getModuleIdentifier();
600 // Collect for each module the list of function it defines (GUID -> Summary).
601 StringMap
<GVSummaryMapTy
> ModuleToDefinedGVSummaries
;
602 Index
.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries
);
604 // Convert the preserved symbols set from string to GUID
605 auto GUIDPreservedSymbols
= computeGUIDPreservedSymbols(
606 PreservedSymbols
, Triple(TheModule
.getTargetTriple()));
608 // Compute "dead" symbols, we don't want to import/export these!
609 computeDeadSymbolsInIndex(Index
, GUIDPreservedSymbols
);
611 // Generate import/export list
612 StringMap
<FunctionImporter::ImportMapTy
> ImportLists(ModuleCount
);
613 StringMap
<FunctionImporter::ExportSetTy
> ExportLists(ModuleCount
);
614 ComputeCrossModuleImport(Index
, ModuleToDefinedGVSummaries
, ImportLists
,
617 // Resolve prevailing symbols
618 StringMap
<std::map
<GlobalValue::GUID
, GlobalValue::LinkageTypes
>> ResolvedODR
;
619 resolvePrevailingInIndex(Index
, ResolvedODR
);
621 thinLTOResolvePrevailingInModule(
622 TheModule
, ModuleToDefinedGVSummaries
[ModuleIdentifier
]);
624 // Promote the exported values in the index, so that they are promoted
626 internalizeAndPromoteInIndex(ExportLists
, GUIDPreservedSymbols
, Index
);
628 promoteModule(TheModule
, Index
);
632 * Perform cross-module importing for the module identified by ModuleIdentifier.
634 void ThinLTOCodeGenerator::crossModuleImport(Module
&TheModule
,
635 ModuleSummaryIndex
&Index
) {
636 auto ModuleMap
= generateModuleMap(Modules
);
637 auto ModuleCount
= Index
.modulePaths().size();
639 // Collect for each module the list of function it defines (GUID -> Summary).
640 StringMap
<GVSummaryMapTy
> ModuleToDefinedGVSummaries(ModuleCount
);
641 Index
.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries
);
643 // Convert the preserved symbols set from string to GUID
644 auto GUIDPreservedSymbols
= computeGUIDPreservedSymbols(
645 PreservedSymbols
, Triple(TheModule
.getTargetTriple()));
647 // Compute "dead" symbols, we don't want to import/export these!
648 computeDeadSymbolsInIndex(Index
, GUIDPreservedSymbols
);
650 // Generate import/export list
651 StringMap
<FunctionImporter::ImportMapTy
> ImportLists(ModuleCount
);
652 StringMap
<FunctionImporter::ExportSetTy
> ExportLists(ModuleCount
);
653 ComputeCrossModuleImport(Index
, ModuleToDefinedGVSummaries
, ImportLists
,
655 auto &ImportList
= ImportLists
[TheModule
.getModuleIdentifier()];
657 crossImportIntoModule(TheModule
, Index
, ModuleMap
, ImportList
);
661 * Compute the list of summaries needed for importing into module.
663 void ThinLTOCodeGenerator::gatherImportedSummariesForModule(
664 Module
&TheModule
, ModuleSummaryIndex
&Index
,
665 std::map
<std::string
, GVSummaryMapTy
> &ModuleToSummariesForIndex
) {
666 auto ModuleCount
= Index
.modulePaths().size();
667 auto ModuleIdentifier
= TheModule
.getModuleIdentifier();
669 // Collect for each module the list of function it defines (GUID -> Summary).
670 StringMap
<GVSummaryMapTy
> ModuleToDefinedGVSummaries(ModuleCount
);
671 Index
.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries
);
673 // Convert the preserved symbols set from string to GUID
674 auto GUIDPreservedSymbols
= computeGUIDPreservedSymbols(
675 PreservedSymbols
, Triple(TheModule
.getTargetTriple()));
677 // Compute "dead" symbols, we don't want to import/export these!
678 computeDeadSymbolsInIndex(Index
, GUIDPreservedSymbols
);
680 // Generate import/export list
681 StringMap
<FunctionImporter::ImportMapTy
> ImportLists(ModuleCount
);
682 StringMap
<FunctionImporter::ExportSetTy
> ExportLists(ModuleCount
);
683 ComputeCrossModuleImport(Index
, ModuleToDefinedGVSummaries
, ImportLists
,
686 llvm::gatherImportedSummariesForModule(
687 ModuleIdentifier
, ModuleToDefinedGVSummaries
,
688 ImportLists
[ModuleIdentifier
], ModuleToSummariesForIndex
);
692 * Emit the list of files needed for importing into module.
694 void ThinLTOCodeGenerator::emitImports(Module
&TheModule
, StringRef OutputName
,
695 ModuleSummaryIndex
&Index
) {
696 auto ModuleCount
= Index
.modulePaths().size();
697 auto ModuleIdentifier
= TheModule
.getModuleIdentifier();
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
,
716 std::map
<std::string
, GVSummaryMapTy
> ModuleToSummariesForIndex
;
717 llvm::gatherImportedSummariesForModule(
718 ModuleIdentifier
, ModuleToDefinedGVSummaries
,
719 ImportLists
[ModuleIdentifier
], ModuleToSummariesForIndex
);
722 if ((EC
= EmitImportsFiles(ModuleIdentifier
, OutputName
,
723 ModuleToSummariesForIndex
)))
724 report_fatal_error(Twine("Failed to open ") + OutputName
+
725 " to save imports lists\n");
729 * Perform internalization. Index is updated to reflect linkage changes.
731 void ThinLTOCodeGenerator::internalize(Module
&TheModule
,
732 ModuleSummaryIndex
&Index
) {
733 initTMBuilder(TMBuilder
, Triple(TheModule
.getTargetTriple()));
734 auto ModuleCount
= Index
.modulePaths().size();
735 auto ModuleIdentifier
= TheModule
.getModuleIdentifier();
737 // Convert the preserved symbols set from string to GUID
738 auto GUIDPreservedSymbols
=
739 computeGUIDPreservedSymbols(PreservedSymbols
, TMBuilder
.TheTriple
);
741 // Collect for each module the list of function it defines (GUID -> Summary).
742 StringMap
<GVSummaryMapTy
> ModuleToDefinedGVSummaries(ModuleCount
);
743 Index
.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries
);
745 // Compute "dead" symbols, we don't want to import/export these!
746 computeDeadSymbolsInIndex(Index
, GUIDPreservedSymbols
);
748 // Generate import/export list
749 StringMap
<FunctionImporter::ImportMapTy
> ImportLists(ModuleCount
);
750 StringMap
<FunctionImporter::ExportSetTy
> ExportLists(ModuleCount
);
751 ComputeCrossModuleImport(Index
, ModuleToDefinedGVSummaries
, ImportLists
,
753 auto &ExportList
= ExportLists
[ModuleIdentifier
];
755 // Be friendly and don't nuke totally the module when the client didn't
756 // supply anything to preserve.
757 if (ExportList
.empty() && GUIDPreservedSymbols
.empty())
761 internalizeAndPromoteInIndex(ExportLists
, GUIDPreservedSymbols
, Index
);
762 thinLTOInternalizeModule(TheModule
,
763 ModuleToDefinedGVSummaries
[ModuleIdentifier
]);
767 * Perform post-importing ThinLTO optimizations.
769 void ThinLTOCodeGenerator::optimize(Module
&TheModule
) {
770 initTMBuilder(TMBuilder
, Triple(TheModule
.getTargetTriple()));
773 optimizeModule(TheModule
, *TMBuilder
.create(), OptLevel
, Freestanding
);
776 /// Write out the generated object file, either from CacheEntryPath or from
777 /// OutputBuffer, preferring hard-link when possible.
778 /// Returns the path to the generated file in SavedObjectsDirectoryPath.
779 static std::string
writeGeneratedObject(int count
, StringRef CacheEntryPath
,
780 StringRef SavedObjectsDirectoryPath
,
781 const MemoryBuffer
&OutputBuffer
) {
782 SmallString
<128> OutputPath(SavedObjectsDirectoryPath
);
783 llvm::sys::path::append(OutputPath
, Twine(count
) + ".thinlto.o");
784 OutputPath
.c_str(); // Ensure the string is null terminated.
785 if (sys::fs::exists(OutputPath
))
786 sys::fs::remove(OutputPath
);
788 // We don't return a memory buffer to the linker, just a list of files.
789 if (!CacheEntryPath
.empty()) {
790 // Cache is enabled, hard-link the entry (or copy if hard-link fails).
791 auto Err
= sys::fs::create_hard_link(CacheEntryPath
, OutputPath
);
793 return OutputPath
.str();
794 // Hard linking failed, try to copy.
795 Err
= sys::fs::copy_file(CacheEntryPath
, OutputPath
);
797 return OutputPath
.str();
798 // Copy failed (could be because the CacheEntry was removed from the cache
799 // in the meantime by another process), fall back and try to write down the
800 // buffer to the output.
801 errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
802 << "' to '" << OutputPath
<< "'\n";
804 // No cache entry, just write out the buffer.
806 raw_fd_ostream
OS(OutputPath
, Err
, sys::fs::F_None
);
808 report_fatal_error("Can't open output '" + OutputPath
+ "'\n");
809 OS
<< OutputBuffer
.getBuffer();
810 return OutputPath
.str();
813 // Main entry point for the ThinLTO processing
814 void ThinLTOCodeGenerator::run() {
815 // Prepare the resulting object vector
816 assert(ProducedBinaries
.empty() && "The generator should not be reused");
817 if (SavedObjectsDirectoryPath
.empty())
818 ProducedBinaries
.resize(Modules
.size());
820 sys::fs::create_directories(SavedObjectsDirectoryPath
);
822 sys::fs::is_directory(SavedObjectsDirectoryPath
, IsDir
);
824 report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath
+ "'");
825 ProducedBinaryFiles
.resize(Modules
.size());
829 // Perform only parallel codegen and return.
832 for (auto &ModuleBuffer
: Modules
) {
833 Pool
.async([&](int count
) {
835 Context
.setDiscardValueNames(LTODiscardValueNames
);
839 loadModuleFromBuffer(ModuleBuffer
.getMemBuffer(), Context
, false,
840 /*IsImporting*/ false);
843 auto OutputBuffer
= codegenModule(*TheModule
, *TMBuilder
.create());
844 if (SavedObjectsDirectoryPath
.empty())
845 ProducedBinaries
[count
] = std::move(OutputBuffer
);
847 ProducedBinaryFiles
[count
] = writeGeneratedObject(
848 count
, "", SavedObjectsDirectoryPath
, *OutputBuffer
);
855 // Sequential linking phase
856 auto Index
= linkCombinedIndex();
858 // Save temps: index.
859 if (!SaveTempsDir
.empty()) {
860 auto SaveTempPath
= SaveTempsDir
+ "index.bc";
862 raw_fd_ostream
OS(SaveTempPath
, EC
, sys::fs::F_None
);
864 report_fatal_error(Twine("Failed to open ") + SaveTempPath
+
865 " to save optimized bitcode\n");
866 WriteIndexToFile(*Index
, OS
);
870 // Prepare the module map.
871 auto ModuleMap
= generateModuleMap(Modules
);
872 auto ModuleCount
= Modules
.size();
874 // Collect for each module the list of function it defines (GUID -> Summary).
875 StringMap
<GVSummaryMapTy
> ModuleToDefinedGVSummaries(ModuleCount
);
876 Index
->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries
);
878 // Convert the preserved symbols set from string to GUID, this is needed for
879 // computing the caching hash and the internalization.
880 auto GUIDPreservedSymbols
=
881 computeGUIDPreservedSymbols(PreservedSymbols
, TMBuilder
.TheTriple
);
883 // Compute "dead" symbols, we don't want to import/export these!
884 computeDeadSymbolsInIndex(*Index
, GUIDPreservedSymbols
);
886 // Synthesize entry counts for functions in the combined index.
887 computeSyntheticCounts(*Index
);
889 // Collect the import/export lists for all modules from the call-graph in the
891 StringMap
<FunctionImporter::ImportMapTy
> ImportLists(ModuleCount
);
892 StringMap
<FunctionImporter::ExportSetTy
> ExportLists(ModuleCount
);
893 ComputeCrossModuleImport(*Index
, ModuleToDefinedGVSummaries
, ImportLists
,
896 // We use a std::map here to be able to have a defined ordering when
897 // producing a hash for the cache entry.
898 // FIXME: we should be able to compute the caching hash for the entry based
899 // on the index, and nuke this map.
900 StringMap
<std::map
<GlobalValue::GUID
, GlobalValue::LinkageTypes
>> ResolvedODR
;
902 // Resolve prevailing symbols, this has to be computed early because it
903 // impacts the caching.
904 resolvePrevailingInIndex(*Index
, ResolvedODR
);
906 // Use global summary-based analysis to identify symbols that can be
907 // internalized (because they aren't exported or preserved as per callback).
908 // Changes are made in the index, consumed in the ThinLTO backends.
909 internalizeAndPromoteInIndex(ExportLists
, GUIDPreservedSymbols
, *Index
);
911 // Make sure that every module has an entry in the ExportLists, ImportList,
912 // GVSummary and ResolvedODR maps to enable threaded access to these maps
914 for (auto &Module
: Modules
) {
915 auto ModuleIdentifier
= Module
.getBufferIdentifier();
916 ExportLists
[ModuleIdentifier
];
917 ImportLists
[ModuleIdentifier
];
918 ResolvedODR
[ModuleIdentifier
];
919 ModuleToDefinedGVSummaries
[ModuleIdentifier
];
922 // Compute the ordering we will process the inputs: the rough heuristic here
923 // is to sort them per size so that the largest module get schedule as soon as
924 // possible. This is purely a compile-time optimization.
925 std::vector
<int> ModulesOrdering
;
926 ModulesOrdering
.resize(Modules
.size());
927 std::iota(ModulesOrdering
.begin(), ModulesOrdering
.end(), 0);
928 llvm::sort(ModulesOrdering
, [&](int LeftIndex
, int RightIndex
) {
929 auto LSize
= Modules
[LeftIndex
].getBuffer().size();
930 auto RSize
= Modules
[RightIndex
].getBuffer().size();
931 return LSize
> RSize
;
934 // Parallel optimizer + codegen
936 ThreadPool
Pool(ThreadCount
);
937 for (auto IndexCount
: ModulesOrdering
) {
938 auto &ModuleBuffer
= Modules
[IndexCount
];
939 Pool
.async([&](int count
) {
940 auto ModuleIdentifier
= ModuleBuffer
.getBufferIdentifier();
941 auto &ExportList
= ExportLists
[ModuleIdentifier
];
943 auto &DefinedGVSummaries
= ModuleToDefinedGVSummaries
[ModuleIdentifier
];
945 // The module may be cached, this helps handling it.
946 ModuleCacheEntry
CacheEntry(CacheOptions
.Path
, *Index
, ModuleIdentifier
,
947 ImportLists
[ModuleIdentifier
], ExportList
,
948 ResolvedODR
[ModuleIdentifier
],
949 DefinedGVSummaries
, OptLevel
, Freestanding
,
951 auto CacheEntryPath
= CacheEntry
.getEntryPath();
954 auto ErrOrBuffer
= CacheEntry
.tryLoadingBuffer();
955 LLVM_DEBUG(dbgs() << "Cache " << (ErrOrBuffer
? "hit" : "miss")
956 << " '" << CacheEntryPath
<< "' for buffer "
957 << count
<< " " << ModuleIdentifier
<< "\n");
961 if (SavedObjectsDirectoryPath
.empty())
962 ProducedBinaries
[count
] = std::move(ErrOrBuffer
.get());
964 ProducedBinaryFiles
[count
] = writeGeneratedObject(
965 count
, CacheEntryPath
, SavedObjectsDirectoryPath
,
972 Context
.setDiscardValueNames(LTODiscardValueNames
);
973 Context
.enableDebugTypeODRUniquing();
974 auto DiagFileOrErr
= lto::setupOptimizationRemarks(
975 Context
, LTORemarksFilename
, LTOPassRemarksWithHotness
, count
);
976 if (!DiagFileOrErr
) {
977 errs() << "Error: " << toString(DiagFileOrErr
.takeError()) << "\n";
978 report_fatal_error("ThinLTO: Can't get an output file for the "
984 loadModuleFromBuffer(ModuleBuffer
.getMemBuffer(), Context
, false,
985 /*IsImporting*/ false);
987 // Save temps: original file.
988 saveTempBitcode(*TheModule
, SaveTempsDir
, count
, ".0.original.bc");
990 auto &ImportList
= ImportLists
[ModuleIdentifier
];
991 // Run the main process now, and generates a binary
992 auto OutputBuffer
= ProcessThinLTOModule(
993 *TheModule
, *Index
, ModuleMap
, *TMBuilder
.create(), ImportList
,
994 ExportList
, GUIDPreservedSymbols
,
995 ModuleToDefinedGVSummaries
[ModuleIdentifier
], CacheOptions
,
996 DisableCodeGen
, SaveTempsDir
, Freestanding
, OptLevel
, count
);
998 // Commit to the cache (if enabled)
999 CacheEntry
.write(*OutputBuffer
);
1001 if (SavedObjectsDirectoryPath
.empty()) {
1002 // We need to generated a memory buffer for the linker.
1003 if (!CacheEntryPath
.empty()) {
1004 // When cache is enabled, reload from the cache if possible.
1005 // Releasing the buffer from the heap and reloading it from the
1006 // cache file with mmap helps us to lower memory pressure.
1007 // The freed memory can be used for the next input file.
1008 // The final binary link will read from the VFS cache (hopefully!)
1009 // or from disk (if the memory pressure was too high).
1010 auto ReloadedBufferOrErr
= CacheEntry
.tryLoadingBuffer();
1011 if (auto EC
= ReloadedBufferOrErr
.getError()) {
1012 // On error, keep the preexisting buffer and print a diagnostic.
1013 errs() << "error: can't reload cached file '" << CacheEntryPath
1014 << "': " << EC
.message() << "\n";
1016 OutputBuffer
= std::move(*ReloadedBufferOrErr
);
1019 ProducedBinaries
[count
] = std::move(OutputBuffer
);
1022 ProducedBinaryFiles
[count
] = writeGeneratedObject(
1023 count
, CacheEntryPath
, SavedObjectsDirectoryPath
, *OutputBuffer
);
1028 pruneCache(CacheOptions
.Path
, CacheOptions
.Policy
);
1030 // If statistics were requested, print them out now.
1031 if (llvm::AreStatisticsEnabled())
1032 llvm::PrintStatistics();
1033 reportAndResetTimings();