26 #include "llvm/Config/llvm-config.h" 49 #include "llvm/Support/VCSRevision.h" 60 #if !defined(_MSC_VER) && !defined(__MINGW32__) 68 #define DEBUG_TYPE "thinlto" 88 std::string SaveTempPath = (TempDir +
llvm::Twine(count) + Suffix).str();
93 " to save optimized bitcode\n");
101 GVSummaryList, [](
const std::unique_ptr<GlobalValueSummary> &Summary) {
102 auto Linkage = Summary->linkage();
106 if (StrongDefForLinker != GVSummaryList.end())
107 return StrongDefForLinker->get();
111 GVSummaryList, [](
const std::unique_ptr<GlobalValueSummary> &Summary) {
112 auto Linkage = Summary->linkage();
116 if (FirstDefForLinker == GVSummaryList.end())
118 return FirstDefForLinker->get();
124 static void computePrevailingCopies(
128 return GVSummaryList.size() > 1;
131 for (
auto &
I : Index) {
132 if (HasMultipleCopies(
I.second.SummaryList))
133 PrevailingCopy[
I.first] =
134 getFirstDefinitionForLinker(
I.second.SummaryList);
139 generateModuleMap(
const std::vector<ThinLTOBuffer> &Modules) {
141 for (
auto &ModuleBuffer : Modules) {
142 assert(ModuleMap.
find(ModuleBuffer.getBufferIdentifier()) ==
144 "Expect unique Buffer Identifier");
145 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer.getMemBuffer();
159 ThinLTODiagnosticInfo(
const Twine &DiagMsg,
167 static void verifyLoadedModule(
Module &TheModule) {
168 bool BrokenDebugInfo =
false;
171 if (BrokenDebugInfo) {
173 "Invalid debug info found, debug info will be stripped",
DS_Warning));
178 static std::unique_ptr<Module>
180 bool Lazy,
bool IsImporting) {
196 verifyLoadedModule(*ModuleOrErr.
get());
197 return std::move(ModuleOrErr.
get());
204 auto Loader = [&](
StringRef Identifier) {
205 return loadModuleFromBuffer(ModuleMap[Identifier], TheModule.
getContext(),
220 verifyLoadedModule(TheModule);
224 unsigned OptLevel,
bool Freestanding) {
253 computeGUIDPreservedSymbols(
const StringSet<> &PreservedSymbols,
254 const Triple &TheTriple) {
256 for (
auto &Entry : PreservedSymbols) {
262 return GUIDPreservedSymbols;
265 std::unique_ptr<MemoryBuffer> codegenModule(
Module &TheModule,
286 return make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer));
290 class ModuleCacheEntry {
301 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
304 if (CachePath.
empty())
326 ResolvedODR, DefinedGVSummaries);
334 StringRef getEntryPath() {
return EntryPath; }
338 if (EntryPath.empty())
339 return std::error_code();
356 if (EntryPath.empty())
368 errs() <<
"Error: " << EC.message() <<
"\n";
382 static std::unique_ptr<MemoryBuffer>
390 bool DisableCodeGen,
StringRef SaveTempsDir,
391 bool Freestanding,
unsigned OptLevel,
unsigned count) {
394 bool SingleModule = (ModuleMap.
size() == 1);
397 promoteModule(TheModule, Index);
403 saveTempBitcode(TheModule, SaveTempsDir, count,
".1.promoted.bc");
408 if (!ExportList.empty() || !GUIDPreservedSymbols.
empty()) {
414 saveTempBitcode(TheModule, SaveTempsDir, count,
".2.internalized.bc");
417 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
420 saveTempBitcode(TheModule, SaveTempsDir, count,
".3.imported.bc");
423 optimizeModule(TheModule, TM, OptLevel, Freestanding);
425 saveTempBitcode(TheModule, SaveTempsDir, count,
".4.opt.bc");
427 if (DisableCodeGen) {
436 return make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer));
439 return codegenModule(TheModule, TM);
447 static void resolvePrevailingInIndex(
449 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
453 computePrevailingCopies(Index, PrevailingCopy);
456 const auto &Prevailing = PrevailingCopy.
find(GUID);
458 if (Prevailing == PrevailingCopy.
end())
460 return Prevailing->second == S;
463 auto recordNewLinkage = [&](
StringRef ModuleIdentifier,
466 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
474 const Triple &TheTriple) {
479 TMBuilder.
MCpu =
"core2";
481 TMBuilder.
MCpu =
"yonah";
483 TMBuilder.
MCpu =
"cyclone";
485 TMBuilder.
TheTriple = std::move(TheTriple);
498 TripleStr = *TripleOrErr;
500 Triple TheTriple(TripleStr);
503 initTMBuilder(TMBuilder,
Triple(TheTriple));
504 else if (TMBuilder.TheTriple != TheTriple) {
505 if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
508 initTMBuilder(TMBuilder,
Triple(TMBuilder.TheTriple.merge(TheTriple)));
511 Modules.push_back(Buffer);
515 PreservedSymbols.insert(Name);
522 PreservedSymbols.insert(Name);
537 std::string FeatureStr = Features.
getString();
539 return std::unique_ptr<TargetMachine>(
541 RelocModel,
None, CGOptLevel));
549 std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
550 llvm::make_unique<ModuleSummaryIndex>(
false);
551 uint64_t NextModuleId = 0;
552 for (
auto &ModuleBuffer : Modules) {
554 *CombinedIndex, NextModuleId++)) {
557 std::move(Err),
errs(),
558 "error: can't create module summary index for buffer: ");
562 return CombinedIndex;
570 const auto &ExportList = ExportLists.
find(ModuleIdentifier);
571 return (ExportList != ExportLists.
end() &&
572 ExportList->second.count(GUID)) ||
573 GUIDPreservedSymbols.
count(GUID);
606 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
620 resolvePrevailingInIndex(Index, ResolvedODR);
623 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
629 promoteModule(TheModule, Index);
637 auto ModuleMap = generateModuleMap(Modules);
645 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
658 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
666 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
675 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
688 ModuleIdentifier, ModuleToDefinedGVSummaries,
689 ImportLists[ModuleIdentifier], ModuleToSummariesForIndex);
705 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
717 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
719 ModuleIdentifier, ModuleToDefinedGVSummaries,
720 ImportLists[ModuleIdentifier], ModuleToSummariesForIndex);
724 ModuleToSummariesForIndex)))
726 " to save imports lists\n");
739 auto GUIDPreservedSymbols =
740 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
754 auto &ExportList = ExportLists[ModuleIdentifier];
758 if (ExportList.empty() && GUIDPreservedSymbols.empty())
764 ModuleToDefinedGVSummaries[ModuleIdentifier]);
774 optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding);
790 if (!CacheEntryPath.
empty()) {
794 return OutputPath.
str();
798 return OutputPath.
str();
802 errs() <<
"error: can't link or copy from cached entry '" << CacheEntryPath
803 <<
"' to '" << OutputPath <<
"'\n";
811 return OutputPath.
str();
817 assert(ProducedBinaries.empty() &&
"The generator should not be reused");
818 if (SavedObjectsDirectoryPath.empty())
819 ProducedBinaries.resize(Modules.size());
826 ProducedBinaryFiles.resize(Modules.size());
833 for (
auto &ModuleBuffer : Modules) {
834 Pool.
async([&](
int count) {
840 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(),
Context,
false,
844 auto OutputBuffer = codegenModule(*TheModule, *TMBuilder.create());
845 if (SavedObjectsDirectoryPath.empty())
846 ProducedBinaries[count] = std::move(OutputBuffer);
849 count,
"", SavedObjectsDirectoryPath, *OutputBuffer);
857 auto Index = linkCombinedIndex();
860 if (!SaveTempsDir.empty()) {
861 auto SaveTempPath = SaveTempsDir +
"index.bc";
866 " to save optimized bitcode\n");
872 auto ModuleMap = generateModuleMap(Modules);
873 auto ModuleCount = Modules.size();
877 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
881 auto GUIDPreservedSymbols =
882 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
905 resolvePrevailingInIndex(*
Index, ResolvedODR);
915 for (
auto &
Module : Modules) {
916 auto ModuleIdentifier =
Module.getBufferIdentifier();
917 ExportLists[ModuleIdentifier];
918 ImportLists[ModuleIdentifier];
919 ResolvedODR[ModuleIdentifier];
920 ModuleToDefinedGVSummaries[ModuleIdentifier];
926 std::vector<int> ModulesOrdering;
927 ModulesOrdering.resize(Modules.
size());
928 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
929 llvm::sort(ModulesOrdering, [&](
int LeftIndex,
int RightIndex) {
930 auto LSize = Modules[LeftIndex].getBuffer().
size();
931 auto RSize = Modules[RightIndex].getBuffer().
size();
932 return LSize > RSize;
938 for (
auto IndexCount : ModulesOrdering) {
939 auto &ModuleBuffer = Modules[IndexCount];
941 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
942 auto &ExportList = ExportLists[ModuleIdentifier];
944 auto &DefinedGVSummaries = ModuleToDefinedGVSummaries[ModuleIdentifier];
947 ModuleCacheEntry CacheEntry(CacheOptions.Path, *
Index, ModuleIdentifier,
948 ImportLists[ModuleIdentifier], ExportList,
949 ResolvedODR[ModuleIdentifier],
950 DefinedGVSummaries, OptLevel, Freestanding,
952 auto CacheEntryPath = CacheEntry.getEntryPath();
955 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
957 <<
" '" << CacheEntryPath <<
"' for buffer " 958 << count <<
" " << ModuleIdentifier <<
"\n");
962 if (SavedObjectsDirectoryPath.empty())
963 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
966 count, CacheEntryPath, SavedObjectsDirectoryPath,
977 if (!DiagFileOrErr) {
978 errs() <<
"Error: " <<
toString(DiagFileOrErr.takeError()) <<
"\n";
985 loadModuleFromBuffer(ModuleBuffer.getMemBuffer(),
Context,
false,
989 saveTempBitcode(*TheModule, SaveTempsDir, count,
".0.original.bc");
991 auto &ImportList = ImportLists[ModuleIdentifier];
993 auto OutputBuffer = ProcessThinLTOModule(
994 *TheModule, *
Index, ModuleMap, *TMBuilder.create(), ImportList,
995 ExportList, GUIDPreservedSymbols,
996 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
997 DisableCodeGen, SaveTempsDir, Freestanding, OptLevel,
count);
1000 CacheEntry.write(*OutputBuffer);
1002 if (SavedObjectsDirectoryPath.empty()) {
1004 if (!CacheEntryPath.empty()) {
1011 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1012 if (
auto EC = ReloadedBufferOrErr.getError()) {
1014 errs() <<
"error: can't reload cached file '" << CacheEntryPath
1015 <<
"': " << EC.message() <<
"\n";
1017 OutputBuffer = std::move(*ReloadedBufferOrErr);
1020 ProducedBinaries[
count] = std::move(OutputBuffer);
1024 count, CacheEntryPath, SavedObjectsDirectoryPath, *OutputBuffer);
1029 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.
void collectDefinedGVSummariesPerModule(StringMap< GVSummaryMapTy > &ModuleToDefinedGVSummaries) const
Collect for each module the list of Summaries it defines (GUID -> Summary).
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.
Expected< std::unique_ptr< ToolOutputFile > > setupOptimizationRemarks(LLVMContext &Context, StringRef LTORemarksFilename, bool LTOPassRemarksWithHotness, int Count=-1)
Setup optimization remarks.
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
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
std::error_code openFileForRead(const Twine &Name, int &ResultFD, 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.
void print(const char *ProgName, raw_ostream &S, bool ShowColors=true, bool ShowKindLabel=true) const
void promote(Module &Module, ModuleSummaryIndex &Index)
Perform promotion and renaming of exported internal functions, and additionally resolve weak and link...
cl::opt< std::string > LTORemarksFilename("lto-pass-remarks-output", cl::desc("Output filename for pass remarks"), cl::value_desc("filename"))
unsigned heavyweight_hardware_concurrency()
Get the amount of currency to use for tasks requiring significant memory or other resources...
A Module instance is used to store all the information related to an LLVM module. ...
Expected< std::unique_ptr< Module > > getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false)
Read the header of the specified bitcode buffer and prepare for lazy deserialization of function bodi...
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...
std::error_code createUniqueFile(const Twine &Model, int &ResultFD, SmallVectorImpl< char > &ResultPath, unsigned Mode=all_read|all_write)
Create a uniquely named file.
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.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
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.
const FeatureBitset Features
iterator find(StringRef Key)
const StringMap< std::pair< uint64_t, ModuleHash > > & modulePaths() const
Table of modules, containing module hash and id.
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...
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 reportAndResetTimings()
If -time-passes has been specified, report the timings immediately and then reset the timers to zero...
Pass * Inliner
Inliner - Specifies the inliner to use.
void gatherImportedSummariesForModule(Module &Module, ModuleSummaryIndex &Index, std::map< std::string, GVSummaryMapTy > &ModuleToSummariesForIndex)
Compute the list of summaries needed for importing into module.
void setDiscardValueNames(bool Discard)
Set the Context runtime configuration to discard all value name (but GlobalValue).
ModuleSummaryIndex buildModuleSummaryIndex(const Module &M, std::function< BlockFrequencyInfo *(const Function &F)> GetBFICallback, ProfileSummaryInfo *PSI)
Direct function to compute a ModuleSummaryIndex from a given module.
Wrapper around MemoryBufferRef, owning the identifier.
virtual bool addPassesToEmitFile(PassManagerBase &, raw_pwrite_stream &, raw_pwrite_stream *, CodeGenFileType, bool=true, MachineModuleInfo *MMI=nullptr)
Add passes to the specified pass manager to get the specified file emitted.
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
amdgpu Simplify well known AMD library false Value Value const Twine & Name
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...
std::vector< std::string > MAttrs
LLVMContext & getContext() const
Get the global data context.
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...
StringRef str() const
Explicit conversion to StringRef.
void run()
Process all the modules that were added to the code generator in parallel.
cl::opt< bool > LTOPassRemarksWithHotness("lto-pass-remarks-with-hotness", cl::desc("With PGO, include profile count in optimization remarks"), cl::Hidden)
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
Pass * createObjCARCContractPass()
unsigned OptLevel
The Optimization Level - Specify the basic optimization level.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
A ThreadPool for asynchronous parallel execution on a defined number of threads.
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.
This is an important class for using LLVM in a threaded context.
TargetLibraryInfoImpl * LibraryInfo
LibraryInfo - Specifies information about the runtime library for the optimizer.
Helper to gather options relevant to the target machine creation.
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.
void thinLTOResolvePrevailingInIndex(ModuleSummaryIndex &Index, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, function_ref< void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)> recordNewLinkage)
Resolve linkage for prevailing symbols in the Index.
bool isWeakForLinker() const
Expected< std::string > getBitcodeTargetTriple(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the triple information.
const Triple & getTargetTriple() const
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
Error readModuleSummaryIndex(MemoryBufferRef Buffer, ModuleSummaryIndex &CombinedIndex, uint64_t ModuleId)
Parse the specified bitcode buffer and merge the index into CombinedIndex.
const ModuleHash & getModuleHash(const StringRef ModPath) const
Get the module SHA1 hash recorded for the given module path.
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 internalizeAndPromoteInIndex(const StringMap< FunctionImporter::ExportSetTy > &ExportLists, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols, ModuleSummaryIndex &Index)
static void write(bool isBE, void *P, T V)
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)
static std::string writeGeneratedObject(int count, StringRef CacheEntryPath, StringRef SavedObjectsDirectoryPath, const MemoryBuffer &OutputBuffer)
Write out the generated object file, either from CacheEntryPath or from OutputBuffer, preferring hard-link when possible.
void computeSyntheticCounts(ModuleSummaryIndex &Index)
Compute synthetic function entry counts.
std::error_code rename(const Twine &from, const Twine &to)
Rename from to to.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
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
reference get()
Returns a reference to the stored T value.
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.
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.
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 ...
StringRef getBufferIdentifier() const
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< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context)
Read the specified bitcode file, returning the module.
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)
ErrorOr< T > expectedToErrorOrAndEmitErrors(LLVMContext &Ctx, Expected< T > Val)
MemoryBufferRef getMemBuffer() const
A raw_ostream that writes to a file descriptor.
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 crossModuleImport(Module &Module, ModuleSummaryIndex &Index)
Perform cross-module importing for the module identified by ModuleIdentifier.
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())
Pass * createFunctionInliningPass()
createFunctionInliningPass - Return a new pass object that uses a heuristic to inline direct function...
void internalize(Module &Module, ModuleSummaryIndex &Index)
Perform internalization.
The function importer is automatically importing function from other modules based on the provided su...
Lightweight error class with error context and mandatory checking.
StringSet - A wrapper for StringMap that provides set-like functionality.
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...
void emitImports(Module &Module, StringRef OutputName, ModuleSummaryIndex &Index)
Compute and emit the imported files for module at ModulePath.
static ErrorOr< std::unique_ptr< MemoryBuffer > > getOpenFile(int 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.
bool exists(const basic_file_status &status)
Does file exist?
bool AreStatisticsEnabled()
Check if statistics are enabled.
void thinLTOInternalizeAndPromoteInIndex(ModuleSummaryIndex &Index, function_ref< bool(StringRef, GlobalValue::GUID)> isExported)
Update the linkages in the given Index to mark exported values as external and non-exported values as...
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...