1 //===- InlineAdvisor.cpp - analysis pass implementation -------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements InlineAdvisorAnalysis and DefaultInlineAdvisor, and
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Analysis/InlineAdvisor.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/Analysis/InlineCost.h"
17 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
18 #include "llvm/Analysis/ProfileSummaryInfo.h"
19 #include "llvm/Analysis/ReplayInlineAdvisor.h"
20 #include "llvm/Analysis/TargetLibraryInfo.h"
21 #include "llvm/Analysis/TargetTransformInfo.h"
22 #include "llvm/IR/DebugInfoMetadata.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/raw_ostream.h"
28 #define DEBUG_TYPE "inline"
30 // This weirdly named statistic tracks the number of times that, when attempting
31 // to inline a function A into B, we analyze the callers of B in order to see
32 // if those would be more profitable and blocked inline steps.
33 STATISTIC(NumCallerCallersAnalyzed
, "Number of caller-callers analyzed");
35 /// Flag to add inline messages as callsite attributes 'inline-remark'.
37 InlineRemarkAttribute("inline-remark-attribute", cl::init(false),
39 cl::desc("Enable adding inline-remark attribute to"
40 " callsites processed by inliner but decided"
41 " to be not inlined"));
43 // An integer used to limit the cost of inline deferral. The default negative
44 // number tells shouldBeDeferred to only take the secondary cost into account.
46 InlineDeferralScale("inline-deferral-scale",
47 cl::desc("Scale to limit the cost of inline deferral"),
48 cl::init(2), cl::Hidden
);
50 extern cl::opt
<InlinerFunctionImportStatsOpts
> InlinerFunctionImportStats
;
52 void DefaultInlineAdvice::recordUnsuccessfulInliningImpl(
53 const InlineResult
&Result
) {
55 llvm::setInlineRemark(*OriginalCB
, std::string(Result
.getFailureReason()) +
56 "; " + inlineCostStr(*OIC
));
58 return OptimizationRemarkMissed(DEBUG_TYPE
, "NotInlined", DLoc
, Block
)
59 << "'" << NV("Callee", Callee
) << "' is not inlined into '"
60 << "'" << NV("Caller", Caller
)
61 << "': " << NV("Reason", Result
.getFailureReason());
65 void DefaultInlineAdvice::recordInliningWithCalleeDeletedImpl() {
67 emitInlinedInto(ORE
, DLoc
, Block
, *Callee
, *Caller
, *OIC
);
70 void DefaultInlineAdvice::recordInliningImpl() {
72 emitInlinedInto(ORE
, DLoc
, Block
, *Callee
, *Caller
, *OIC
);
75 llvm::Optional
<llvm::InlineCost
> static getDefaultInlineAdvice(
76 CallBase
&CB
, FunctionAnalysisManager
&FAM
, const InlineParams
&Params
) {
77 Function
&Caller
= *CB
.getCaller();
78 ProfileSummaryInfo
*PSI
=
79 FAM
.getResult
<ModuleAnalysisManagerFunctionProxy
>(Caller
)
80 .getCachedResult
<ProfileSummaryAnalysis
>(
81 *CB
.getParent()->getParent()->getParent());
83 auto &ORE
= FAM
.getResult
<OptimizationRemarkEmitterAnalysis
>(Caller
);
84 auto GetAssumptionCache
= [&](Function
&F
) -> AssumptionCache
& {
85 return FAM
.getResult
<AssumptionAnalysis
>(F
);
87 auto GetBFI
= [&](Function
&F
) -> BlockFrequencyInfo
& {
88 return FAM
.getResult
<BlockFrequencyAnalysis
>(F
);
90 auto GetTLI
= [&](Function
&F
) -> const TargetLibraryInfo
& {
91 return FAM
.getResult
<TargetLibraryAnalysis
>(F
);
94 auto GetInlineCost
= [&](CallBase
&CB
) {
95 Function
&Callee
= *CB
.getCalledFunction();
96 auto &CalleeTTI
= FAM
.getResult
<TargetIRAnalysis
>(Callee
);
98 Callee
.getContext().getDiagHandlerPtr()->isMissedOptRemarkEnabled(
100 return getInlineCost(CB
, Params
, CalleeTTI
, GetAssumptionCache
, GetTLI
,
101 GetBFI
, PSI
, RemarksEnabled
? &ORE
: nullptr);
103 return llvm::shouldInline(CB
, GetInlineCost
, ORE
,
104 Params
.EnableDeferral
.getValueOr(false));
107 std::unique_ptr
<InlineAdvice
>
108 DefaultInlineAdvisor::getAdviceImpl(CallBase
&CB
) {
109 auto OIC
= getDefaultInlineAdvice(CB
, FAM
, Params
);
110 return std::make_unique
<DefaultInlineAdvice
>(
112 FAM
.getResult
<OptimizationRemarkEmitterAnalysis
>(*CB
.getCaller()));
115 InlineAdvice::InlineAdvice(InlineAdvisor
*Advisor
, CallBase
&CB
,
116 OptimizationRemarkEmitter
&ORE
,
117 bool IsInliningRecommended
)
118 : Advisor(Advisor
), Caller(CB
.getCaller()), Callee(CB
.getCalledFunction()),
119 DLoc(CB
.getDebugLoc()), Block(CB
.getParent()), ORE(ORE
),
120 IsInliningRecommended(IsInliningRecommended
) {}
122 void InlineAdvisor::markFunctionAsDeleted(Function
*F
) {
123 assert((!DeletedFunctions
.count(F
)) &&
124 "Cannot put cause a function to become dead twice!");
125 DeletedFunctions
.insert(F
);
128 void InlineAdvisor::freeDeletedFunctions() {
129 for (auto *F
: DeletedFunctions
)
131 DeletedFunctions
.clear();
134 void InlineAdvice::recordInlineStatsIfNeeded() {
135 if (Advisor
->ImportedFunctionsStats
)
136 Advisor
->ImportedFunctionsStats
->recordInline(*Caller
, *Callee
);
139 void InlineAdvice::recordInlining() {
141 recordInlineStatsIfNeeded();
142 recordInliningImpl();
145 void InlineAdvice::recordInliningWithCalleeDeleted() {
147 recordInlineStatsIfNeeded();
148 Advisor
->markFunctionAsDeleted(Callee
);
149 recordInliningWithCalleeDeletedImpl();
152 AnalysisKey
InlineAdvisorAnalysis::Key
;
154 bool InlineAdvisorAnalysis::Result::tryCreate(InlineParams Params
,
155 InliningAdvisorMode Mode
,
156 StringRef ReplayFile
) {
157 auto &FAM
= MAM
.getResult
<FunctionAnalysisManagerModuleProxy
>(M
).getManager();
159 case InliningAdvisorMode::Default
:
160 LLVM_DEBUG(dbgs() << "Using default inliner heuristic.\n");
161 Advisor
.reset(new DefaultInlineAdvisor(M
, FAM
, Params
));
162 // Restrict replay to default advisor, ML advisors are stateful so
163 // replay will need augmentations to interleave with them correctly.
164 if (!ReplayFile
.empty()) {
165 Advisor
= std::make_unique
<ReplayInlineAdvisor
>(
166 M
, FAM
, M
.getContext(), std::move(Advisor
), ReplayFile
,
167 /* EmitRemarks =*/true);
170 case InliningAdvisorMode::Development
:
171 #ifdef LLVM_HAVE_TF_API
172 LLVM_DEBUG(dbgs() << "Using development-mode inliner policy.\n");
174 llvm::getDevelopmentModeAdvisor(M
, MAM
, [&FAM
, Params
](CallBase
&CB
) {
175 auto OIC
= getDefaultInlineAdvice(CB
, FAM
, Params
);
176 return OIC
.hasValue();
180 case InliningAdvisorMode::Release
:
181 #ifdef LLVM_HAVE_TF_AOT
182 LLVM_DEBUG(dbgs() << "Using release-mode inliner policy.\n");
183 Advisor
= llvm::getReleaseModeAdvisor(M
, MAM
);
191 /// Return true if inlining of CB can block the caller from being
192 /// inlined which is proved to be more beneficial. \p IC is the
193 /// estimated inline cost associated with callsite \p CB.
194 /// \p TotalSecondaryCost will be set to the estimated cost of inlining the
195 /// caller if \p CB is suppressed for inlining.
197 shouldBeDeferred(Function
*Caller
, InlineCost IC
, int &TotalSecondaryCost
,
198 function_ref
<InlineCost(CallBase
&CB
)> GetInlineCost
) {
199 // For now we only handle local or inline functions.
200 if (!Caller
->hasLocalLinkage() && !Caller
->hasLinkOnceODRLinkage())
202 // If the cost of inlining CB is non-positive, it is not going to prevent the
203 // caller from being inlined into its callers and hence we don't need to
205 if (IC
.getCost() <= 0)
207 // Try to detect the case where the current inlining candidate caller (call
208 // it B) is a static or linkonce-ODR function and is an inlining candidate
209 // elsewhere, and the current candidate callee (call it C) is large enough
210 // that inlining it into B would make B too big to inline later. In these
211 // circumstances it may be best not to inline C into B, but to inline B into
214 // This only applies to static and linkonce-ODR functions because those are
215 // expected to be available for inlining in the translation units where they
216 // are used. Thus we will always have the opportunity to make local inlining
217 // decisions. Importantly the linkonce-ODR linkage covers inline functions
218 // and templates in C++.
220 // FIXME: All of this logic should be sunk into getInlineCost. It relies on
221 // the internal implementation of the inline cost metrics rather than
222 // treating them as truly abstract units etc.
223 TotalSecondaryCost
= 0;
224 // The candidate cost to be imposed upon the current function.
225 int CandidateCost
= IC
.getCost() - 1;
226 // If the caller has local linkage and can be inlined to all its callers, we
227 // can apply a huge negative bonus to TotalSecondaryCost.
228 bool ApplyLastCallBonus
= Caller
->hasLocalLinkage() && !Caller
->hasOneUse();
229 // This bool tracks what happens if we DO inline C into B.
230 bool InliningPreventsSomeOuterInline
= false;
231 unsigned NumCallerUsers
= 0;
232 for (User
*U
: Caller
->users()) {
233 CallBase
*CS2
= dyn_cast
<CallBase
>(U
);
235 // If this isn't a call to Caller (it could be some other sort
236 // of reference) skip it. Such references will prevent the caller
237 // from being removed.
238 if (!CS2
|| CS2
->getCalledFunction() != Caller
) {
239 ApplyLastCallBonus
= false;
243 InlineCost IC2
= GetInlineCost(*CS2
);
244 ++NumCallerCallersAnalyzed
;
246 ApplyLastCallBonus
= false;
252 // See if inlining of the original callsite would erase the cost delta of
253 // this callsite. We subtract off the penalty for the call instruction,
254 // which we would be deleting.
255 if (IC2
.getCostDelta() <= CandidateCost
) {
256 InliningPreventsSomeOuterInline
= true;
257 TotalSecondaryCost
+= IC2
.getCost();
262 if (!InliningPreventsSomeOuterInline
)
265 // If all outer calls to Caller would get inlined, the cost for the last
266 // one is set very low by getInlineCost, in anticipation that Caller will
267 // be removed entirely. We did not account for this above unless there
268 // is only one caller of Caller.
269 if (ApplyLastCallBonus
)
270 TotalSecondaryCost
-= InlineConstants::LastCallToStaticBonus
;
272 // If InlineDeferralScale is negative, then ignore the cost of primary
273 // inlining -- IC.getCost() multiplied by the number of callers to Caller.
274 if (InlineDeferralScale
< 0)
275 return TotalSecondaryCost
< IC
.getCost();
277 int TotalCost
= TotalSecondaryCost
+ IC
.getCost() * NumCallerUsers
;
278 int Allowance
= IC
.getCost() * InlineDeferralScale
;
279 return TotalCost
< Allowance
;
283 static raw_ostream
&operator<<(raw_ostream
&R
, const ore::NV
&Arg
) {
287 template <class RemarkT
>
288 RemarkT
&operator<<(RemarkT
&&R
, const InlineCost
&IC
) {
291 R
<< "(cost=always)";
292 } else if (IC
.isNever()) {
295 R
<< "(cost=" << ore::NV("Cost", IC
.getCost())
296 << ", threshold=" << ore::NV("Threshold", IC
.getThreshold()) << ")";
298 if (const char *Reason
= IC
.getReason())
299 R
<< ": " << ore::NV("Reason", Reason
);
304 std::string
llvm::inlineCostStr(const InlineCost
&IC
) {
306 raw_string_ostream
Remark(Buffer
);
311 void llvm::setInlineRemark(CallBase
&CB
, StringRef Message
) {
312 if (!InlineRemarkAttribute
)
315 Attribute Attr
= Attribute::get(CB
.getContext(), "inline-remark", Message
);
319 /// Return the cost only if the inliner should attempt to inline at the given
320 /// CallSite. If we return the cost, we will emit an optimisation remark later
321 /// using that cost, so we won't do so from this function. Return None if
322 /// inlining should not be attempted.
324 llvm::shouldInline(CallBase
&CB
,
325 function_ref
<InlineCost(CallBase
&CB
)> GetInlineCost
,
326 OptimizationRemarkEmitter
&ORE
, bool EnableDeferral
) {
329 InlineCost IC
= GetInlineCost(CB
);
330 Instruction
*Call
= &CB
;
331 Function
*Callee
= CB
.getCalledFunction();
332 Function
*Caller
= CB
.getCaller();
335 LLVM_DEBUG(dbgs() << " Inlining " << inlineCostStr(IC
)
336 << ", Call: " << CB
<< "\n");
341 LLVM_DEBUG(dbgs() << " NOT Inlining " << inlineCostStr(IC
)
342 << ", Call: " << CB
<< "\n");
345 return OptimizationRemarkMissed(DEBUG_TYPE
, "NeverInline", Call
)
346 << "'" << NV("Callee", Callee
) << "' not inlined into '"
347 << NV("Caller", Caller
)
348 << "' because it should never be inlined " << IC
;
352 return OptimizationRemarkMissed(DEBUG_TYPE
, "TooCostly", Call
)
353 << "'" << NV("Callee", Callee
) << "' not inlined into '"
354 << NV("Caller", Caller
) << "' because too costly to inline "
358 setInlineRemark(CB
, inlineCostStr(IC
));
362 int TotalSecondaryCost
= 0;
363 if (EnableDeferral
&&
364 shouldBeDeferred(Caller
, IC
, TotalSecondaryCost
, GetInlineCost
)) {
365 LLVM_DEBUG(dbgs() << " NOT Inlining: " << CB
366 << " Cost = " << IC
.getCost()
367 << ", outer Cost = " << TotalSecondaryCost
<< '\n');
369 return OptimizationRemarkMissed(DEBUG_TYPE
, "IncreaseCostInOtherContexts",
371 << "Not inlining. Cost of inlining '" << NV("Callee", Callee
)
372 << "' increases the cost of inlining '" << NV("Caller", Caller
)
373 << "' in other contexts";
375 setInlineRemark(CB
, "deferred");
376 // IC does not bool() to false, so get an InlineCost that will.
377 // This will not be inspected to make an error message.
381 LLVM_DEBUG(dbgs() << " Inlining " << inlineCostStr(IC
) << ", Call: " << CB
386 std::string
llvm::getCallSiteLocation(DebugLoc DLoc
) {
388 raw_string_ostream
CallSiteLoc(Buffer
);
390 for (DILocation
*DIL
= DLoc
.get(); DIL
; DIL
= DIL
->getInlinedAt()) {
392 CallSiteLoc
<< " @ ";
393 // Note that negative line offset is actually possible, but we use
394 // unsigned int to match line offset representation in remarks so
395 // it's directly consumable by relay advisor.
397 DIL
->getLine() - DIL
->getScope()->getSubprogram()->getLine();
398 uint32_t Discriminator
= DIL
->getBaseDiscriminator();
399 StringRef Name
= DIL
->getScope()->getSubprogram()->getLinkageName();
401 Name
= DIL
->getScope()->getSubprogram()->getName();
402 CallSiteLoc
<< Name
.str() << ":" << llvm::utostr(Offset
) << ":"
403 << llvm::utostr(DIL
->getColumn());
405 CallSiteLoc
<< "." << llvm::utostr(Discriminator
);
409 return CallSiteLoc
.str();
412 void llvm::addLocationToRemarks(OptimizationRemark
&Remark
, DebugLoc DLoc
) {
418 Remark
<< " at callsite ";
419 for (DILocation
*DIL
= DLoc
.get(); DIL
; DIL
= DIL
->getInlinedAt()) {
422 unsigned int Offset
= DIL
->getLine();
423 Offset
-= DIL
->getScope()->getSubprogram()->getLine();
424 unsigned int Discriminator
= DIL
->getBaseDiscriminator();
425 StringRef Name
= DIL
->getScope()->getSubprogram()->getLinkageName();
427 Name
= DIL
->getScope()->getSubprogram()->getName();
428 Remark
<< Name
<< ":" << ore::NV("Line", Offset
) << ":"
429 << ore::NV("Column", DIL
->getColumn());
431 Remark
<< "." << ore::NV("Disc", Discriminator
);
438 void llvm::emitInlinedInto(OptimizationRemarkEmitter
&ORE
, DebugLoc DLoc
,
439 const BasicBlock
*Block
, const Function
&Callee
,
440 const Function
&Caller
, const InlineCost
&IC
,
441 bool ForProfileContext
, const char *PassName
) {
443 bool AlwaysInline
= IC
.isAlways();
444 StringRef RemarkName
= AlwaysInline
? "AlwaysInline" : "Inlined";
445 OptimizationRemark
Remark(PassName
? PassName
: DEBUG_TYPE
, RemarkName
,
447 Remark
<< "'" << ore::NV("Callee", &Callee
) << "' inlined into '"
448 << ore::NV("Caller", &Caller
) << "'";
449 if (ForProfileContext
)
450 Remark
<< " to match profiling context";
451 Remark
<< " with " << IC
;
452 addLocationToRemarks(Remark
, DLoc
);
457 InlineAdvisor::InlineAdvisor(Module
&M
, FunctionAnalysisManager
&FAM
)
459 if (InlinerFunctionImportStats
!= InlinerFunctionImportStatsOpts::No
) {
460 ImportedFunctionsStats
=
461 std::make_unique
<ImportedFunctionsInliningStatistics
>();
462 ImportedFunctionsStats
->setModuleInfo(M
);
466 InlineAdvisor::~InlineAdvisor() {
467 if (ImportedFunctionsStats
) {
468 assert(InlinerFunctionImportStats
!= InlinerFunctionImportStatsOpts::No
);
469 ImportedFunctionsStats
->dump(InlinerFunctionImportStats
==
470 InlinerFunctionImportStatsOpts::Verbose
);
473 freeDeletedFunctions();
476 std::unique_ptr
<InlineAdvice
> InlineAdvisor::getMandatoryAdvice(CallBase
&CB
,
478 return std::make_unique
<InlineAdvice
>(this, CB
, getCallerORE(CB
), Advice
);
481 InlineAdvisor::MandatoryInliningKind
482 InlineAdvisor::getMandatoryKind(CallBase
&CB
, FunctionAnalysisManager
&FAM
,
483 OptimizationRemarkEmitter
&ORE
) {
484 auto &Callee
= *CB
.getCalledFunction();
486 auto GetTLI
= [&](Function
&F
) -> const TargetLibraryInfo
& {
487 return FAM
.getResult
<TargetLibraryAnalysis
>(F
);
490 auto &TIR
= FAM
.getResult
<TargetIRAnalysis
>(Callee
);
492 auto TrivialDecision
=
493 llvm::getAttributeBasedInliningDecision(CB
, &Callee
, TIR
, GetTLI
);
495 if (TrivialDecision
.hasValue()) {
496 if (TrivialDecision
->isSuccess())
497 return MandatoryInliningKind::Always
;
499 return MandatoryInliningKind::Never
;
501 return MandatoryInliningKind::NotMandatory
;
504 std::unique_ptr
<InlineAdvice
> InlineAdvisor::getAdvice(CallBase
&CB
,
505 bool MandatoryOnly
) {
507 return getAdviceImpl(CB
);
508 bool Advice
= CB
.getCaller() != CB
.getCalledFunction() &&
509 MandatoryInliningKind::Always
==
510 getMandatoryKind(CB
, FAM
, getCallerORE(CB
));
511 return getMandatoryAdvice(CB
, Advice
);
514 OptimizationRemarkEmitter
&InlineAdvisor::getCallerORE(CallBase
&CB
) {
515 return FAM
.getResult
<OptimizationRemarkEmitterAnalysis
>(*CB
.getCaller());