1 //===- InlineAdvisor.cpp - analysis pass implementation -------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements InlineAdvisorAnalysis and DefaultInlineAdvisor, and
10 // related types.
11 //
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"
21 #include "llvm/IR/DebugInfoMetadata.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/raw_ostream.h"
25 
26 #include <sstream>
27 
28 using 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.
34 STATISTIC(NumCallerCallersAnalyzed, "Number of caller-callers analyzed");
35 
36 /// Flag to add inline messages as callsite attributes 'inline-remark'.
37 static 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.
46 static cl::opt<int>
47     InlineDeferralScale("inline-deferral-scale",
48                         cl::desc("Scale to limit the cost of inline deferral"),
49                         cl::init(2), cl::Hidden);
50 
51 namespace {
52 class DefaultInlineAdvice : public InlineAdvice {
53 public:
54   DefaultInlineAdvice(DefaultInlineAdvisor *Advisor, CallBase &CB,
55                       Optional<InlineCost> OIC, OptimizationRemarkEmitter &ORE)
56       : InlineAdvice(Advisor, CB, ORE, OIC.hasValue()), OriginalCB(&CB),
57         OIC(OIC) {}
58 
59 private:
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 
80 private:
81   CallBase *const OriginalCB;
82   Optional<InlineCost> OIC;
83 };
84 
85 } // namespace
86 
87 std::unique_ptr<InlineAdvice> DefaultInlineAdvisor::getAdvice(CallBase &CB) {
88   Function &Caller = *CB.getCaller();
89   ProfileSummaryInfo *PSI =
90       FAM.getResult<ModuleAnalysisManagerFunctionProxy>(Caller)
91           .getCachedResult<ProfileSummaryAnalysis>(
92               *CB.getParent()->getParent()->getParent());
93 
94   auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(Caller);
95   auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
96     return FAM.getResult<AssumptionAnalysis>(F);
97   };
98   auto GetBFI = [&](Function &F) -> BlockFrequencyInfo & {
99     return FAM.getResult<BlockFrequencyAnalysis>(F);
100   };
101   auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & {
102     return FAM.getResult<TargetLibraryAnalysis>(F);
103   };
104 
105   auto GetInlineCost = [&](CallBase &CB) {
106     Function &Callee = *CB.getCalledFunction();
107     auto &CalleeTTI = FAM.getResult<TargetIRAnalysis>(Callee);
108     bool RemarksEnabled =
109         Callee.getContext().getDiagHandlerPtr()->isMissedOptRemarkEnabled(
110             DEBUG_TYPE);
111     return getInlineCost(CB, Params, CalleeTTI, GetAssumptionCache, GetTLI,
112                          GetBFI, PSI, RemarksEnabled ? &ORE : nullptr);
113   };
114   auto OIC = llvm::shouldInline(CB, GetInlineCost, ORE,
115                                 Params.EnableDeferral.hasValue() &&
116                                     Params.EnableDeferral.getValue());
117   return std::make_unique<DefaultInlineAdvice>(this, CB, OIC, ORE);
118 }
119 
120 InlineAdvice::InlineAdvice(InlineAdvisor *Advisor, CallBase &CB,
121                            OptimizationRemarkEmitter &ORE,
122                            bool IsInliningRecommended)
123     : Advisor(Advisor), Caller(CB.getCaller()), Callee(CB.getCalledFunction()),
124       DLoc(CB.getDebugLoc()), Block(CB.getParent()), ORE(ORE),
125       IsInliningRecommended(IsInliningRecommended) {}
126 
127 void InlineAdvisor::markFunctionAsDeleted(Function *F) {
128   assert((!DeletedFunctions.count(F)) &&
129          "Cannot put cause a function to become dead twice!");
130   DeletedFunctions.insert(F);
131 }
132 
133 void InlineAdvisor::freeDeletedFunctions() {
134   for (auto *F : DeletedFunctions)
135     delete F;
136   DeletedFunctions.clear();
137 }
138 
139 void InlineAdvice::recordInliningWithCalleeDeleted() {
140   markRecorded();
141   Advisor->markFunctionAsDeleted(Callee);
142   recordInliningWithCalleeDeletedImpl();
143 }
144 
145 AnalysisKey InlineAdvisorAnalysis::Key;
146 
147 bool InlineAdvisorAnalysis::Result::tryCreate(InlineParams Params,
148                                               InliningAdvisorMode Mode) {
149   auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
150   switch (Mode) {
151   case InliningAdvisorMode::Default:
152     Advisor.reset(new DefaultInlineAdvisor(FAM, Params));
153     break;
154   case InliningAdvisorMode::Development:
155     // To be added subsequently under conditional compilation.
156     break;
157   case InliningAdvisorMode::Release:
158     // To be added subsequently under conditional compilation.
159     break;
160   }
161   return !!Advisor;
162 }
163 
164 /// Return true if inlining of CB can block the caller from being
165 /// inlined which is proved to be more beneficial. \p IC is the
166 /// estimated inline cost associated with callsite \p CB.
167 /// \p TotalSecondaryCost will be set to the estimated cost of inlining the
168 /// caller if \p CB is suppressed for inlining.
169 static bool
170 shouldBeDeferred(Function *Caller, InlineCost IC, int &TotalSecondaryCost,
171                  function_ref<InlineCost(CallBase &CB)> GetInlineCost) {
172   // For now we only handle local or inline functions.
173   if (!Caller->hasLocalLinkage() && !Caller->hasLinkOnceODRLinkage())
174     return false;
175   // If the cost of inlining CB is non-positive, it is not going to prevent the
176   // caller from being inlined into its callers and hence we don't need to
177   // defer.
178   if (IC.getCost() <= 0)
179     return false;
180   // Try to detect the case where the current inlining candidate caller (call
181   // it B) is a static or linkonce-ODR function and is an inlining candidate
182   // elsewhere, and the current candidate callee (call it C) is large enough
183   // that inlining it into B would make B too big to inline later. In these
184   // circumstances it may be best not to inline C into B, but to inline B into
185   // its callers.
186   //
187   // This only applies to static and linkonce-ODR functions because those are
188   // expected to be available for inlining in the translation units where they
189   // are used. Thus we will always have the opportunity to make local inlining
190   // decisions. Importantly the linkonce-ODR linkage covers inline functions
191   // and templates in C++.
192   //
193   // FIXME: All of this logic should be sunk into getInlineCost. It relies on
194   // the internal implementation of the inline cost metrics rather than
195   // treating them as truly abstract units etc.
196   TotalSecondaryCost = 0;
197   // The candidate cost to be imposed upon the current function.
198   int CandidateCost = IC.getCost() - 1;
199   // If the caller has local linkage and can be inlined to all its callers, we
200   // can apply a huge negative bonus to TotalSecondaryCost.
201   bool ApplyLastCallBonus = Caller->hasLocalLinkage() && !Caller->hasOneUse();
202   // This bool tracks what happens if we DO inline C into B.
203   bool InliningPreventsSomeOuterInline = false;
204   unsigned NumCallerUsers = 0;
205   for (User *U : Caller->users()) {
206     CallBase *CS2 = dyn_cast<CallBase>(U);
207 
208     // If this isn't a call to Caller (it could be some other sort
209     // of reference) skip it.  Such references will prevent the caller
210     // from being removed.
211     if (!CS2 || CS2->getCalledFunction() != Caller) {
212       ApplyLastCallBonus = false;
213       continue;
214     }
215 
216     InlineCost IC2 = GetInlineCost(*CS2);
217     ++NumCallerCallersAnalyzed;
218     if (!IC2) {
219       ApplyLastCallBonus = false;
220       continue;
221     }
222     if (IC2.isAlways())
223       continue;
224 
225     // See if inlining of the original callsite would erase the cost delta of
226     // this callsite. We subtract off the penalty for the call instruction,
227     // which we would be deleting.
228     if (IC2.getCostDelta() <= CandidateCost) {
229       InliningPreventsSomeOuterInline = true;
230       TotalSecondaryCost += IC2.getCost();
231       NumCallerUsers++;
232     }
233   }
234 
235   if (!InliningPreventsSomeOuterInline)
236     return false;
237 
238   // If all outer calls to Caller would get inlined, the cost for the last
239   // one is set very low by getInlineCost, in anticipation that Caller will
240   // be removed entirely.  We did not account for this above unless there
241   // is only one caller of Caller.
242   if (ApplyLastCallBonus)
243     TotalSecondaryCost -= InlineConstants::LastCallToStaticBonus;
244 
245   // If InlineDeferralScale is negative, then ignore the cost of primary
246   // inlining -- IC.getCost() multiplied by the number of callers to Caller.
247   if (InlineDeferralScale < 0)
248     return TotalSecondaryCost < IC.getCost();
249 
250   int TotalCost = TotalSecondaryCost + IC.getCost() * NumCallerUsers;
251   int Allowance = IC.getCost() * InlineDeferralScale;
252   return TotalCost < Allowance;
253 }
254 
255 namespace llvm {
256 static std::basic_ostream<char> &operator<<(std::basic_ostream<char> &R,
257                                             const ore::NV &Arg) {
258   return R << Arg.Val;
259 }
260 
261 template <class RemarkT>
262 RemarkT &operator<<(RemarkT &&R, const InlineCost &IC) {
263   using namespace ore;
264   if (IC.isAlways()) {
265     R << "(cost=always)";
266   } else if (IC.isNever()) {
267     R << "(cost=never)";
268   } else {
269     R << "(cost=" << ore::NV("Cost", IC.getCost())
270       << ", threshold=" << ore::NV("Threshold", IC.getThreshold()) << ")";
271   }
272   if (const char *Reason = IC.getReason())
273     R << ": " << ore::NV("Reason", Reason);
274   return R;
275 }
276 } // namespace llvm
277 
278 std::string llvm::inlineCostStr(const InlineCost &IC) {
279   std::stringstream Remark;
280   Remark << IC;
281   return Remark.str();
282 }
283 
284 void llvm::setInlineRemark(CallBase &CB, StringRef Message) {
285   if (!InlineRemarkAttribute)
286     return;
287 
288   Attribute Attr = Attribute::get(CB.getContext(), "inline-remark", Message);
289   CB.addAttribute(AttributeList::FunctionIndex, Attr);
290 }
291 
292 /// Return the cost only if the inliner should attempt to inline at the given
293 /// CallSite. If we return the cost, we will emit an optimisation remark later
294 /// using that cost, so we won't do so from this function. Return None if
295 /// inlining should not be attempted.
296 Optional<InlineCost>
297 llvm::shouldInline(CallBase &CB,
298                    function_ref<InlineCost(CallBase &CB)> GetInlineCost,
299                    OptimizationRemarkEmitter &ORE, bool EnableDeferral) {
300   using namespace ore;
301 
302   InlineCost IC = GetInlineCost(CB);
303   Instruction *Call = &CB;
304   Function *Callee = CB.getCalledFunction();
305   Function *Caller = CB.getCaller();
306 
307   if (IC.isAlways()) {
308     LLVM_DEBUG(dbgs() << "    Inlining " << inlineCostStr(IC)
309                       << ", Call: " << CB << "\n");
310     return IC;
311   }
312 
313   if (!IC) {
314     LLVM_DEBUG(dbgs() << "    NOT Inlining " << inlineCostStr(IC)
315                       << ", Call: " << CB << "\n");
316     if (IC.isNever()) {
317       ORE.emit([&]() {
318         return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline", Call)
319                << NV("Callee", Callee) << " not inlined into "
320                << NV("Caller", Caller) << " because it should never be inlined "
321                << IC;
322       });
323     } else {
324       ORE.emit([&]() {
325         return OptimizationRemarkMissed(DEBUG_TYPE, "TooCostly", Call)
326                << NV("Callee", Callee) << " not inlined into "
327                << NV("Caller", Caller) << " because too costly to inline "
328                << IC;
329       });
330     }
331     setInlineRemark(CB, inlineCostStr(IC));
332     return None;
333   }
334 
335   int TotalSecondaryCost = 0;
336   if (EnableDeferral &&
337       shouldBeDeferred(Caller, IC, TotalSecondaryCost, GetInlineCost)) {
338     LLVM_DEBUG(dbgs() << "    NOT Inlining: " << CB
339                       << " Cost = " << IC.getCost()
340                       << ", outer Cost = " << TotalSecondaryCost << '\n');
341     ORE.emit([&]() {
342       return OptimizationRemarkMissed(DEBUG_TYPE, "IncreaseCostInOtherContexts",
343                                       Call)
344              << "Not inlining. Cost of inlining " << NV("Callee", Callee)
345              << " increases the cost of inlining " << NV("Caller", Caller)
346              << " in other contexts";
347     });
348     setInlineRemark(CB, "deferred");
349     // IC does not bool() to false, so get an InlineCost that will.
350     // This will not be inspected to make an error message.
351     return None;
352   }
353 
354   LLVM_DEBUG(dbgs() << "    Inlining " << inlineCostStr(IC) << ", Call: " << CB
355                     << '\n');
356   return IC;
357 }
358 
359 void llvm::addLocationToRemarks(OptimizationRemark &Remark, DebugLoc DLoc) {
360   if (!DLoc.get())
361     return;
362 
363   bool First = true;
364   Remark << " at callsite ";
365   for (DILocation *DIL = DLoc.get(); DIL; DIL = DIL->getInlinedAt()) {
366     if (!First)
367       Remark << " @ ";
368     unsigned int Offset = DIL->getLine();
369     Offset -= DIL->getScope()->getSubprogram()->getLine();
370     unsigned int Discriminator = DIL->getBaseDiscriminator();
371     StringRef Name = DIL->getScope()->getSubprogram()->getLinkageName();
372     if (Name.empty())
373       Name = DIL->getScope()->getSubprogram()->getName();
374     Remark << Name << ":" << ore::NV("Line", Offset);
375     if (Discriminator)
376       Remark << "." << ore::NV("Disc", Discriminator);
377     First = false;
378   }
379 }
380 
381 void llvm::emitInlinedInto(OptimizationRemarkEmitter &ORE, DebugLoc DLoc,
382                            const BasicBlock *Block, const Function &Callee,
383                            const Function &Caller, const InlineCost &IC,
384                            bool ForProfileContext, const char *PassName) {
385   ORE.emit([&]() {
386     bool AlwaysInline = IC.isAlways();
387     StringRef RemarkName = AlwaysInline ? "AlwaysInline" : "Inlined";
388     OptimizationRemark Remark(PassName ? PassName : DEBUG_TYPE, RemarkName,
389                               DLoc, Block);
390     Remark << ore::NV("Callee", &Callee) << " inlined into ";
391     Remark << ore::NV("Caller", &Caller);
392     if (ForProfileContext)
393       Remark << " to match profiling context";
394     Remark << " with " << IC;
395     addLocationToRemarks(Remark, DLoc);
396     return Remark;
397   });
398 }
399