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