25 #include "llvm/Config/llvm-config.h" 50 #include "llvm/Support/VCSRevision.h" 62 #if !defined(_MSC_VER) && !defined(__MINGW32__) 70 #define DEBUG_TYPE "thinlto" 92 std::string SaveTempPath = (TempDir +
llvm::Twine(count) + Suffix).str();
97 " to save optimized bitcode\n");
105 GVSummaryList, [](
const std::unique_ptr<GlobalValueSummary> &Summary) {
106 auto Linkage = Summary->linkage();
110 if (StrongDefForLinker != GVSummaryList.end())
111 return StrongDefForLinker->get();
115 GVSummaryList, [](
const std::unique_ptr<GlobalValueSummary> &Summary) {
116 auto Linkage = Summary->linkage();
120 if (FirstDefForLinker == GVSummaryList.end())
122 return FirstDefForLinker->get();
128 static void computePrevailingCopies(
132 return GVSummaryList.size() > 1;
135 for (
auto &
I : Index) {
136 if (HasMultipleCopies(
I.second.SummaryList))
137 PrevailingCopy[
I.first] =
138 getFirstDefinitionForLinker(
I.second.SummaryList);
143 generateModuleMap(std::vector<std::unique_ptr<lto::InputFile>> &Modules) {
145 for (
auto &M : Modules) {
147 "Expect unique Buffer Identifier");
148 ModuleMap[M->getName()] = M.get();
162 ThinLTODiagnosticInfo(
const Twine &DiagMsg,
170 static void verifyLoadedModule(
Module &TheModule) {
171 bool BrokenDebugInfo =
false;
174 if (BrokenDebugInfo) {
176 "Invalid debug info found, debug info will be stripped",
DS_Warning));
181 static std::unique_ptr<Module> loadModuleFromInput(
lto::InputFile *Input,
188 Lazy ?
Mod.getLazyModule(Context,
190 :
Mod.parseModule(Context);
200 verifyLoadedModule(*ModuleOrErr.
get());
201 return std::move(*ModuleOrErr);
208 auto Loader = [&](
StringRef Identifier) {
209 auto &Input = ModuleMap[Identifier];
210 return loadModuleFromInput(Input, TheModule.
getContext(),
225 verifyLoadedModule(TheModule);
229 unsigned OptLevel,
bool Freestanding,
261 for (
const auto &Sym : File.
symbols()) {
269 computeGUIDPreservedSymbols(
const StringSet<> &PreservedSymbols,
270 const Triple &TheTriple) {
272 for (
auto &
Entry : PreservedSymbols) {
278 return GUIDPreservedSymbols;
281 std::unique_ptr<MemoryBuffer> codegenModule(
Module &TheModule,
302 return std::make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer));
306 class ModuleCacheEntry {
317 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
320 if (CachePath.
empty())
342 ResolvedODR, DefinedGVSummaries);
350 StringRef getEntryPath() {
return EntryPath; }
354 if (EntryPath.empty())
355 return std::error_code();
362 *FDOrErr, EntryPath, -1,
false);
369 if (EntryPath.empty())
382 std::string ErrorMsgBuffer;
388 errs() <<
"Error: " << ErrorMsgBuffer <<
"\n";
398 static std::unique_ptr<MemoryBuffer>
406 bool DisableCodeGen,
StringRef SaveTempsDir,
407 bool Freestanding,
unsigned OptLevel,
unsigned count) {
410 bool SingleModule = (ModuleMap.
size() == 1);
413 promoteModule(TheModule, Index);
419 saveTempBitcode(TheModule, SaveTempsDir, count,
".1.promoted.bc");
424 if (!ExportList.empty() || !GUIDPreservedSymbols.
empty()) {
430 saveTempBitcode(TheModule, SaveTempsDir, count,
".2.internalized.bc");
433 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
436 saveTempBitcode(TheModule, SaveTempsDir, count,
".3.imported.bc");
439 optimizeModule(TheModule, TM, OptLevel, Freestanding, &Index);
441 saveTempBitcode(TheModule, SaveTempsDir, count,
".4.opt.bc");
443 if (DisableCodeGen) {
452 return std::make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer));
455 return codegenModule(TheModule, TM);
463 static void resolvePrevailingInIndex(
465 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
472 const auto &Prevailing = PrevailingCopy.
find(GUID);
474 if (Prevailing == PrevailingCopy.
end())
476 return Prevailing->second == S;
479 auto recordNewLinkage = [&](
StringRef ModuleIdentifier,
482 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
486 GUIDPreservedSymbols);
491 const Triple &TheTriple) {
496 TMBuilder.
MCpu =
"core2";
498 TMBuilder.
MCpu =
"yonah";
501 TMBuilder.
MCpu =
"cyclone";
503 TMBuilder.
TheTriple = std::move(TheTriple);
514 toString(InputOrError.takeError()));
516 auto TripleStr = (*InputOrError)->getTargetTriple();
517 Triple TheTriple(TripleStr);
520 initTMBuilder(TMBuilder,
Triple(TheTriple));
521 else if (TMBuilder.TheTriple != TheTriple) {
522 if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
525 initTMBuilder(TMBuilder,
Triple(TMBuilder.TheTriple.merge(TheTriple)));
528 Modules.emplace_back(std::move(*InputOrError));
532 PreservedSymbols.insert(Name);
539 PreservedSymbols.insert(Name);
554 std::string FeatureStr = Features.
getString();
556 return std::unique_ptr<TargetMachine>(
558 RelocModel,
None, CGOptLevel));
566 std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
567 std::make_unique<ModuleSummaryIndex>(
false);
568 uint64_t NextModuleId = 0;
569 for (
auto &
Mod : Modules) {
570 auto &M =
Mod->getSingleBitcodeModule();
572 M.readSummary(*CombinedIndex,
Mod->getName(), NextModuleId++)) {
575 std::move(Err),
errs(),
576 "error: can't create module summary index for buffer: ");
580 return CombinedIndex;
589 : ExportLists(ExportLists), GUIDPreservedSymbols(GUIDPreservedSymbols) {}
592 const auto &ExportList = ExportLists.
find(ModuleIdentifier);
593 return (ExportList != ExportLists.
end() &&
594 ExportList->second.count(GUID)) ||
595 GUIDPreservedSymbols.
count(GUID);
603 : PrevailingCopy(PrevailingCopy) {}
606 const auto &Prevailing = PrevailingCopy.
find(GUID);
608 if (Prevailing == PrevailingCopy.
end())
610 return Prevailing->second == S;
641 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
645 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
657 computePrevailingCopies(Index, PrevailingCopy);
661 resolvePrevailingInIndex(Index, ResolvedODR, GUIDPreservedSymbols,
665 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
670 Index,
IsExported(ExportLists, GUIDPreservedSymbols),
673 promoteModule(TheModule, Index);
682 auto ModuleMap = generateModuleMap(Modules);
690 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
693 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
705 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
713 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex,
723 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
726 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
738 ModuleIdentifier, ModuleToDefinedGVSummaries,
739 ImportLists[ModuleIdentifier], ModuleToSummariesForIndex);
756 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
759 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
770 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
772 ModuleIdentifier, ModuleToDefinedGVSummaries,
773 ImportLists[ModuleIdentifier], ModuleToSummariesForIndex);
777 ModuleToSummariesForIndex)))
779 " to save imports lists\n");
794 auto GUIDPreservedSymbols =
795 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
797 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
811 auto &ExportList = ExportLists[ModuleIdentifier];
815 if (ExportList.empty() && GUIDPreservedSymbols.empty())
819 computePrevailingCopies(Index, PrevailingCopy);
823 resolvePrevailingInIndex(Index, ResolvedODR, GUIDPreservedSymbols,
829 Index,
IsExported(ExportLists, GUIDPreservedSymbols),
832 promoteModule(TheModule, Index);
836 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
839 ModuleToDefinedGVSummaries[ModuleIdentifier]);
849 optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding,
859 auto ArchName = TMBuilder.TheTriple.getArchName();
862 Twine(count) +
"." + ArchName +
".thinlto.o");
868 if (!CacheEntryPath.
empty()) {
872 return OutputPath.
str();
876 return OutputPath.
str();
880 errs() <<
"error: can't link or copy from cached entry '" << CacheEntryPath
881 <<
"' to '" << OutputPath <<
"'\n";
889 return OutputPath.
str();
895 assert(ProducedBinaries.empty() &&
"The generator should not be reused");
896 if (SavedObjectsDirectoryPath.empty())
897 ProducedBinaries.resize(Modules.size());
904 ProducedBinaryFiles.resize(Modules.size());
911 for (
auto &
Mod : Modules) {
912 Pool.
async([&](
int count) {
917 auto TheModule = loadModuleFromInput(
Mod.get(),
Context,
false,
921 auto OutputBuffer = codegenModule(*TheModule, *TMBuilder.create());
922 if (SavedObjectsDirectoryPath.empty())
923 ProducedBinaries[count] = std::move(OutputBuffer);
925 ProducedBinaryFiles[
count] =
926 writeGeneratedObject(count,
"", *OutputBuffer);
934 auto Index = linkCombinedIndex();
937 if (!SaveTempsDir.empty()) {
938 auto SaveTempPath = SaveTempsDir +
"index.bc";
943 " to save optimized bitcode\n");
949 auto ModuleMap = generateModuleMap(Modules);
950 auto ModuleCount = Modules.size();
954 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
958 auto GUIDPreservedSymbols =
959 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
962 for (
const auto &M : Modules)
963 addUsedSymbolToPreservedGUID(*M, GUIDPreservedSymbols);
974 std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
975 std::set<GlobalValue::GUID> ExportedGUIDs;
977 for (
auto GUID : ExportedGUIDs)
978 GUIDPreservedSymbols.insert(GUID);
994 computePrevailingCopies(*
Index, PrevailingCopy);
998 resolvePrevailingInIndex(*
Index, ResolvedODR, GUIDPreservedSymbols,
1005 IsExported(ExportLists, GUIDPreservedSymbols),
1006 LocalWPDTargetsMap);
1014 for (
auto &
Module : Modules) {
1016 ExportLists[ModuleIdentifier];
1017 ImportLists[ModuleIdentifier];
1018 ResolvedODR[ModuleIdentifier];
1019 ModuleToDefinedGVSummaries[ModuleIdentifier];
1025 std::vector<int> ModulesOrdering;
1026 ModulesOrdering.resize(Modules.
size());
1027 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
1028 llvm::sort(ModulesOrdering, [&](
int LeftIndex,
int RightIndex) {
1030 Modules[LeftIndex]->getSingleBitcodeModule().getBuffer().
size();
1032 Modules[RightIndex]->getSingleBitcodeModule().getBuffer().
size();
1033 return LSize > RSize;
1039 for (
auto IndexCount : ModulesOrdering) {
1040 auto &
Mod = Modules[IndexCount];
1042 auto ModuleIdentifier =
Mod->getName();
1043 auto &ExportList = ExportLists[ModuleIdentifier];
1045 auto &DefinedGVSummaries = ModuleToDefinedGVSummaries[ModuleIdentifier];
1048 ModuleCacheEntry CacheEntry(CacheOptions.Path, *
Index, ModuleIdentifier,
1049 ImportLists[ModuleIdentifier], ExportList,
1050 ResolvedODR[ModuleIdentifier],
1051 DefinedGVSummaries, OptLevel, Freestanding,
1053 auto CacheEntryPath = CacheEntry.getEntryPath();
1056 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
1058 <<
" '" << CacheEntryPath <<
"' for buffer " 1059 << count <<
" " << ModuleIdentifier <<
"\n");
1063 if (SavedObjectsDirectoryPath.empty())
1064 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
1066 ProducedBinaryFiles[
count] = writeGeneratedObject(
1067 count, CacheEntryPath, *ErrOrBuffer.get());
1078 if (!DiagFileOrErr) {
1079 errs() <<
"Error: " <<
toString(DiagFileOrErr.takeError()) <<
"\n";
1085 auto TheModule = loadModuleFromInput(
Mod.get(),
Context,
false,
1089 saveTempBitcode(*TheModule, SaveTempsDir, count,
".0.original.bc");
1091 auto &ImportList = ImportLists[ModuleIdentifier];
1093 auto OutputBuffer = ProcessThinLTOModule(
1094 *TheModule, *
Index, ModuleMap, *TMBuilder.create(), ImportList,
1095 ExportList, GUIDPreservedSymbols,
1096 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
1097 DisableCodeGen, SaveTempsDir, Freestanding, OptLevel,
count);
1100 CacheEntry.write(*OutputBuffer);
1102 if (SavedObjectsDirectoryPath.empty()) {
1104 if (!CacheEntryPath.empty()) {
1111 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1112 if (
auto EC = ReloadedBufferOrErr.getError()) {
1114 errs() <<
"error: can't reload cached file '" << CacheEntryPath
1115 <<
"': " << EC.message() <<
"\n";
1117 OutputBuffer = std::move(*ReloadedBufferOrErr);
1120 ProducedBinaries[
count] = std::move(OutputBuffer);
1123 ProducedBinaryFiles[
count] = writeGeneratedObject(
1124 count, CacheEntryPath, *OutputBuffer);
1129 pruneCache(CacheOptions.Path, CacheOptions.Policy);
bool isOSDarwin() const
isOSDarwin - Is this a "Darwin" OS (OS X, iOS, or watchOS).
std::error_code create_directories(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create all the non-existent directories in path.
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Represents either an error or a value T.
void remove_filename(SmallVectorImpl< char > &path, Style style=Style::native)
Remove the last component from path unless it is the root dir.
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void thinLTOResolvePrevailingInModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Resolve prevailing symbol linkages in TheModule based on the information recorded in the summaries du...
CodeGenOpt::Level CGOptLevel
virtual bool addPassesToEmitFile(PassManagerBase &, raw_pwrite_stream &, raw_pwrite_stream *, CodeGenFileType, bool=true, MachineModuleInfoWrapperPass *MMIWP=nullptr)
Add passes to the specified pass manager to get the specified file emitted.
PassManagerBuilder - This class is used to set up a standard optimization sequence for languages like...
StringRef getBuffer() const
std::vector< std::unique_ptr< GlobalValueSummary > > GlobalValueSummaryList
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
This class represents lattice values for constants.
void getDefaultSubtargetFeatures(const Triple &Triple)
Adds the default features for the specified target triple.
CodeGenOpt::Level CGOptLevel
void print(const char *ProgName, raw_ostream &S, bool ShowColors=true, bool ShowKindLabel=true) const
unsigned heavyweight_hardware_concurrency()
Get the amount of currency to use for tasks requiring significant memory or other resources...
cl::opt< bool > RemarksWithHotness("lto-pass-remarks-with-hotness", cl::desc("With PGO, include profile count in optimization remarks"), cl::Hidden)
A Module instance is used to store all the information related to an LLVM module. ...
TargetMachine * createTargetMachine(StringRef TT, StringRef CPU, StringRef Features, const TargetOptions &Options, Optional< Reloc::Model > RM, Optional< CodeModel::Model > CM=None, CodeGenOpt::Level OL=CodeGenOpt::Default, bool JIT=false) const
createTargetMachine - Create a target specific machine implementation for the specified Triple...
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
This is the interface to build a ModuleSummaryIndex for a module.
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
This file provides a bitcode writing pass.
void populateThinLTOPassManager(legacy::PassManagerBase &PM)
std::error_code EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename, const std::map< std::string, GVSummaryMapTy > &ModuleToSummariesForIndex)
Emit into OutputFilename the files module ModulePath will import from.
Analysis providing profile information.
void enableDebugTypeODRUniquing()
void disableAllFunctions()
Disables all builtins.
ImmutablePass * createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA)
Create an analysis pass wrapper around a TTI object.
std::string getString() const
Returns features as a string.
iterator find(StringRef Key)
IsExported(const StringMap< FunctionImporter::ExportSetTy > &ExportLists, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols)
const StringMap< std::pair< uint64_t, ModuleHash > > & modulePaths() const
Table of modules, containing module hash and id.
const ModuleSummaryIndex * ImportSummary
The module summary index to use for importing information to the thin LTO backends, for example for the CFI and devirtualization type tests.
A raw_ostream that writes to an SmallVector or SmallString.
bool operator()(GlobalValue::GUID GUID, const GlobalValueSummary *S) const
bool is_directory(const basic_file_status &status)
Does status represent a directory?
Implementation of the target library information.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
StringRef getName() const
Get a short "name" for the module.
Error takeError()
Take ownership of the stored error.
static const Target * lookupTarget(const std::string &Triple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
void addModule(StringRef Identifier, StringRef Data)
Add given module to the code generator.
Base class for error info classes.
std::shared_future< void > async(Function &&F, Args &&... ArgList)
Asynchronous submission of a task to the pool.
void thinLTOInternalizeAndPromoteInIndex(ModuleSummaryIndex &Index, function_ref< bool(StringRef, GlobalValue::GUID)> isExported, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing)
Update the linkages in the given Index to mark exported values as external and non-exported values as...
Pass * Inliner
Inliner - Specifies the inliner to use.
const atomic_write_error Error
void setDiscardValueNames(bool Discard)
Set the Context runtime configuration to discard all value name (but GlobalValue).
void log(raw_ostream &OS) const override
Print an error message to an output stream.
ModuleSummaryIndex buildModuleSummaryIndex(const Module &M, std::function< BlockFrequencyInfo *(const Function &F)> GetBFICallback, ProfileSummaryInfo *PSI)
Direct function to compute a ModuleSummaryIndex from a given module.
void crossModuleImport(Module &Module, ModuleSummaryIndex &Index, const lto::InputFile &File)
Perform cross-module importing for the module identified by ModuleIdentifier.
cl::opt< std::string > RemarksPasses("lto-pass-remarks-filter", cl::desc("Only record optimization remarks from passes whose " "names match the given regular expression"), cl::value_desc("regex"))
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
std::string toString(Error E)
Write all error messages (if any) in E to a string.
void add(Pass *P) override
Add a pass to the queue of passes to run.
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
IsPrevailing(const DenseMap< GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVM_NODISCARD StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
std::vector< std::string > MAttrs
LLVMContext & getContext() const
Get the global data context.
static ErrorOr< std::unique_ptr< MemoryBuffer > > getOpenFile(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize, bool RequiresNullTerminator=true, bool IsVolatile=false)
Given an already-open file descriptor, read the file and return a MemoryBuffer.
void emitImports(Module &Module, StringRef OutputName, ModuleSummaryIndex &Index, const lto::InputFile &File)
Compute and emit the imported files for module at ModulePath.
std::unordered_set< GlobalValue::GUID > ExportSetTy
The set contains an entry for every global value the module exports.
Tagged union holding either a T or a Error.
Interface for custom diagnostic printing.
This header defines classes/functions to handle pass execution timing information with interfaces for...
const StringMap< FunctionImporter::ExportSetTy > & ExportLists
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
std::string writeGeneratedObject(int count, StringRef CacheEntryPath, const MemoryBuffer &OutputBuffer)
Write temporary object file to SavedObjectDirectoryPath, write symlink to Cache directory if needed...
StringRef str() const
Explicit conversion to StringRef.
void run()
Process all the modules that were added to the code generator in parallel.
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
Pass * createObjCARCContractPass()
unsigned OptLevel
The Optimization Level - Specify the basic optimization level.
bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
LLVM_NODISCARD size_t size() const
size - Get the string size.
A ThreadPool for asynchronous parallel execution on a defined number of threads.
void reportAndResetTimings(raw_ostream *OutStream=nullptr)
If -time-passes has been specified, report the timings immediately and then reset the timers to zero...
Class to hold module path string table and global value map, and encapsulate methods for operating on...
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
iterator find(const_arg_type_t< KeyT > Val)
PassManager manages ModulePassManagers.
const DenseSet< GlobalValue::GUID > & GUIDPreservedSymbols
std::error_code copy_file(const Twine &From, const Twine &To)
Copy the contents of From to To.
void crossReferenceSymbol(StringRef Name)
Adds to a list of all global symbols that are cross-referenced between ThinLTO files.
initializer< Ty > init(const Ty &Val)
This is the base abstract class for diagnostic reporting in the backend.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
bool renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index, SetVector< GlobalValue *> *GlobalsToImport=nullptr)
Perform in-place global value handling on the given Module for exported local functions renamed and p...
void gatherImportedSummariesForModule(StringRef ModulePath, const StringMap< GVSummaryMapTy > &ModuleToDefinedGVSummaries, const FunctionImporter::ImportMapTy &ImportList, std::map< std::string, GVSummaryMapTy > &ModuleToSummariesForIndex)
Compute the set of summaries needed for a ThinLTO backend compilation of ModulePath.
void optimize(Module &Module)
Perform post-importing ThinLTO optimizations.
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
void runWholeProgramDevirtOnIndex(ModuleSummaryIndex &Summary, std::set< GlobalValue::GUID > &ExportedGUIDs, std::map< ValueInfo, std::vector< VTableSlotSummary >> &LocalWPDTargetsMap)
Perform index-based whole program devirtualization on the Summary index.
This is an important class for using LLVM in a threaded context.
Instrumentation for Order File
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
TargetLibraryInfoImpl * LibraryInfo
LibraryInfo - Specifies information about the runtime library for the optimizer.
Helper to gather options relevant to the target machine creation.
void internalize(Module &Module, ModuleSummaryIndex &Index, const lto::InputFile &File)
Perform internalization.
std::pair< iterator, bool > insert(const ValueT &V)
TargetIRAnalysis getTargetIRAnalysis()
Get a TargetIRAnalysis appropriate for the target.
void WriteBitcodeToFile(const Module &M, raw_ostream &Out, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the specified raw output stream.
bool isWeakForLinker() const
const Triple & getTargetTriple() const
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
const ModuleHash & getModuleHash(const StringRef ModPath) const
Get the module SHA1 hash recorded for the given module path.
void thinLTOResolvePrevailingInIndex(ModuleSummaryIndex &Index, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, function_ref< void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)> recordNewLinkage, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols)
Resolve linkage for prevailing symbols in the Index.
auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
std::error_code create_hard_link(const Twine &to, const Twine &from)
Create a hard link from from to to, or return an error.
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
Function and variable summary information to aid decisions and implementation of importing.
static void write(bool isBE, void *P, T V)
void gatherImportedSummariesForModule(Module &Module, ModuleSummaryIndex &Index, std::map< std::string, GVSummaryMapTy > &ModuleToSummariesForIndex, const lto::InputFile &File)
Compute the list of summaries needed for importing into module.
void consumeError(Error Err)
Consume a Error without doing anything.
bool pruneCache(StringRef Path, CachePruningPolicy Policy)
Peform pruning using the supplied policy, returns true if pruning occurred, i.e.
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Force files Atime to be updated on access. Only makes a difference on windows.
Triple - Helper class for working with autoconf configuration names.
void sort(IteratorTy Start, IteratorTy End)
void computeSyntheticCounts(ModuleSummaryIndex &Index)
Compute synthetic function entry counts.
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
void computeLTOCacheKey(SmallString< 40 > &Key, const lto::Config &Conf, const ModuleSummaryIndex &Index, StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList, const FunctionImporter::ExportSetTy &ExportList, const std::map< GlobalValue::GUID, GlobalValue::LinkageTypes > &ResolvedODR, const GVSummaryMapTy &DefinedGlobals, const std::set< GlobalValue::GUID > &CfiFunctionDefs={}, const std::set< GlobalValue::GUID > &CfiFunctionDecls={})
Computes a unique hash for the Module considering the current list of export/import and other global ...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
static bool isAvailableExternallyLinkage(LinkageTypes Linkage)
Optional< Reloc::Model > RelocModel
Expected< file_t > openNativeFileForRead(const Twine &Name, OpenFlags Flags=OF_None, SmallVectorImpl< char > *RealPath=nullptr)
Opens the file with the given name in a read-only mode, returning its open file descriptor.
reference get()
Returns a reference to the stored T value.
std::error_code closeFile(file_t &F)
Close the file object.
This interface provides simple read-only access to a block of memory, and provides simple methods for...
bool operator()(StringRef ModuleIdentifier, GlobalValue::GUID GUID) const
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
The access may modify the value stored in memory.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Target - Wrapper for Target specific information.
Manages the enabling and disabling of subtarget specific features.
void promote(Module &Module, ModuleSummaryIndex &Index, const lto::InputFile &File)
Perform promotion and renaming of exported internal functions, and additionally resolve weak and link...
LinkageTypes
An enumeration for the kinds of linkage for global values.
void WriteIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const std::map< std::string, GVSummaryMapTy > *ModuleToSummariesForIndex=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
std::unique_ptr< ModuleSummaryIndex > linkCombinedIndex()
Produce the combined summary index from all the bitcode files: "thin-link".
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
static void computeDeadSymbolsInIndex(ModuleSummaryIndex &Index, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols)
bool verifyModule(const Module &M, raw_ostream *OS=nullptr, bool *BrokenDebugInfo=nullptr)
Check a module for errors.
Expected< bool > importFunctions(Module &M, const ImportMapTy &ImportList)
Import functions in Module M based on the supplied import list.
std::unique_ptr< TargetMachine > create() const
void ComputeCrossModuleImport(const ModuleSummaryIndex &Index, const StringMap< GVSummaryMapTy > &ModuleToDefinedGVSummaries, StringMap< FunctionImporter::ImportMapTy > &ImportLists, StringMap< FunctionImporter::ExportSetTy > &ExportLists)
Compute all the imports and exports for every module in the Index.
cl::opt< bool > LTODiscardValueNames("lto-discard-value-names", cl::desc("Strip names from Value during LTO (other than GlobalValue)."), cl::init(false), cl::Hidden)
void updateIndexWPDForExports(ModuleSummaryIndex &Summary, function_ref< bool(StringRef, GlobalValue::GUID)> isExported, std::map< ValueInfo, std::vector< VTableSlotSummary >> &LocalWPDTargetsMap)
Call after cross-module importing to update the recorded single impl devirt target names for any loca...
A raw_ostream that writes to a file descriptor.
Linkage
Describes symbol linkage.
void thinLTOInternalizeModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Internalize TheModule based on the information recorded in the summaries during global summary-based ...
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
void preserveSymbol(StringRef Name)
Adds to a list of all global symbols that must exist in the final generated code. ...
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
const DenseMap< GlobalValue::GUID, const GlobalValueSummary * > & PrevailingCopy
void computeDeadSymbolsWithConstProp(ModuleSummaryIndex &Index, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols, function_ref< PrevailingType(GlobalValue::GUID)> isPrevailing, bool ImportEnabled)
Compute dead symbols and run constant propagation in combined index after that.
void PrintStatistics()
Print statistics to the file returned by CreateInfoOutputFile().
Optional< Reloc::Model > RelocModel
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void collectDefinedGVSummariesPerModule(Map &ModuleToDefinedGVSummaries) const
Collect for each module the list of Summaries it defines (GUID -> Summary).
llvm::Error writeFileAtomically(StringRef TempPathModel, StringRef FinalPath, StringRef Buffer)
Creates a unique file with name according to the given TempPathModel, writes content of Buffer to the...
Expected< std::unique_ptr< ToolOutputFile > > setupOptimizationRemarks(LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses, StringRef RemarksFormat, bool RemarksWithHotness, int Count=-1)
Setup optimization remarks.
A raw_ostream that writes to an std::string.
cl::opt< std::string > RemarksFormat("lto-pass-remarks-format", cl::desc("The format used for serializing remarks (default: YAML)"), cl::value_desc("format"), cl::init("yaml"))
Pass * createFunctionInliningPass()
createFunctionInliningPass - Return a new pass object that uses a heuristic to inline direct function...
The function importer is automatically importing function from other modules based on the provided su...
cl::opt< std::string > RemarksFilename("lto-pass-remarks-output", cl::desc("Output filename for pass remarks"), cl::value_desc("filename"))
Lightweight error class with error context and mandatory checking.
StringSet - A wrapper for StringMap that provides set-like functionality.
Error handleErrors(Error E, HandlerTs &&... Hs)
Pass the ErrorInfo(s) contained in E to their respective handlers.
Primary interface to the complete machine description for the target machine.
StringRef - Represent a constant reference to a string, i.e.
bool Freestanding
Flag to indicate that the optimizer should not assume builtins are present on the target...
bool exists(const basic_file_status &status)
Does file exist?
bool AreStatisticsEnabled()
Check if statistics are enabled.
std::error_code errorToErrorCode(Error Err)
Helper for converting an ECError to a std::error_code.
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...