blob: ee92450d7e09587c12830e0237505f1a6ef65ec2 [file] [log] [blame]
Mircea Trofin48fa3552020-05-07 20:35:08 -07001//===- InlineAdvisor.cpp - analysis pass implementation -------------------===//
2//
Mircea Trofin296e4772020-06-15 16:46:21 -07003// 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
Mircea Trofin48fa3552020-05-07 20:35:08 -07006//
7//===----------------------------------------------------------------------===//
8//
Mircea Trofind6695e12020-04-28 13:25:15 -07009// This file implements InlineAdvisorAnalysis and DefaultInlineAdvisor, and
10// related types.
Mircea Trofin48fa3552020-05-07 20:35:08 -070011//
12//===----------------------------------------------------------------------===//
13
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/TargetLibraryInfo.h"
20#include "llvm/Analysis/TargetTransformInfo.h"
Wenlei He7c8a6932020-06-19 10:25:31 -070021#include "llvm/IR/DebugInfoMetadata.h"
Mircea Trofin48fa3552020-05-07 20:35:08 -070022#include "llvm/IR/Instructions.h"
Simon Pilgrimcdceef42020-06-23 12:19:09 +010023#include "llvm/Support/CommandLine.h"
Mircea Trofin48fa3552020-05-07 20:35:08 -070024#include "llvm/Support/raw_ostream.h"
25
26#include <sstream>
27
28using namespace llvm;
29#define DEBUG_TYPE "inline"
30
31// This weirdly named statistic tracks the number of times that, when attempting
32// to inline a function A into B, we analyze the callers of B in order to see
33// if those would be more profitable and blocked inline steps.
34STATISTIC(NumCallerCallersAnalyzed, "Number of caller-callers analyzed");
35
36/// Flag to add inline messages as callsite attributes 'inline-remark'.
37static cl::opt<bool>
38 InlineRemarkAttribute("inline-remark-attribute", cl::init(false),
39 cl::Hidden,
40 cl::desc("Enable adding inline-remark attribute to"
41 " callsites processed by inliner but decided"
42 " to be not inlined"));
43
44// An integer used to limit the cost of inline deferral. The default negative
45// number tells shouldBeDeferred to only take the secondary cost into account.
46static cl::opt<int>
47 InlineDeferralScale("inline-deferral-scale",
48 cl::desc("Scale to limit the cost of inline deferral"),
Kazu Hiratacec20db2020-05-25 15:43:28 -070049 cl::init(2), cl::Hidden);
Mircea Trofin48fa3552020-05-07 20:35:08 -070050
Mircea Trofind6695e12020-04-28 13:25:15 -070051namespace {
52class DefaultInlineAdvice : public InlineAdvice {
53public:
54 DefaultInlineAdvice(DefaultInlineAdvisor *Advisor, CallBase &CB,
55 Optional<InlineCost> OIC, OptimizationRemarkEmitter &ORE)
Mircea Trofine82eff72020-06-09 14:33:46 -070056 : InlineAdvice(Advisor, CB, ORE, OIC.hasValue()), OriginalCB(&CB),
57 OIC(OIC) {}
Mircea Trofind6695e12020-04-28 13:25:15 -070058
59private:
60 void recordUnsuccessfulInliningImpl(const InlineResult &Result) override {
61 using namespace ore;
62 llvm::setInlineRemark(*OriginalCB, std::string(Result.getFailureReason()) +
63 "; " + inlineCostStr(*OIC));
64 ORE.emit([&]() {
65 return OptimizationRemarkMissed(DEBUG_TYPE, "NotInlined", DLoc, Block)
66 << NV("Callee", Callee) << " will not be inlined into "
67 << NV("Caller", Caller) << ": "
68 << NV("Reason", Result.getFailureReason());
69 });
70 }
71
72 void recordInliningWithCalleeDeletedImpl() override {
73 emitInlinedInto(ORE, DLoc, Block, *Callee, *Caller, *OIC);
74 }
75
76 void recordInliningImpl() override {
77 emitInlinedInto(ORE, DLoc, Block, *Callee, *Caller, *OIC);
78 }
79
80private:
81 CallBase *const OriginalCB;
82 Optional<InlineCost> OIC;
Mircea Trofind6695e12020-04-28 13:25:15 -070083};
84
85} // namespace
86
Benjamin Kramer9a0689e2020-07-17 13:49:11 +020087llvm::Optional<llvm::InlineCost> static getDefaultInlineAdvice(
88 CallBase &CB, FunctionAnalysisManager &FAM, const InlineParams &Params) {
Mircea Trofin8a2e2a62020-05-14 15:42:26 -070089 Function &Caller = *CB.getCaller();
90 ProfileSummaryInfo *PSI =
91 FAM.getResult<ModuleAnalysisManagerFunctionProxy>(Caller)
92 .getCachedResult<ProfileSummaryAnalysis>(
93 *CB.getParent()->getParent()->getParent());
Mircea Trofind6695e12020-04-28 13:25:15 -070094
Mircea Trofin8a2e2a62020-05-14 15:42:26 -070095 auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(Caller);
Mircea Trofin08e23862020-05-14 22:38:41 -070096 auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
Mircea Trofin8a2e2a62020-05-14 15:42:26 -070097 return FAM.getResult<AssumptionAnalysis>(F);
Mircea Trofind6695e12020-04-28 13:25:15 -070098 };
99 auto GetBFI = [&](Function &F) -> BlockFrequencyInfo & {
100 return FAM.getResult<BlockFrequencyAnalysis>(F);
101 };
102 auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & {
103 return FAM.getResult<TargetLibraryAnalysis>(F);
104 };
105
106 auto GetInlineCost = [&](CallBase &CB) {
107 Function &Callee = *CB.getCalledFunction();
108 auto &CalleeTTI = FAM.getResult<TargetIRAnalysis>(Callee);
109 bool RemarksEnabled =
110 Callee.getContext().getDiagHandlerPtr()->isMissedOptRemarkEnabled(
111 DEBUG_TYPE);
Mircea Trofin08e23862020-05-14 22:38:41 -0700112 return getInlineCost(CB, Params, CalleeTTI, GetAssumptionCache, GetTLI,
113 GetBFI, PSI, RemarksEnabled ? &ORE : nullptr);
Mircea Trofind6695e12020-04-28 13:25:15 -0700114 };
Mircea Trofin11046ef2020-07-13 12:14:21 -0700115 return llvm::shouldInline(CB, GetInlineCost, ORE,
116 Params.EnableDeferral.hasValue() &&
117 Params.EnableDeferral.getValue());
118}
119
120std::unique_ptr<InlineAdvice> DefaultInlineAdvisor::getAdvice(CallBase &CB) {
121 auto OIC = getDefaultInlineAdvice(CB, FAM, Params);
122 return std::make_unique<DefaultInlineAdvice>(
123 this, CB, OIC,
124 FAM.getResult<OptimizationRemarkEmitterAnalysis>(*CB.getCaller()));
Mircea Trofind6695e12020-04-28 13:25:15 -0700125}
126
127InlineAdvice::InlineAdvice(InlineAdvisor *Advisor, CallBase &CB,
Mircea Trofine82eff72020-06-09 14:33:46 -0700128 OptimizationRemarkEmitter &ORE,
Mircea Trofind6695e12020-04-28 13:25:15 -0700129 bool IsInliningRecommended)
130 : Advisor(Advisor), Caller(CB.getCaller()), Callee(CB.getCalledFunction()),
Mircea Trofine82eff72020-06-09 14:33:46 -0700131 DLoc(CB.getDebugLoc()), Block(CB.getParent()), ORE(ORE),
Mircea Trofind6695e12020-04-28 13:25:15 -0700132 IsInliningRecommended(IsInliningRecommended) {}
133
134void InlineAdvisor::markFunctionAsDeleted(Function *F) {
135 assert((!DeletedFunctions.count(F)) &&
136 "Cannot put cause a function to become dead twice!");
137 DeletedFunctions.insert(F);
138}
139
140void InlineAdvisor::freeDeletedFunctions() {
141 for (auto *F : DeletedFunctions)
142 delete F;
143 DeletedFunctions.clear();
144}
145
146void InlineAdvice::recordInliningWithCalleeDeleted() {
147 markRecorded();
148 Advisor->markFunctionAsDeleted(Callee);
149 recordInliningWithCalleeDeletedImpl();
150}
151
152AnalysisKey InlineAdvisorAnalysis::Key;
153
154bool InlineAdvisorAnalysis::Result::tryCreate(InlineParams Params,
155 InliningAdvisorMode Mode) {
Mircea Trofin999ea252020-05-21 08:40:49 -0700156 auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
Mircea Trofind6695e12020-04-28 13:25:15 -0700157 switch (Mode) {
158 case InliningAdvisorMode::Default:
Mircea Trofin999ea252020-05-21 08:40:49 -0700159 Advisor.reset(new DefaultInlineAdvisor(FAM, Params));
Mircea Trofind6695e12020-04-28 13:25:15 -0700160 break;
161 case InliningAdvisorMode::Development:
Mircea Trofin70f8d0a2020-07-08 18:55:36 -0700162#ifdef LLVM_HAVE_TF_API
163 Advisor =
164 llvm::getDevelopmentModeAdvisor(M, MAM, [&FAM, Params](CallBase &CB) {
165 auto OIC = getDefaultInlineAdvice(CB, FAM, Params);
166 return OIC.hasValue();
167 });
168#endif
Mircea Trofind6695e12020-04-28 13:25:15 -0700169 break;
170 case InliningAdvisorMode::Release:
Mircea Trofinbdceefe2020-06-09 14:50:50 -0700171#ifdef LLVM_HAVE_TF_AOT
172 Advisor = llvm::getReleaseModeAdvisor(M, MAM);
173#endif
Mircea Trofind6695e12020-04-28 13:25:15 -0700174 break;
175 }
176 return !!Advisor;
177}
178
Mircea Trofin48fa3552020-05-07 20:35:08 -0700179/// Return true if inlining of CB can block the caller from being
180/// inlined which is proved to be more beneficial. \p IC is the
181/// estimated inline cost associated with callsite \p CB.
182/// \p TotalSecondaryCost will be set to the estimated cost of inlining the
183/// caller if \p CB is suppressed for inlining.
Kazu Hirata0205fab2020-05-11 14:04:10 -0700184static bool
185shouldBeDeferred(Function *Caller, InlineCost IC, int &TotalSecondaryCost,
186 function_ref<InlineCost(CallBase &CB)> GetInlineCost) {
Mircea Trofin48fa3552020-05-07 20:35:08 -0700187 // For now we only handle local or inline functions.
188 if (!Caller->hasLocalLinkage() && !Caller->hasLinkOnceODRLinkage())
189 return false;
190 // If the cost of inlining CB is non-positive, it is not going to prevent the
191 // caller from being inlined into its callers and hence we don't need to
192 // defer.
193 if (IC.getCost() <= 0)
194 return false;
195 // Try to detect the case where the current inlining candidate caller (call
196 // it B) is a static or linkonce-ODR function and is an inlining candidate
197 // elsewhere, and the current candidate callee (call it C) is large enough
198 // that inlining it into B would make B too big to inline later. In these
199 // circumstances it may be best not to inline C into B, but to inline B into
200 // its callers.
201 //
202 // This only applies to static and linkonce-ODR functions because those are
203 // expected to be available for inlining in the translation units where they
204 // are used. Thus we will always have the opportunity to make local inlining
205 // decisions. Importantly the linkonce-ODR linkage covers inline functions
206 // and templates in C++.
207 //
208 // FIXME: All of this logic should be sunk into getInlineCost. It relies on
209 // the internal implementation of the inline cost metrics rather than
210 // treating them as truly abstract units etc.
211 TotalSecondaryCost = 0;
212 // The candidate cost to be imposed upon the current function.
213 int CandidateCost = IC.getCost() - 1;
214 // If the caller has local linkage and can be inlined to all its callers, we
215 // can apply a huge negative bonus to TotalSecondaryCost.
216 bool ApplyLastCallBonus = Caller->hasLocalLinkage() && !Caller->hasOneUse();
217 // This bool tracks what happens if we DO inline C into B.
218 bool InliningPreventsSomeOuterInline = false;
219 unsigned NumCallerUsers = 0;
220 for (User *U : Caller->users()) {
221 CallBase *CS2 = dyn_cast<CallBase>(U);
222
223 // If this isn't a call to Caller (it could be some other sort
224 // of reference) skip it. Such references will prevent the caller
225 // from being removed.
226 if (!CS2 || CS2->getCalledFunction() != Caller) {
227 ApplyLastCallBonus = false;
228 continue;
229 }
230
231 InlineCost IC2 = GetInlineCost(*CS2);
232 ++NumCallerCallersAnalyzed;
233 if (!IC2) {
234 ApplyLastCallBonus = false;
235 continue;
236 }
237 if (IC2.isAlways())
238 continue;
239
240 // See if inlining of the original callsite would erase the cost delta of
241 // this callsite. We subtract off the penalty for the call instruction,
242 // which we would be deleting.
243 if (IC2.getCostDelta() <= CandidateCost) {
244 InliningPreventsSomeOuterInline = true;
245 TotalSecondaryCost += IC2.getCost();
246 NumCallerUsers++;
247 }
248 }
249
250 if (!InliningPreventsSomeOuterInline)
251 return false;
252
253 // If all outer calls to Caller would get inlined, the cost for the last
254 // one is set very low by getInlineCost, in anticipation that Caller will
255 // be removed entirely. We did not account for this above unless there
256 // is only one caller of Caller.
257 if (ApplyLastCallBonus)
258 TotalSecondaryCost -= InlineConstants::LastCallToStaticBonus;
259
260 // If InlineDeferralScale is negative, then ignore the cost of primary
261 // inlining -- IC.getCost() multiplied by the number of callers to Caller.
262 if (InlineDeferralScale < 0)
263 return TotalSecondaryCost < IC.getCost();
264
265 int TotalCost = TotalSecondaryCost + IC.getCost() * NumCallerUsers;
266 int Allowance = IC.getCost() * InlineDeferralScale;
267 return TotalCost < Allowance;
268}
269
270namespace llvm {
271static std::basic_ostream<char> &operator<<(std::basic_ostream<char> &R,
272 const ore::NV &Arg) {
273 return R << Arg.Val;
274}
275
276template <class RemarkT>
277RemarkT &operator<<(RemarkT &&R, const InlineCost &IC) {
278 using namespace ore;
279 if (IC.isAlways()) {
280 R << "(cost=always)";
281 } else if (IC.isNever()) {
282 R << "(cost=never)";
283 } else {
284 R << "(cost=" << ore::NV("Cost", IC.getCost())
285 << ", threshold=" << ore::NV("Threshold", IC.getThreshold()) << ")";
286 }
287 if (const char *Reason = IC.getReason())
288 R << ": " << ore::NV("Reason", Reason);
289 return R;
290}
291} // namespace llvm
292
293std::string llvm::inlineCostStr(const InlineCost &IC) {
294 std::stringstream Remark;
295 Remark << IC;
296 return Remark.str();
297}
298
299void llvm::setInlineRemark(CallBase &CB, StringRef Message) {
300 if (!InlineRemarkAttribute)
301 return;
302
303 Attribute Attr = Attribute::get(CB.getContext(), "inline-remark", Message);
304 CB.addAttribute(AttributeList::FunctionIndex, Attr);
305}
306
307/// Return the cost only if the inliner should attempt to inline at the given
308/// CallSite. If we return the cost, we will emit an optimisation remark later
309/// using that cost, so we won't do so from this function. Return None if
310/// inlining should not be attempted.
311Optional<InlineCost>
312llvm::shouldInline(CallBase &CB,
313 function_ref<InlineCost(CallBase &CB)> GetInlineCost,
Kazu Hirata347a5992020-06-04 00:40:17 -0700314 OptimizationRemarkEmitter &ORE, bool EnableDeferral) {
Mircea Trofin48fa3552020-05-07 20:35:08 -0700315 using namespace ore;
316
317 InlineCost IC = GetInlineCost(CB);
318 Instruction *Call = &CB;
319 Function *Callee = CB.getCalledFunction();
320 Function *Caller = CB.getCaller();
321
322 if (IC.isAlways()) {
323 LLVM_DEBUG(dbgs() << " Inlining " << inlineCostStr(IC)
324 << ", Call: " << CB << "\n");
325 return IC;
326 }
327
328 if (!IC) {
329 LLVM_DEBUG(dbgs() << " NOT Inlining " << inlineCostStr(IC)
330 << ", Call: " << CB << "\n");
331 if (IC.isNever()) {
332 ORE.emit([&]() {
333 return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline", Call)
334 << NV("Callee", Callee) << " not inlined into "
335 << NV("Caller", Caller) << " because it should never be inlined "
336 << IC;
337 });
338 } else {
339 ORE.emit([&]() {
340 return OptimizationRemarkMissed(DEBUG_TYPE, "TooCostly", Call)
341 << NV("Callee", Callee) << " not inlined into "
342 << NV("Caller", Caller) << " because too costly to inline "
343 << IC;
344 });
345 }
346 setInlineRemark(CB, inlineCostStr(IC));
347 return None;
348 }
349
350 int TotalSecondaryCost = 0;
Kazu Hirata347a5992020-06-04 00:40:17 -0700351 if (EnableDeferral &&
352 shouldBeDeferred(Caller, IC, TotalSecondaryCost, GetInlineCost)) {
Mircea Trofin48fa3552020-05-07 20:35:08 -0700353 LLVM_DEBUG(dbgs() << " NOT Inlining: " << CB
354 << " Cost = " << IC.getCost()
355 << ", outer Cost = " << TotalSecondaryCost << '\n');
356 ORE.emit([&]() {
357 return OptimizationRemarkMissed(DEBUG_TYPE, "IncreaseCostInOtherContexts",
358 Call)
359 << "Not inlining. Cost of inlining " << NV("Callee", Callee)
360 << " increases the cost of inlining " << NV("Caller", Caller)
361 << " in other contexts";
362 });
363 setInlineRemark(CB, "deferred");
364 // IC does not bool() to false, so get an InlineCost that will.
365 // This will not be inspected to make an error message.
366 return None;
367 }
368
369 LLVM_DEBUG(dbgs() << " Inlining " << inlineCostStr(IC) << ", Call: " << CB
370 << '\n');
371 return IC;
372}
373
Wenlei He7c8a6932020-06-19 10:25:31 -0700374void llvm::addLocationToRemarks(OptimizationRemark &Remark, DebugLoc DLoc) {
375 if (!DLoc.get())
376 return;
377
378 bool First = true;
379 Remark << " at callsite ";
380 for (DILocation *DIL = DLoc.get(); DIL; DIL = DIL->getInlinedAt()) {
381 if (!First)
382 Remark << " @ ";
383 unsigned int Offset = DIL->getLine();
384 Offset -= DIL->getScope()->getSubprogram()->getLine();
385 unsigned int Discriminator = DIL->getBaseDiscriminator();
386 StringRef Name = DIL->getScope()->getSubprogram()->getLinkageName();
387 if (Name.empty())
388 Name = DIL->getScope()->getSubprogram()->getName();
389 Remark << Name << ":" << ore::NV("Line", Offset);
390 if (Discriminator)
391 Remark << "." << ore::NV("Disc", Discriminator);
392 First = false;
393 }
394}
395
Mircea Trofin48fa3552020-05-07 20:35:08 -0700396void llvm::emitInlinedInto(OptimizationRemarkEmitter &ORE, DebugLoc DLoc,
397 const BasicBlock *Block, const Function &Callee,
Wenlei He7c8a6932020-06-19 10:25:31 -0700398 const Function &Caller, const InlineCost &IC,
399 bool ForProfileContext, const char *PassName) {
Mircea Trofin48fa3552020-05-07 20:35:08 -0700400 ORE.emit([&]() {
401 bool AlwaysInline = IC.isAlways();
402 StringRef RemarkName = AlwaysInline ? "AlwaysInline" : "Inlined";
Wenlei He7c8a6932020-06-19 10:25:31 -0700403 OptimizationRemark Remark(PassName ? PassName : DEBUG_TYPE, RemarkName,
404 DLoc, Block);
405 Remark << ore::NV("Callee", &Callee) << " inlined into ";
406 Remark << ore::NV("Caller", &Caller);
407 if (ForProfileContext)
408 Remark << " to match profiling context";
409 Remark << " with " << IC;
410 addLocationToRemarks(Remark, DLoc);
411 return Remark;
Mircea Trofin48fa3552020-05-07 20:35:08 -0700412 });
413}