52 errs() <<
"failed to open " << Path <<
": " << Msg <<
'\n';
58 bool UseInputModulePath) {
67 auto setHook = [&](std::string PathSuffix,
ModuleHookFn &Hook) {
70 Hook = [=](
unsigned Task,
const Module &M) {
73 if (LinkerHook && !LinkerHook(Task, M))
76 std::string PathPrefix;
80 if (M.getModuleIdentifier() ==
"ld-temp.o" || !UseInputModulePath) {
81 PathPrefix = OutputFileName;
82 if (Task != (
unsigned)-1)
83 PathPrefix +=
utostr(Task) +
".";
85 PathPrefix = M.getModuleIdentifier() +
".";
86 std::string Path = PathPrefix + PathSuffix +
".bc";
108 std::string Path = OutputFileName +
"index.bc";
117 Path = OutputFileName +
"index.dot";
130 std::unique_ptr<TargetMachine>
135 for (
const std::string &A : Conf.
MAttrs)
230 std::string PipelineDesc,
231 std::string AAPipelineDesc,
237 if (!AAPipelineDesc.empty())
240 AAPipelineDesc +
"': " +
toString(std::move(Err)));
265 PipelineDesc +
"': " +
toString(std::move(Err)));
311 runNewPMPasses(Conf, Mod, TM, Conf.
OptLevel, IsThinLTO, ExportSummary,
314 runOldPMPasses(Conf, Mod, TM, IsThinLTO, ExportSummary, ImportSummary);
319 "lto-embed-bitcode",
cl::init(
false),
320 cl::desc(
"Embed LLVM bitcode in object files produced by LTO"));
322 static void EmitBitcodeSection(
Module &M,
const Config &Conf) {
329 std::unique_ptr<MemoryBuffer> Buf(
336 unsigned Task,
Module &Mod) {
340 EmitBitcodeSection(Mod, Conf);
342 std::unique_ptr<ToolOutputFile> DwoOut;
344 if (!Conf.
DwoDir.empty()) {
356 if (!DwoFile.
empty()) {
363 auto Stream = AddStream(Task);
366 DwoOut ? &DwoOut->os() :
nullptr,
369 CodeGenPasses.
run(Mod);
376 unsigned ParallelCodeGenParallelismLevel,
377 std::unique_ptr<Module> Mod) {
378 ThreadPool CodegenThreadPool(ParallelCodeGenParallelismLevel);
379 unsigned ThreadCount = 0;
383 std::move(Mod), ParallelCodeGenParallelismLevel,
384 [&](std::unique_ptr<Module> MPart) {
396 CodegenThreadPool.
async(
404 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.
get());
406 std::unique_ptr<TargetMachine> TM =
407 createTargetMachine(C, T, *MPartInCtx);
409 codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx);
413 std::move(BC), ThreadCount++);
420 CodegenThreadPool.
wait();
443 DiagOutputFile->keep();
444 DiagOutputFile->os().flush();
449 unsigned ParallelCodeGenParallelismLevel,
450 std::unique_ptr<Module> Mod,
456 std::unique_ptr<TargetMachine>
TM = createTargetMachine(C, *TOrErr, *Mod);
463 return DiagFileOrErr.takeError();
464 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
467 if (!
opt(C, TM.get(), 0, *Mod,
false,
468 &CombinedIndex,
nullptr))
472 if (ParallelCodeGenParallelismLevel == 1) {
473 codegen(C, TM.get(), AddStream, 0, *Mod);
475 splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel,
483 std::vector<GlobalValue*> DeadGVs;
487 DeadGVs.push_back(&GV);
494 GV->removeDeadConstantUsers();
498 GV->eraseFromParent();
511 std::unique_ptr<TargetMachine>
TM = createTargetMachine(Conf, *TOrErr, Mod);
518 return DiagFileOrErr.takeError();
519 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
522 codegen(Conf, TM.get(), AddStream, Task, Mod);
538 if (!DefinedGlobals.
empty())
545 auto ModuleLoader = [&](
StringRef Identifier) {
547 "ODR Type uniquing should be enabled on the context");
548 auto I = ModuleMap.
find(Identifier);
550 return I->second.getLazyModule(Mod.
getContext(),
562 if (!
opt(Conf, TM.get(), Task, Mod,
true,
563 nullptr, &CombinedIndex))
566 codegen(Conf, TM.get(), AddStream, Task, Mod);
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.
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, CodeGenFileType FileType=CGFT_ObjectFile, bool PreserveLocals=false)
Split M into OSs.size() partitions, and generate code for each.
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.
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
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...
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.
bool EnablePGOCSInstrUse
Enable profile context sensitive profile use pass.
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
Implements a dense probed hash-table based set.
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 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::string PGOSampleUse
Path of the sample Profile data file.
void registerCallbacks(PassInstrumentationCallbacks &PIC)
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
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.
Tagged union holding either a T or a Error.
bool EnablePGOCSInstrGen
Enable profile context sensitive instrumentation pass.
void AddFeature(StringRef String, bool Enable=true)
Adds Features.
void registerLoopAnalyses(LoopAnalysisManager &LAM)
Registers all available loop analysis passes.
std::string SplitDwarfFile
The name for the split debug info file used for the DW_AT_[GNU_]dwo_name attribute in the skeleton CU...
StringRef str() const
Explicit conversion to StringRef.
Error backend(const Config &C, AddStreamFn AddStream, unsigned ParallelCodeGenParallelismLevel, std::unique_ptr< Module > M, ModuleSummaryIndex &CombinedIndex)
Runs a regular LTO backend.
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)
std::string PGOInstrUse
Path of the profile data file.
The file should be opened in text mode on platforms that make this distinction.
This class provides an interface to register all the standard pass instrumentations and manages their...
static void codegen(Module *M, llvm::raw_pwrite_stream &OS, function_ref< std::unique_ptr< TargetMachine >()> TMFactory, CodeGenFileType FileType)
PassManager manages ModulePassManagers.
static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals, const ModuleSummaryIndex &Index)
initializer< Ty > init(const Ty &Val)
ModuleHookFn PreOptModuleHook
This module hook is called after linking (regular LTO) or loading (ThinLTO) the module, before modifying it.
std::function< bool(unsigned Task, const Module &)> ModuleHookFn
The following callbacks deal with tasks, which normally represent the entire optimization and code ge...
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.
Error thinBackend(const 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.
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
std::string CSIRProfile
Context Sensitive PGO profile path.
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.
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.
Triple - Helper class for working with autoconf configuration names.
std::string RemarksFilename
Optimization remarks file path.
void exportToDot(raw_ostream &OS, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols) const
Export summary to dot file for GraphViz.
static ErrorSuccess success()
Create a success value.
bool RunCSIRInstr
Run PGO context sensitive IR instrumentation.
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.
#define LLVM_ATTRIBUTE_NORETURN
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.
CodeGenFileType CGFileType
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)
void EmbedBitcodeInModule(Module &M, MemoryBufferRef Buf, bool EmbedBitcode, bool EmbedMarker, const std::vector< uint8_t > *CmdArgs)
Save a copy of the llvm IR as data in the __LLVM,__bitcode section.
std::string RemarksFormat
The format used for serializing remarks (default: YAML).
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.
SmallVector-backed MemoryBuffer instance.
This header defines a class that provides bookkeeping for all standard (i.e in-tree) pass instrumenta...
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 SplitDwarfOutput
The path to write a .dwo file to.
std::string RemarksPasses
Optimization remarks pass filter.
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).
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Optimize quickly without destroying debuggability.
Expected< std::unique_ptr< ToolOutputFile > > setupOptimizationRemarks(LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses, StringRef RemarksFormat, bool RemarksWithHotness, int Count=-1)
Setup optimization remarks.
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)
This class manages callbacks registration, as well as provides a way for PassInstrumentation to pass ...
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)
PipelineTuningOptions PTO
Tunable parameters for passes in the default pipelines.
This header defines various interfaces for pass management in LLVM.
ModuleHookFn PostPromoteModuleHook
This hook is called after promoting any internal functions (ThinLTO-specific).
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...
iterator_range< global_value_iterator > global_values()