34#define DEBUG_TYPE "inline"
35#ifdef LLVM_HAVE_TF_AOT_INLINERSIZEMODEL
36#define LLVM_HAVE_TF_AOT
42STATISTIC(NumCallerCallersAnalyzed,
"Number of caller-callers analyzed");
50 bool IsInliningMandatory)
54 void recordInliningWithCalleeDeletedImpl()
override { recordInliningImpl(); }
56 void recordInliningImpl()
override {
57 if (IsInliningRecommended)
59 [&](OptimizationRemark &
Remark) {
60 Remark <<
": always inline attribute";
64 void recordUnsuccessfulInliningImpl(
const InlineResult &Result)
override {
65 if (IsInliningRecommended)
67 return OptimizationRemarkMissed(Advisor->getAnnotatedInlinePassName(),
68 "NotInlined", DLoc,
Block)
69 <<
"'" <<
NV(
"Callee", Callee) <<
"' is not AlwaysInline into '"
70 <<
NV(
"Caller", Caller)
71 <<
"': " <<
NV(
"Reason",
Result.getFailureReason());
75 void recordUnattemptedInliningImpl()
override {
76 assert(!IsInliningRecommended &&
"Expected to attempt inlining");
81void DefaultInlineAdvice::recordUnsuccessfulInliningImpl(
87 return OptimizationRemarkMissed(
Advisor->getAnnotatedInlinePassName(),
89 <<
"'" <<
NV(
"Callee",
Callee) <<
"' is not inlined into '"
91 <<
"': " <<
NV(
"Reason",
Result.getFailureReason());
99 Advisor->getAnnotatedInlinePassName());
106 Advisor->getAnnotatedInlinePassName());
114 .getCachedResult<ProfileSummaryAnalysis>(
115 *CB.
getParent()->getParent()->getParent());
127 auto GetEphValuesCache =
134 auto GetInlineCost = [&](
CallBase &CB) {
135 bool RemarksEnabled =
136 Callee.getContext().getDiagHandlerPtr()->isMissedOptRemarkEnabled(
138 return getInlineCost(CB, Params, CallerTTI, GetAssumptionCache, GetTLI,
139 GetBFI, PSI, RemarksEnabled ? &ORE :
nullptr,
148std::unique_ptr<InlineAdvice>
149DefaultInlineAdvisor::getAdviceImpl(
CallBase &CB) {
151 return std::make_unique<DefaultInlineAdvice>(
153 FAM.getResult<OptimizationRemarkEmitterAnalysis>(*CB.
getCaller()));
163void InlineAdvice::recordInlineStatsIfNeeded() {
170 recordInlineStatsIfNeeded();
176 recordInlineStatsIfNeeded();
183bool InlineAdvisorAnalysis::initializeIR2VecVocabIfRequested(
187 if (!IR2VecVocabResult.isValid()) {
188 M.getContext().emitError(
"Failed to load IR2Vec vocabulary");
203 Advisor.reset(DA.Factory(M,
FAM, Params, IC));
206 auto GetDefaultAdvice = [&
FAM, Params](
CallBase &CB) {
208 return OIC.has_value();
218 std::move(Advisor), ReplaySettings,
226#ifdef LLVM_HAVE_TFLITE
228 if (!InlineAdvisorAnalysis::initializeIR2VecVocabIfRequested(M, MAM))
235 if (!InlineAdvisorAnalysis::initializeIR2VecVocabIfRequested(M, MAM))
254 if (!Caller->hasLocalLinkage() && !Caller->hasLinkOnceODRLinkage())
277 TotalSecondaryCost = 0;
279 int CandidateCost = IC.
getCost() - 1;
282 bool ApplyLastCallBonus = Caller->hasLocalLinkage() && !Caller->hasOneUse();
284 bool InliningPreventsSomeOuterInline =
false;
285 unsigned NumCallerUsers = 0;
286 for (
User *U : Caller->users()) {
293 ApplyLastCallBonus =
false;
298 ++NumCallerCallersAnalyzed;
300 ApplyLastCallBonus =
false;
310 InliningPreventsSomeOuterInline =
true;
311 TotalSecondaryCost += IC2.
getCost();
316 if (!InliningPreventsSomeOuterInline)
323 if (ApplyLastCallBonus)
329 if (InlineDeferralScale < 0)
330 return TotalSecondaryCost < IC.
getCost();
332 int TotalCost = TotalSecondaryCost + IC.
getCost() * NumCallerUsers;
333 int Allowance = IC.
getCost() * InlineDeferralScale;
334 return TotalCost < Allowance;
342template <
class RemarkT>
343decltype(
auto)
operator<<(RemarkT &&R,
const InlineCost &IC) {
346 R <<
"(cost=always)";
354 R <<
": " <<
ore::NV(
"Reason", Reason);
355 return std::forward<RemarkT>(R);
378std::optional<InlineCost>
391 <<
", Call: " << CB <<
"\n");
397 <<
", Call: " << CB <<
"\n");
401 <<
"'" <<
NV(
"Callee", Callee) <<
"' not inlined into '"
402 <<
NV(
"Caller", Caller)
403 <<
"' because it should never be inlined " << IC;
408 <<
"'" <<
NV(
"Callee", Callee) <<
"' not inlined into '"
409 <<
NV(
"Caller", Caller) <<
"' because too costly to inline "
417 int TotalSecondaryCost = 0;
419 TotalSecondaryCost, GetInlineCost)) {
422 <<
", outer Cost = " << TotalSecondaryCost <<
'\n');
426 <<
"Not inlining. Cost of inlining '" <<
NV(
"Callee", Callee)
427 <<
"' increases the cost of inlining '" <<
NV(
"Caller", Caller)
428 <<
"' in other contexts";
444 for (
DILocation *DIL = DLoc.
get(); DIL; DIL = DIL->getInlinedAt()) {
450 DIL->getLine() - DIL->getScope()->getSubprogram()->getLine();
451 uint32_t Discriminator = DIL->getBaseDiscriminator();
452 StringRef Name = DIL->getScope()->getSubprogram()->getLinkageName();
454 Name = DIL->getScope()->getSubprogram()->getName();
456 if (
Format.outputColumn())
458 if (
Format.outputDiscriminator() && Discriminator)
462 return CallSiteLoc.
str();
470 Remark <<
" at callsite ";
471 for (
DILocation *DIL = DLoc.
get(); DIL; DIL = DIL->getInlinedAt()) {
474 unsigned int Offset = DIL->getLine();
475 Offset -= DIL->getScope()->getSubprogram()->getLine();
476 unsigned int Discriminator = DIL->getBaseDiscriminator();
477 StringRef Name = DIL->getScope()->getSubprogram()->getLinkageName();
479 Name = DIL->getScope()->getSubprogram()->getName();
481 <<
ore::NV(
"Column", DIL->getColumn());
496 StringRef RemarkName = AlwaysInline ?
"AlwaysInline" :
"Inlined";
499 Remark <<
"'" <<
ore::NV(
"Callee", &Callee) <<
"' inlined into '"
500 <<
ore::NV(
"Caller", &Caller) <<
"'";
511 bool ForProfileContext,
const char *
PassName) {
515 if (ForProfileContext)
516 Remark <<
" to match profiling context";
517 Remark <<
" with " << IC;
523 std::optional<InlineContext>
IC)
532 std::make_unique<ImportedFunctionsInliningStatistics>();
546 return std::make_unique<MandatoryInlineAdvice>(
this, CB,
getCallerORE(CB),
567 return "always-inline";
569 return "cgscc-inline";
571 return "early-inline";
575 return "module-inline";
577 return "replay-cgscc-inline";
579 return "replay-sample-profile-inline";
581 return "sample-profile-inline";
603 auto TrivialDecision =
606 if (TrivialDecision) {
607 if (TrivialDecision->isSuccess())
616 bool MandatoryOnly) {
633 OS <<
"No Inline Advisor\n";
635 IA->getAdvisor()->print(OS);
642 const auto &MAMProxy =
645 if (InitialC.
size() == 0) {
646 OS <<
"SCC is empty!\n";
649 Module &M = *InitialC.
begin()->getFunction().getParent();
652 OS <<
"No Inline Advisor\n";
654 IA->getAdvisor()->print(OS);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static const Function * getParent(const Value *V)
This file defines the IR2Vec vocabulary analysis(IR2VecVocabAnalysis), the core ir2vec::Embedder inte...
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
static bool shouldBeDeferred(Function *Caller, TargetTransformInfo &CallerTTI, InlineCost IC, int &TotalSecondaryCost, function_ref< InlineCost(CallBase &CB)> GetInlineCost)
Return true if inlining of CB can block the caller from being inlined which is proved to be more bene...
static const char * getLTOPhase(ThinOrFullLTOPhase LTOPhase)
static std::optional< llvm::InlineCost > getDefaultInlineAdvice(CallBase &CB, FunctionAnalysisManager &FAM, const InlineParams &Params)
static const char * getInlineAdvisorContext(InlinePass IP)
static DebugLoc getDebugLoc(MachineBasicBlock::instr_iterator FirstMI, MachineBasicBlock::instr_iterator LastMI)
Return the first DebugLoc that has line number information, given a range of instructions.
static const Function * getCalledFunction(const Value *V)
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
static const char PassName[]
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
static LLVM_ABI Attribute get(LLVMContext &Context, AttrKind Kind, uint64_t Val=0)
Return a uniquified Attribute object.
LLVM Basic Block Representation.
Analysis pass which computes BlockFrequencyInfo.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
void addFnAttr(Attribute::AttrKind Kind)
Adds the attribute to the function.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
LLVM_ABI Function * getCaller()
Helper to get the caller (the parent function).
DILocation * get() const
Get the underlying DILocation.
The default (manual heuristics) implementation of the InlineAdvisor.
EphemeralValuesCache Result
This analysis provides the vocabulary for IR2Vec.
Capture state between an inlining decision having had been made, and its impact being observable.
Function *const Caller
Caller and Callee are pre-inlining.
virtual void recordInliningWithCalleeDeletedImpl()
virtual void recordInliningImpl()
const BasicBlock *const Block
LLVM_ABI void recordInlining()
Exactly one of the record* APIs must be called.
OptimizationRemarkEmitter & ORE
InlineAdvisor *const Advisor
LLVM_ABI InlineAdvice(InlineAdvisor *Advisor, CallBase &CB, OptimizationRemarkEmitter &ORE, bool IsInliningRecommended)
LLVM_ABI void recordInliningWithCalleeDeleted()
Call after inlining succeeded, and results in the callee being delete-able, meaning,...
const bool IsInliningRecommended
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
The InlineAdvisorAnalysis is a module pass because the InlineAdvisor needs to capture state right bef...
static LLVM_ABI AnalysisKey Key
Interface for deciding whether to inline a call site or not.
const std::optional< InlineContext > IC
OptimizationRemarkEmitter & getCallerORE(CallBase &CB)
FunctionAnalysisManager & FAM
static MandatoryInliningKind getMandatoryKind(CallBase &CB, FunctionAnalysisManager &FAM, OptimizationRemarkEmitter &ORE)
const std::string AnnotatedInlinePassName
virtual std::unique_ptr< InlineAdvice > getMandatoryAdvice(CallBase &CB, bool Advice)
std::unique_ptr< ImportedFunctionsInliningStatistics > ImportedFunctionsStats
InlineAdvisor(InlineAdvisor &&)=delete
virtual std::unique_ptr< InlineAdvice > getAdviceImpl(CallBase &CB)=0
std::unique_ptr< InlineAdvice > getAdvice(CallBase &CB, bool MandatoryOnly=false)
Get an InlineAdvice containing a recommendation on whether to inline or not.
Represents the cost of inlining a function.
int getThreshold() const
Get the threshold against which the cost was computed.
const char * getReason() const
Get the reason of Always or Never.
int getCost() const
Get the inline cost estimate.
int getCostDelta() const
Get the cost delta from the threshold for inlining.
InlineResult is basically true or false.
An SCC of the call graph.
A lazily constructed view of the call graph of a module.
A helper class to return the specified delimiter string after the first invocation of operator String...
A Module instance is used to store all the information related to an LLVM module.
Used for dynamically registering InlineAdvisors as plugins.
static LLVM_ABI AnalysisKey Key
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Analysis providing profile information.
Represent a constant reference to a string, i.e.
constexpr bool empty() const
Check if the string is empty.
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
LLVMContext & getContext() const
All values hold a context through their type.
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
This class implements an extremely fast bulk output stream that can only output to a stream.
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Add a small namespace to avoid name clashes with the classes used in the streaming interface.
DiagnosticInfoOptimizationBase::Argument NV
This is an optimization pass for GlobalISel generic memory operations.
@ ReplaySampleProfileInliner
LLVM_ABI void emitInlinedInto(OptimizationRemarkEmitter &ORE, DebugLoc DLoc, const BasicBlock *Block, const Function &Callee, const Function &Caller, bool IsMandatory, function_ref< void(OptimizationRemark &)> ExtraContext={}, const char *PassName=nullptr)
Emit ORE message.
LLVM_ABI InlineCost getInlineCost(CallBase &Call, const InlineParams &Params, TargetTransformInfo &CallerTTI, function_ref< AssumptionCache &(Function &)> GetAssumptionCache, function_ref< const TargetLibraryInfo &(Function &)> GetTLI, function_ref< BlockFrequencyInfo &(Function &)> GetBFI=nullptr, ProfileSummaryInfo *PSI=nullptr, OptimizationRemarkEmitter *ORE=nullptr, function_ref< EphemeralValuesCache &(Function &)> GetEphValuesCache=nullptr)
Get an InlineCost object representing the cost of inlining this callsite.
LLVM_ABI std::string inlineCostStr(const InlineCost &IC)
Utility for extracting the inline cost message to a string.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
InliningAdvisorMode
There are 4 scenarios we can use the InlineAdvisor:
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
LLVM_ABI std::unique_ptr< InlineAdvisor > getDevelopmentModeAdvisor(Module &M, ModuleAnalysisManager &MAM, std::function< bool(CallBase &)> GetDefaultAdvice)
LLVM_ABI std::unique_ptr< InlineAdvisor > getReleaseModeAdvisor(Module &M, ModuleAnalysisManager &MAM, std::function< bool(CallBase &)> GetDefaultAdvice)
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
std::string utostr(uint64_t X, bool isNeg=false)
LLVM_ABI void setInlineRemark(CallBase &CB, StringRef Message)
Set the inline-remark attribute.
LLVM_ABI std::optional< InlineResult > getAttributeBasedInliningDecision(CallBase &Call, Function *Callee, TargetTransformInfo &CallerTTI, function_ref< const TargetLibraryInfo &(Function &)> GetTLI)
Returns InlineResult::success() if the call site should be always inlined because of user directives,...
AnalysisManager< LazyCallGraph::SCC, LazyCallGraph & > CGSCCAnalysisManager
The CGSCC analysis manager.
LLVM_ABI std::string AnnotateInlinePassName(InlineContext IC)
ThinOrFullLTOPhase
This enumerates the LLVM full LTO or ThinLTO optimization phases.
@ FullLTOPreLink
Full LTO prelink phase.
@ ThinLTOPostLink
ThinLTO postlink (backend compile) phase.
@ None
No LTO/ThinLTO behavior needed.
@ FullLTOPostLink
Full LTO postlink (backend compile) phase.
@ ThinLTOPreLink
ThinLTO prelink (summary) phase.
const AnalysisOptions & getAnalysisOptions(const LLVMContext &C)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI void emitInlinedIntoBasedOnCost(OptimizationRemarkEmitter &ORE, DebugLoc DLoc, const BasicBlock *Block, const Function &Callee, const Function &Caller, const InlineCost &IC, bool ForProfileContext=false, const char *PassName=nullptr)
Emit ORE message based in cost (default heuristic).
LLVM_ABI std::unique_ptr< InlineAdvisor > getReplayInlineAdvisor(Module &M, FunctionAnalysisManager &FAM, LLVMContext &Context, std::unique_ptr< InlineAdvisor > OriginalAdvisor, const ReplayInlinerSettings &ReplaySettings, bool EmitRemarks, InlineContext IC)
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
LLVM_ABI std::optional< InlineCost > shouldInline(CallBase &CB, TargetTransformInfo &CallerTTI, function_ref< InlineCost(CallBase &CB)> GetInlineCost, OptimizationRemarkEmitter &ORE, bool EnableDeferral=true)
Return the cost only if the inliner should attempt to inline at the given CallSite.
OuterAnalysisManagerProxy< ModuleAnalysisManager, LazyCallGraph::SCC, LazyCallGraph & > ModuleAnalysisManagerCGSCCProxy
A proxy from a ModuleAnalysisManager to an SCC.
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
LLVM_ABI void addLocationToRemarks(OptimizationRemark &Remark, DebugLoc DLoc)
Add location info to ORE message.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI std::string formatCallSiteLocation(DebugLoc DLoc, const CallSiteFormat &Format)
Get call site location as a string with the given format.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
A special type used by analysis passes to provide an address that identifies that particular analysis...
Support structure for SCC passes to communicate updates the call graph back to the CGSCC pass manager...
LLVM_ABI bool tryCreate(InlineParams Params, InliningAdvisorMode Mode, const ReplayInlinerSettings &ReplaySettings, InlineContext IC)
Provides context on when an inline advisor is constructed in the pipeline (e.g., link phase,...
ThinOrFullLTOPhase LTOPhase
Thresholds to tune inline cost analysis.
std::optional< bool > EnableDeferral
Indicate whether we should allow inline deferral.