26 #include "llvm/Config/llvm-config.h" 51 #include "llvm/Support/VCSRevision.h" 63 #if !defined(_MSC_VER) && !defined(__MINGW32__) 71 #define DEBUG_TYPE "thinlto" 93 std::string SaveTempPath = (TempDir +
llvm::Twine(count) + Suffix).str();
98 " to save optimized bitcode\n");
106 GVSummaryList, [](
const std::unique_ptr<GlobalValueSummary> &Summary) {
107 auto Linkage = Summary->linkage();
111 if (StrongDefForLinker != GVSummaryList.end())
112 return StrongDefForLinker->get();
116 GVSummaryList, [](
const std::unique_ptr<GlobalValueSummary> &Summary) {
117 auto Linkage = Summary->linkage();
121 if (FirstDefForLinker == GVSummaryList.end())
123 return FirstDefForLinker->get();
129 static void computePrevailingCopies(
133 return GVSummaryList.size() > 1;
136 for (
auto &
I : Index) {
137 if (HasMultipleCopies(
I.second.SummaryList))
138 PrevailingCopy[
I.first] =
139 getFirstDefinitionForLinker(
I.second.SummaryList);
144 generateModuleMap(std::vector<std::unique_ptr<lto::InputFile>> &Modules) {
146 for (
auto &M : Modules) {
148 "Expect unique Buffer Identifier");
149 ModuleMap[M->getName()] = M.get();
163 ThinLTODiagnosticInfo(
const Twine &DiagMsg,
171 static void verifyLoadedModule(
Module &TheModule) {
172 bool BrokenDebugInfo =
false;
175 if (BrokenDebugInfo) {
177 "Invalid debug info found, debug info will be stripped",
DS_Warning));
182 static std::unique_ptr<Module> loadModuleFromInput(
lto::InputFile *Input,
189 Lazy ?
Mod.getLazyModule(Context,
191 :
Mod.parseModule(Context);
201 verifyLoadedModule(*ModuleOrErr.
get());
202 return std::move(*ModuleOrErr);
209 auto Loader = [&](
StringRef Identifier) {
210 auto &Input = ModuleMap[Identifier];
211 return loadModuleFromInput(Input, TheModule.
getContext(),
226 verifyLoadedModule(TheModule);
230 unsigned OptLevel,
bool Freestanding,
262 for (
const auto &Sym : File.
symbols()) {
270 computeGUIDPreservedSymbols(
const StringSet<> &PreservedSymbols,
271 const Triple &TheTriple) {
273 for (
auto &
Entry : PreservedSymbols) {
279 return GUIDPreservedSymbols;
282 std::unique_ptr<MemoryBuffer> codegenModule(
Module &TheModule,
303 return std::make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer));
307 class ModuleCacheEntry {
318 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
321 if (CachePath.
empty())
343 ResolvedODR, DefinedGVSummaries);
351 StringRef getEntryPath() {
return EntryPath; }
355 if (EntryPath.empty())
356 return std::error_code();
363 *FDOrErr, EntryPath, -1,
false);
370 if (EntryPath.empty())
383 std::string ErrorMsgBuffer;
389 errs() <<
"Error: " << ErrorMsgBuffer <<
"\n";
399 static std::unique_ptr<MemoryBuffer>
407 bool DisableCodeGen,
StringRef SaveTempsDir,
408 bool Freestanding,
unsigned OptLevel,
unsigned count) {
411 bool SingleModule = (ModuleMap.
size() == 1);
414 promoteModule(TheModule, Index);
420 saveTempBitcode(TheModule, SaveTempsDir, count,
".1.promoted.bc");
425 if (!ExportList.
empty() || !GUIDPreservedSymbols.
empty()) {
431 saveTempBitcode(TheModule, SaveTempsDir, count,
".2.internalized.bc");
434 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
437 saveTempBitcode(TheModule, SaveTempsDir, count,
".3.imported.bc");
440 optimizeModule(TheModule, TM, OptLevel, Freestanding, &Index);
442 saveTempBitcode(TheModule, SaveTempsDir, count,
".4.opt.bc");
444 if (DisableCodeGen) {
453 return std::make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer));
456 return codegenModule(TheModule, TM);
464 static void resolvePrevailingInIndex(
466 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
473 const auto &Prevailing = PrevailingCopy.
find(GUID);
475 if (Prevailing == PrevailingCopy.
end())
477 return Prevailing->second == S;
480 auto recordNewLinkage = [&](
StringRef ModuleIdentifier,
483 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
487 GUIDPreservedSymbols);
492 const Triple &TheTriple) {
497 TMBuilder.
MCpu =
"core2";
499 TMBuilder.
MCpu =
"yonah";
502 TMBuilder.
MCpu =
"cyclone";
504 TMBuilder.
TheTriple = std::move(TheTriple);
515 toString(InputOrError.takeError()));
517 auto TripleStr = (*InputOrError)->getTargetTriple();
518 Triple TheTriple(TripleStr);
521 initTMBuilder(TMBuilder,
Triple(TheTriple));
522 else if (TMBuilder.TheTriple != TheTriple) {
523 if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
526 initTMBuilder(TMBuilder,
Triple(TMBuilder.TheTriple.merge(TheTriple)));
529 Modules.emplace_back(std::move(*InputOrError));
533 PreservedSymbols.insert(Name);
540 PreservedSymbols.insert(Name);
555 std::string FeatureStr = Features.
getString();
557 return std::unique_ptr<TargetMachine>(
559 RelocModel,
None, CGOptLevel));
567 std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
568 std::make_unique<ModuleSummaryIndex>(
false);
569 uint64_t NextModuleId = 0;
570 for (
auto &
Mod : Modules) {
571 auto &M =
Mod->getSingleBitcodeModule();
573 M.readSummary(*CombinedIndex,
Mod->getName(), NextModuleId++)) {
576 std::move(Err),
errs(),
577 "error: can't create module summary index for buffer: ");
581 return CombinedIndex;
591 : ExportLists(ExportLists), GUIDPreservedSymbols(GUIDPreservedSymbols) {}
594 const auto &ExportList = ExportLists.
find(ModuleIdentifier);
595 return (ExportList != ExportLists.
end() && ExportList->second.count(VI)) ||
600 struct IsPrevailing {
604 : PrevailingCopy(PrevailingCopy) {}
607 const auto &Prevailing = PrevailingCopy.
find(GUID);
609 if (Prevailing == PrevailingCopy.
end())
611 return Prevailing->second == S;
643 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
647 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
659 computePrevailingCopies(Index, PrevailingCopy);
663 resolvePrevailingInIndex(Index, ResolvedODR, GUIDPreservedSymbols,
667 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
672 Index, IsExported(ExportLists, GUIDPreservedSymbols),
673 IsPrevailing(PrevailingCopy));
675 promoteModule(TheModule, Index);
684 auto ModuleMap = generateModuleMap(Modules);
692 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
695 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
707 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
715 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex,
725 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
728 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
740 ModuleIdentifier, ModuleToDefinedGVSummaries,
741 ImportLists[ModuleIdentifier], ModuleToSummariesForIndex);
758 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
761 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
772 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
774 ModuleIdentifier, ModuleToDefinedGVSummaries,
775 ImportLists[ModuleIdentifier], ModuleToSummariesForIndex);
779 ModuleToSummariesForIndex)))
781 " to save imports lists\n");
796 auto GUIDPreservedSymbols =
797 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
799 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
813 auto &ExportList = ExportLists[ModuleIdentifier];
817 if (ExportList.empty() && GUIDPreservedSymbols.empty())
821 computePrevailingCopies(Index, PrevailingCopy);
825 resolvePrevailingInIndex(Index, ResolvedODR, GUIDPreservedSymbols,
831 Index, IsExported(ExportLists, GUIDPreservedSymbols),
832 IsPrevailing(PrevailingCopy));
834 promoteModule(TheModule, Index);
838 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
841 ModuleToDefinedGVSummaries[ModuleIdentifier]);
851 optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding,
861 auto ArchName = TMBuilder.TheTriple.getArchName();
864 Twine(count) +
"." + ArchName +
".thinlto.o");
870 if (!CacheEntryPath.
empty()) {
874 return OutputPath.
str();
878 return OutputPath.
str();
882 errs() <<
"error: can't link or copy from cached entry '" << CacheEntryPath
883 <<
"' to '" << OutputPath <<
"'\n";
891 return OutputPath.
str();
897 assert(ProducedBinaries.empty() &&
"The generator should not be reused");
898 if (SavedObjectsDirectoryPath.empty())
899 ProducedBinaries.resize(Modules.size());
906 ProducedBinaryFiles.resize(Modules.size());
913 for (
auto &
Mod : Modules) {
914 Pool.
async([&](
int count) {
919 auto TheModule = loadModuleFromInput(
Mod.get(),
Context,
false,
923 auto OutputBuffer = codegenModule(*TheModule, *TMBuilder.create());
924 if (SavedObjectsDirectoryPath.empty())
925 ProducedBinaries[count] = std::move(OutputBuffer);
927 ProducedBinaryFiles[
count] =
928 writeGeneratedObject(count,
"", *OutputBuffer);
936 auto Index = linkCombinedIndex();
939 if (!SaveTempsDir.empty()) {
940 auto SaveTempPath = SaveTempsDir +
"index.bc";
945 " to save optimized bitcode\n");
951 auto ModuleMap = generateModuleMap(Modules);
952 auto ModuleCount = Modules.size();
956 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
960 auto GUIDPreservedSymbols =
961 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
964 for (
const auto &M : Modules)
965 addUsedSymbolToPreservedGUID(*M, GUIDPreservedSymbols);
976 std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
977 std::set<GlobalValue::GUID> ExportedGUIDs;
979 for (
auto GUID : ExportedGUIDs)
980 GUIDPreservedSymbols.insert(GUID);
996 computePrevailingCopies(*
Index, PrevailingCopy);
1000 resolvePrevailingInIndex(*
Index, ResolvedODR, GUIDPreservedSymbols,
1007 IsExported(ExportLists, GUIDPreservedSymbols),
1008 LocalWPDTargetsMap);
1010 *
Index, IsExported(ExportLists, GUIDPreservedSymbols),
1011 IsPrevailing(PrevailingCopy));
1016 for (
auto &
Module : Modules) {
1018 ExportLists[ModuleIdentifier];
1019 ImportLists[ModuleIdentifier];
1020 ResolvedODR[ModuleIdentifier];
1021 ModuleToDefinedGVSummaries[ModuleIdentifier];
1027 std::vector<int> ModulesOrdering;
1028 ModulesOrdering.resize(Modules.
size());
1029 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
1030 llvm::sort(ModulesOrdering, [&](
int LeftIndex,
int RightIndex) {
1032 Modules[LeftIndex]->getSingleBitcodeModule().getBuffer().
size();
1034 Modules[RightIndex]->getSingleBitcodeModule().getBuffer().
size();
1035 return LSize > RSize;
1041 for (
auto IndexCount : ModulesOrdering) {
1042 auto &
Mod = Modules[IndexCount];
1044 auto ModuleIdentifier =
Mod->getName();
1045 auto &ExportList = ExportLists[ModuleIdentifier];
1047 auto &DefinedGVSummaries = ModuleToDefinedGVSummaries[ModuleIdentifier];
1050 ModuleCacheEntry CacheEntry(CacheOptions.Path, *
Index, ModuleIdentifier,
1051 ImportLists[ModuleIdentifier], ExportList,
1052 ResolvedODR[ModuleIdentifier],
1053 DefinedGVSummaries, OptLevel, Freestanding,
1055 auto CacheEntryPath = CacheEntry.getEntryPath();
1058 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
1060 <<
" '" << CacheEntryPath <<
"' for buffer " 1061 << count <<
" " << ModuleIdentifier <<
"\n");
1065 if (SavedObjectsDirectoryPath.empty())
1066 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
1068 ProducedBinaryFiles[
count] = writeGeneratedObject(
1069 count, CacheEntryPath, *ErrOrBuffer.get());
1080 if (!DiagFileOrErr) {
1081 errs() <<
"Error: " <<
toString(DiagFileOrErr.takeError()) <<
"\n";
1087 auto TheModule = loadModuleFromInput(
Mod.get(),
Context,
false,
1091 saveTempBitcode(*TheModule, SaveTempsDir, count,
".0.original.bc");
1093 auto &ImportList = ImportLists[ModuleIdentifier];
1095 auto OutputBuffer = ProcessThinLTOModule(
1096 *TheModule, *
Index, ModuleMap, *TMBuilder.create(), ImportList,
1097 ExportList, GUIDPreservedSymbols,
1098 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
1099 DisableCodeGen, SaveTempsDir, Freestanding, OptLevel,
count);
1102 CacheEntry.write(*OutputBuffer);
1104 if (SavedObjectsDirectoryPath.empty()) {
1106 if (!CacheEntryPath.empty()) {
1113 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1114 if (
auto EC = ReloadedBufferOrErr.getError()) {
1116 errs() <<
"error: can't reload cached file '" << CacheEntryPath
1117 <<
"': " << EC.message() <<
"\n";
1119 OutputBuffer = std::move(*ReloadedBufferOrErr);
1122 ProducedBinaries[
count] = std::move(OutputBuffer);
1125 ProducedBinaryFiles[
count] = writeGeneratedObject(
1126 count, CacheEntryPath, *OutputBuffer);
1131 pruneCache(CacheOptions.Path, CacheOptions.Policy);
bool isOSDarwin() const
isOSDarwin - Is this a "Darwin" OS (macOS, iOS, tvOS 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...
void thinLTOInternalizeAndPromoteInIndex(ModuleSummaryIndex &Index, function_ref< bool(StringRef, ValueInfo)> 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...
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.
Implements a dense probed hash-table based set.
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)
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 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.
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.
GlobalValue::GUID getGUID() const
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.
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.
void updateIndexWPDForExports(ModuleSummaryIndex &Summary, function_ref< bool(StringRef, ValueInfo)> 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...
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.
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...
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.
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)
Struct that holds a reference to a particular GUID in a global value summary.
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...
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)
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.
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...