50 errs() <<
"failed to open " << Path <<
": " << Msg <<
'\n';
56 bool UseInputModulePath) {
65 auto setHook = [&](std::string PathSuffix,
ModuleHookFn &Hook) {
68 Hook = [=](
unsigned Task,
const Module &M) {
71 if (LinkerHook && !LinkerHook(Task, M))
74 std::string PathPrefix;
78 if (M.getModuleIdentifier() ==
"ld-temp.o" || !UseInputModulePath) {
79 PathPrefix = OutputFileName;
80 if (Task != (
unsigned)-1)
81 PathPrefix +=
utostr(Task) +
".";
83 PathPrefix = M.getModuleIdentifier() +
".";
84 std::string Path = PathPrefix + PathSuffix +
".bc";
104 std::string Path = OutputFileName +
"index.bc";
113 Path = OutputFileName +
"index.dot";
117 Index.exportToDot(OSDot);
126 std::unique_ptr<TargetMachine>
131 for (
const std::string &A : Conf.
MAttrs)
216 std::string PipelineDesc,
217 std::string AAPipelineDesc,
223 if (!AAPipelineDesc.empty())
226 AAPipelineDesc +
"': " +
toString(std::move(Err)));
251 PipelineDesc +
"': " +
toString(std::move(Err)));
292 runNewPMPasses(Conf, Mod, TM, Conf.
OptLevel, IsThinLTO, ExportSummary,
295 runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
300 unsigned Task,
Module &Mod) {
304 std::unique_ptr<ToolOutputFile> DwoOut;
306 if (!Conf.
DwoDir.empty()) {
316 if (!DwoFile.
empty()) {
319 DwoOut = llvm::make_unique<ToolOutputFile>(DwoFile, EC,
sys::fs::F_None);
324 auto Stream = AddStream(Task);
327 DwoOut ? &DwoOut->os() :
nullptr,
330 CodeGenPasses.
run(Mod);
337 unsigned ParallelCodeGenParallelismLevel,
338 std::unique_ptr<Module> Mod) {
339 ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
340 unsigned ThreadCount = 0;
344 std::move(Mod), ParallelCodeGenParallelismLevel,
345 [&](std::unique_ptr<Module> MPart) {
357 CodegenThreadPool.
async(
365 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.
get());
367 std::unique_ptr<TargetMachine> TM =
368 createTargetMachine(C, T, *MPartInCtx);
370 codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
374 std::move(BC), ThreadCount++);
381 CodegenThreadPool.
wait();
405 DiagOutputFile->keep();
406 DiagOutputFile->os().flush();
411 unsigned ParallelCodeGenParallelismLevel,
412 std::unique_ptr<Module> Mod,
418 std::unique_ptr<TargetMachine>
TM = createTargetMachine(C, *TOrErr, *Mod);
424 return DiagFileOrErr.takeError();
425 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
428 if (!
opt(C, TM.get(), 0, *Mod,
false,
429 &CombinedIndex,
nullptr))
433 if (ParallelCodeGenParallelismLevel == 1) {
434 codegen(C, TM.get(), AddStream, 0, *Mod);
436 splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
444 std::vector<GlobalValue*> DeadGVs;
448 DeadGVs.push_back(&GV);
455 GV->removeDeadConstantUsers();
459 GV->eraseFromParent();
472 std::unique_ptr<TargetMachine>
TM = createTargetMachine(Conf, *TOrErr, Mod);
478 return DiagFileOrErr.takeError();
479 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
482 codegen(Conf, TM.get(), AddStream, Task, Mod);
498 if (!DefinedGlobals.
empty())
505 auto ModuleLoader = [&](
StringRef Identifier) {
507 "ODR Type uniquing should be enabled on the context");
508 auto I = ModuleMap.
find(Identifier);
510 return I->second.getLazyModule(Mod.
getContext(),
522 if (!
opt(Conf, TM.get(), Task, Mod,
true,
523 nullptr, &CombinedIndex))
526 codegen(Conf, TM.get(), AddStream, Task, Mod);
static void codegen(Module *M, llvm::raw_pwrite_stream &OS, function_ref< std::unique_ptr< TargetMachine >()> TMFactory, TargetMachine::CodeGenFileType FileType)
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.
Interfaces for registering analysis passes, producing common pass manager configurations, and parsing of pass pipelines.
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...
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
CodeGenOpt::Level CGOptLevel
PassManagerBuilder - This class is used to set up a standard optimization sequence for languages like...
MCTargetOptions MCOptions
Machine level options.
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.
This header provides classes for managing a pipeline of passes over loops in LLVM IR...
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...
Error parseAAPipeline(AAManager &AA, StringRef PipelineText)
Parse a textual alias analysis pipeline into the provided AA manager.
bool ShouldDiscardValueNames
std::string OverrideTriple
Setting this field will replace target triples in input files with this triple.
void populateThinLTOPassManager(legacy::PassManagerBase &PM)
std::string SplitDwarfFile
bool CodeGenOnly
Disable entirely the optimizer, including importing for ThinLTO.
void registerModuleAnalyses(ModuleAnalysisManager &MAM)
Registers all available module analysis passes.
void SplitModule(std::unique_ptr< Module > M, unsigned N, function_ref< void(std::unique_ptr< Module > MPart)> ModuleCallback, bool PreserveLocals=false)
Splits the module M into N linkable partitions.
std::unique_ptr< raw_ostream > ResolutionFile
If this field is set, LTO will write input file paths and symbol resolutions here in llvm-lto2 comman...
bool convertToDeclaration(GlobalValue &GV)
Converts value GV to declaration, or replaces with a declaration if it is an alias.
ImmutablePass * createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA)
Create an analysis pass wrapper around a TTI object.
ModuleSummaryIndex * ExportSummary
The module summary index to use for exporting information from the regular LTO phase, for example for the CFI and devirtualization type tests.
std::string getString() const
Returns features as a string.
const FeatureBitset Features
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.
Optional< CodeModel::Model > getCodeModel() const
Returns the code model (tiny, small, kernel, medium or large model)
OptimizationLevel
LLVM-provided high-level optimization levels.
Implementation of the target library information.
This class implements a map that also provides access to all stored values in a deterministic order...
bool isGlobalValueLive(const GlobalValueSummary *GVS) const
bool DebugPassManager
Whether to emit the pass manager debuggging informations.
std::unique_ptr< Module > splitCodeGen(std::unique_ptr< Module > M, ArrayRef< raw_pwrite_stream *> OSs, ArrayRef< llvm::raw_pwrite_stream *> BCOSs, const std::function< std::unique_ptr< TargetMachine >()> &TMFactory, TargetMachine::CodeGenFileType FileType=TargetMachine::CGFT_ObjectFile, bool PreserveLocals=false)
Split M into OSs.size() partitions, and generate code for each.
std::string PGOSampleUse
Path of the sample Profile data file.
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.
PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM, ExtraArgTs... ExtraArgs)
Run all of the passes in this manager over the given unit of IR.
std::shared_future< void > async(Function &&F, Args &&... ArgList)
Asynchronous submission of a task to the pool.
ModuleHookFn PreCodeGenModuleHook
This module hook is called before code generation.
Pass * Inliner
Inliner - Specifies the inliner to use.
CombinedIndexHookFn CombinedIndexHook
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.
std::function< std::unique_ptr< NativeObjectStream >unsigned Task)> AddStreamFn
This type defines the callback to add a native object that is generated on the fly.
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.
bool RemarksWithHotness
Whether to emit optimization remarks with hotness informations.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
std::string DwoDir
The directory to store .dwo files.
std::vector< std::string > MAttrs
LLVMContext & getContext() const
Get the global data context.
std::string ProfileRemapping
Name remapping file for profile data.
void populateLTOPassManager(legacy::PassManagerBase &PM)
bool registerPass(PassBuilderT &&PassBuilder)
Register an analysis pass with the manager.
This class provides access to building LLVM's passes.
std::function< bool(unsigned Task, const Module &)> ModuleHookFn
The following callbacks deal with tasks, which normally represent the entire optimization and code ge...
Tagged union holding either a T or a Error.
void AddFeature(StringRef String, bool Enable=true)
Adds Features.
void registerLoopAnalyses(LoopAnalysisManager &LAM)
Registers all available loop analysis passes.
StringRef str() const
Explicit conversion to StringRef.
unsigned OptLevel
The Optimization Level - Specify the basic optimization level.
void crossRegisterProxies(LoopAnalysisManager &LAM, FunctionAnalysisManager &FAM, CGSCCAnalysisManager &CGAM, ModuleAnalysisManager &MAM)
Cross register the analysis managers through their proxies.
std::string SampleProfile
Sample PGO profile path.
Optional< CodeModel::Model > CodeModel
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
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...
iterator find(const KeyT &Key)
PassManager manages ModulePassManagers.
static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals, const ModuleSummaryIndex &Index)
ModuleHookFn PreOptModuleHook
This module hook is called after linking (regular LTO) or loading (ThinLTO) the module, before modifying it.
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...
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
TargetLibraryInfoImpl * LibraryInfo
LibraryInfo - Specifies information about the runtime library for the optimizer.
Disable as many optimizations as possible.
A manager for alias analyses.
TargetIRAnalysis getTargetIRAnalysis()
Get a TargetIRAnalysis appropriate for the target.
bool UseNewPM
Use the new pass manager.
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 isODRUniquingDebugTypes() const
Whether there is a string map for uniquing debug info identifiers across the context.
void registerFunctionAnalyses(FunctionAnalysisManager &FAM)
Registers all available function analysis passes.
std::string DefaultTriple
Setting this field will replace unspecified target triples in input files with this triple...
Optimize for fast execution as much as possible.
const Triple & getTargetTriple() const
Function and variable summary information to aid decisions and implementation of importing.
const Target & getTarget() const
ModuleHookFn PostInternalizeModuleHook
This hook is called after internalizing the module.
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
ModulePassManager buildThinLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging, const ModuleSummaryIndex *ImportSummary)
Build an ThinLTO default optimization pipeline to a pass manager.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
TargetMachine::CodeGenFileType CGFileType
Triple - Helper class for working with autoconf configuration names.
std::string RemarksFilename
Optimization remarks file path.
static ErrorSuccess success()
Create a success value.
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
Error parsePassPipeline(ModulePassManager &MPM, StringRef PipelineText, bool VerifyEachPass=true, bool DebugLogging=false)
Parse a textual pass pipeline description into a ModulePassManager.
Optional< Reloc::Model > RelocModel
reference get()
Returns a reference to the stored T value.
std::string utostr(uint64_t X, bool isNeg=false)
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.
std::string OptPipeline
If this field is set, the set of passes run in the middle-end optimizer will be the one specified by ...
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 ...
static Error finalizeOptimizationRemarks(std::unique_ptr< ToolOutputFile > DiagOutputFile)
Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context)
Read the specified bitcode file, returning the module.
#define LLVM_ATTRIBUTE_NORETURN
Expected< bool > importFunctions(Module &M, const ImportMapTy &ImportList)
Import functions in Module M based on the supplied import list.
Error thinBackend(Config &C, unsigned Task, AddStreamFn AddStream, Module &M, const ModuleSummaryIndex &CombinedIndex, const FunctionImporter::ImportMapTy &ImportList, const GVSummaryMapTy &DefinedGlobals, MapVector< StringRef, BitcodeModule > &ModuleMap)
Runs a ThinLTO backend.
A raw_ostream that writes to a file descriptor.
pointer data()
Return a pointer to the vector's buffer, even if empty().
Manages a sequence of passes over a particular unit of IR.
LLVM_NODISCARD bool empty() const
A struct capturing PGO tunables.
void thinLTOInternalizeModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Internalize TheModule based on the information recorded in the summaries during global summary-based ...
void setTargetTriple(StringRef T)
Set the target triple.
std::string DwoPath
The path to write a .dwo file to.
LLVM_NODISCARD bool empty() const
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
This header provides classes for managing passes over SCCs of the call graph.
const std::string to_string(const T &Value)
void registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM)
Registers all available CGSCC analysis passes.
ModulePassManager buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging, ModuleSummaryIndex *ExportSummary)
Build an LTO default optimization pipeline to a pass manager.
ModuleHookFn PostImportModuleHook
This hook is called after importing from other modules (ThinLTO-specific).
Error backend(Config &C, AddStreamFn AddStream, unsigned ParallelCodeGenParallelismLevel, std::unique_ptr< Module > M, ModuleSummaryIndex &CombinedIndex)
Runs a regular LTO backend.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Optimize quickly without destroying debuggability.
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...
Lightweight error class with error context and mandatory checking.
ModuleHookFn PostOptModuleHook
This module hook is called after optimization is complete.
Primary interface to the complete machine description for the target machine.
PICLevel::Level getPICLevel() const
Returns the PIC level (small or large model)
Error addSaveTemps(std::string OutputFileName, bool UseInputModulePath=false)
This is a convenience function that configures this Config object to write temporary files named afte...
A derived class of LLVMContext that initializes itself according to a given Config object...
StringRef - Represent a constant reference to a string, i.e.
A container for analyses that lazily runs them and caches their results.
static LLVM_ATTRIBUTE_NORETURN void reportOpenError(StringRef Path, Twine Msg)
This header defines various interfaces for pass management in LLVM.
ModuleHookFn PostPromoteModuleHook
This hook is called after promoting any internal functions (ThinLTO-specific).
iterator_range< global_value_iterator > global_values()
void wait()
Blocking wait for all the threads to complete and the queue to be empty.
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...