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 extern cl::opt<InlinerFunctionImportStatsOpts> InlinerFunctionImportStats;
52 
53 void DefaultInlineAdvice::recordUnsuccessfulInliningImpl(
54     const InlineResult &Result) {
55   using namespace ore;
56   llvm::setInlineRemark(*OriginalCB, std::string(Result.getFailureReason()) +
57                                          "; " + inlineCostStr(*OIC));
58   ORE.emit([&]() {
59     return OptimizationRemarkMissed(DEBUG_TYPE, "NotInlined", DLoc, Block)
60            << NV("Callee", Callee) << " will not be inlined into "
61            << NV("Caller", Caller) << ": "
62            << NV("Reason", Result.getFailureReason());
63   });
64 }
65 
66 void DefaultInlineAdvice::recordInliningWithCalleeDeletedImpl() {
67   if (EmitRemarks)
68     emitInlinedInto(ORE, DLoc, Block, *Callee, *Caller, *OIC);
69 }
70 
71 void DefaultInlineAdvice::recordInliningImpl() {
72   if (EmitRemarks)
73     emitInlinedInto(ORE, DLoc, Block, *Callee, *Caller, *OIC);
74 }
75 
76 llvm::Optional<llvm::InlineCost> static getDefaultInlineAdvice(
77     CallBase &CB, FunctionAnalysisManager &FAM, const InlineParams &Params) {
78   Function &Caller = *CB.getCaller();
79   ProfileSummaryInfo *PSI =
80       FAM.getResult<ModuleAnalysisManagerFunctionProxy>(Caller)
81           .getCachedResult<ProfileSummaryAnalysis>(
82               *CB.getParent()->getParent()->getParent());
83 
84   auto &ORE = FAM.getResult<OptimizationRemarkEmitterAnalysis>(Caller);
85   auto GetAssumptionCache = [&](Function &F) -> AssumptionCache & {
86     return FAM.getResult<AssumptionAnalysis>(F);
87   };
88   auto GetBFI = [&](Function &F) -> BlockFrequencyInfo & {
89     return FAM.getResult<BlockFrequencyAnalysis>(F);
90   };
91   auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & {
92     return FAM.getResult<TargetLibraryAnalysis>(F);
93   };
94 
95   auto GetInlineCost = [&](CallBase &CB) {
96     Function &Callee = *CB.getCalledFunction();
97     auto &CalleeTTI = FAM.getResult<TargetIRAnalysis>(Callee);
98     bool RemarksEnabled =
99         Callee.getContext().getDiagHandlerPtr()->isMissedOptRemarkEnabled(
100             DEBUG_TYPE);
101     return getInlineCost(CB, Params, CalleeTTI, GetAssumptionCache, GetTLI,
102                          GetBFI, PSI, RemarksEnabled ? &ORE : nullptr);
103   };
104   return llvm::shouldInline(CB, GetInlineCost, ORE,
105                             Params.EnableDeferral.getValueOr(false));
106 }
107 
108 std::unique_ptr<InlineAdvice>
109 DefaultInlineAdvisor::getAdviceImpl(CallBase &CB) {
110   auto OIC = getDefaultInlineAdvice(CB, FAM, Params);
111   return std::make_unique<DefaultInlineAdvice>(
112       this, CB, OIC,
113       FAM.getResult<OptimizationRemarkEmitterAnalysis>(*CB.getCaller()));
114 }
115 
116 InlineAdvice::InlineAdvice(InlineAdvisor *Advisor, CallBase &CB,
117                            OptimizationRemarkEmitter &ORE,
118                            bool IsInliningRecommended)
119     : Advisor(Advisor), Caller(CB.getCaller()), Callee(CB.getCalledFunction()),
120       DLoc(CB.getDebugLoc()), Block(CB.getParent()), ORE(ORE),
121       IsInliningRecommended(IsInliningRecommended) {}
122 
123 void InlineAdvisor::markFunctionAsDeleted(Function *F) {
124   assert((!DeletedFunctions.count(F)) &&
125          "Cannot put cause a function to become dead twice!");
126   DeletedFunctions.insert(F);
127 }
128 
129 void InlineAdvisor::freeDeletedFunctions() {
130   for (auto *F : DeletedFunctions)
131     delete F;
132   DeletedFunctions.clear();
133 }
134 
135 void InlineAdvice::recordInlineStatsIfNeeded() {
136   if (Advisor->ImportedFunctionsStats)
137     Advisor->ImportedFunctionsStats->recordInline(*Caller, *Callee);
138 }
139 
140 void InlineAdvice::recordInlining() {
141   markRecorded();
142   recordInlineStatsIfNeeded();
143   recordInliningImpl();
144 }
145 
146 void InlineAdvice::recordInliningWithCalleeDeleted() {
147   markRecorded();
148   recordInlineStatsIfNeeded();
149   Advisor->markFunctionAsDeleted(Callee);
150   recordInliningWithCalleeDeletedImpl();
151 }
152 
153 AnalysisKey InlineAdvisorAnalysis::Key;
154 
155 bool InlineAdvisorAnalysis::Result::tryCreate(InlineParams Params,
156                                               InliningAdvisorMode Mode) {
157   auto &FAM = MAM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
158   switch (Mode) {
159   case InliningAdvisorMode::Default:
160     Advisor.reset(new DefaultInlineAdvisor(M, FAM, Params));
161     break;
162   case InliningAdvisorMode::Development:
163 #ifdef LLVM_HAVE_TF_API
164     Advisor =
165         llvm::getDevelopmentModeAdvisor(M, MAM, [&FAM, Params](CallBase &CB) {
166           auto OIC = getDefaultInlineAdvice(CB, FAM, Params);
167           return OIC.hasValue();
168         });
169 #endif
170     break;
171   case InliningAdvisorMode::Release:
172 #ifdef LLVM_HAVE_TF_AOT
173     Advisor = llvm::getReleaseModeAdvisor(M, MAM);
174 #endif
175     break;
176   }
177   return !!Advisor;
178 }
179 
180 /// Return true if inlining of CB can block the caller from being
181 /// inlined which is proved to be more beneficial. \p IC is the
182 /// estimated inline cost associated with callsite \p CB.
183 /// \p TotalSecondaryCost will be set to the estimated cost of inlining the
184 /// caller if \p CB is suppressed for inlining.
185 static bool
186 shouldBeDeferred(Function *Caller, InlineCost IC, int &TotalSecondaryCost,
187                  function_ref<InlineCost(CallBase &CB)> GetInlineCost) {
188   // For now we only handle local or inline functions.
189   if (!Caller->hasLocalLinkage() && !Caller->hasLinkOnceODRLinkage())
190     return false;
191   // If the cost of inlining CB is non-positive, it is not going to prevent the
192   // caller from being inlined into its callers and hence we don't need to
193   // defer.
194   if (IC.getCost() <= 0)
195     return false;
196   // Try to detect the case where the current inlining candidate caller (call
197   // it B) is a static or linkonce-ODR function and is an inlining candidate
198   // elsewhere, and the current candidate callee (call it C) is large enough
199   // that inlining it into B would make B too big to inline later. In these
200   // circumstances it may be best not to inline C into B, but to inline B into
201   // its callers.
202   //
203   // This only applies to static and linkonce-ODR functions because those are
204   // expected to be available for inlining in the translation units where they
205   // are used. Thus we will always have the opportunity to make local inlining
206   // decisions. Importantly the linkonce-ODR linkage covers inline functions
207   // and templates in C++.
208   //
209   // FIXME: All of this logic should be sunk into getInlineCost. It relies on
210   // the internal implementation of the inline cost metrics rather than
211   // treating them as truly abstract units etc.
212   TotalSecondaryCost = 0;
213   // The candidate cost to be imposed upon the current function.
214   int CandidateCost = IC.getCost() - 1;
215   // If the caller has local linkage and can be inlined to all its callers, we
216   // can apply a huge negative bonus to TotalSecondaryCost.
217   bool ApplyLastCallBonus = Caller->hasLocalLinkage() && !Caller->hasOneUse();
218   // This bool tracks what happens if we DO inline C into B.
219   bool InliningPreventsSomeOuterInline = false;
220   unsigned NumCallerUsers = 0;
221   for (User *U : Caller->users()) {
222     CallBase *CS2 = dyn_cast<CallBase>(U);
223 
224     // If this isn't a call to Caller (it could be some other sort
225     // of reference) skip it.  Such references will prevent the caller
226     // from being removed.
227     if (!CS2 || CS2->getCalledFunction() != Caller) {
228       ApplyLastCallBonus = false;
229       continue;
230     }
231 
232     InlineCost IC2 = GetInlineCost(*CS2);
233     ++NumCallerCallersAnalyzed;
234     if (!IC2) {
235       ApplyLastCallBonus = false;
236       continue;
237     }
238     if (IC2.isAlways())
239       continue;
240 
241     // See if inlining of the original callsite would erase the cost delta of
242     // this callsite. We subtract off the penalty for the call instruction,
243     // which we would be deleting.
244     if (IC2.getCostDelta() <= CandidateCost) {
245       InliningPreventsSomeOuterInline = true;
246       TotalSecondaryCost += IC2.getCost();
247       NumCallerUsers++;
248     }
249   }
250 
251   if (!InliningPreventsSomeOuterInline)
252     return false;
253 
254   // If all outer calls to Caller would get inlined, the cost for the last
255   // one is set very low by getInlineCost, in anticipation that Caller will
256   // be removed entirely.  We did not account for this above unless there
257   // is only one caller of Caller.
258   if (ApplyLastCallBonus)
259     TotalSecondaryCost -= InlineConstants::LastCallToStaticBonus;
260 
261   // If InlineDeferralScale is negative, then ignore the cost of primary
262   // inlining -- IC.getCost() multiplied by the number of callers to Caller.
263   if (InlineDeferralScale < 0)
264     return TotalSecondaryCost < IC.getCost();
265 
266   int TotalCost = TotalSecondaryCost + IC.getCost() * NumCallerUsers;
267   int Allowance = IC.getCost() * InlineDeferralScale;
268   return TotalCost < Allowance;
269 }
270 
271 namespace llvm {
272 static std::basic_ostream<char> &operator<<(std::basic_ostream<char> &R,
273                                             const ore::NV &Arg) {
274   return R << Arg.Val;
275 }
276 
277 template <class RemarkT>
278 RemarkT &operator<<(RemarkT &&R, const InlineCost &IC) {
279   using namespace ore;
280   if (IC.isAlways()) {
281     R << "(cost=always)";
282   } else if (IC.isNever()) {
283     R << "(cost=never)";
284   } else {
285     R << "(cost=" << ore::NV("Cost", IC.getCost())
286       << ", threshold=" << ore::NV("Threshold", IC.getThreshold()) << ")";
287   }
288   if (const char *Reason = IC.getReason())
289     R << ": " << ore::NV("Reason", Reason);
290   return R;
291 }
292 } // namespace llvm
293 
294 std::string llvm::inlineCostStr(const InlineCost &IC) {
295   std::stringstream Remark;
296   Remark << IC;
297   return Remark.str();
298 }
299 
300 void llvm::setInlineRemark(CallBase &CB, StringRef Message) {
301   if (!InlineRemarkAttribute)
302     return;
303 
304   Attribute Attr = Attribute::get(CB.getContext(), "inline-remark", Message);
305   CB.addAttribute(AttributeList::FunctionIndex, Attr);
306 }
307 
308 /// Return the cost only if the inliner should attempt to inline at the given
309 /// CallSite. If we return the cost, we will emit an optimisation remark later
310 /// using that cost, so we won't do so from this function. Return None if
311 /// inlining should not be attempted.
312 Optional<InlineCost>
313 llvm::shouldInline(CallBase &CB,
314                    function_ref<InlineCost(CallBase &CB)> GetInlineCost,
315                    OptimizationRemarkEmitter &ORE, bool EnableDeferral) {
316   using namespace ore;
317 
318   InlineCost IC = GetInlineCost(CB);
319   Instruction *Call = &CB;
320   Function *Callee = CB.getCalledFunction();
321   Function *Caller = CB.getCaller();
322 
323   if (IC.isAlways()) {
324     LLVM_DEBUG(dbgs() << "    Inlining " << inlineCostStr(IC)
325                       << ", Call: " << CB << "\n");
326     return IC;
327   }
328 
329   if (!IC) {
330     LLVM_DEBUG(dbgs() << "    NOT Inlining " << inlineCostStr(IC)
331                       << ", Call: " << CB << "\n");
332     if (IC.isNever()) {
333       ORE.emit([&]() {
334         return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline", Call)
335                << NV("Callee", Callee) << " not inlined into "
336                << NV("Caller", Caller) << " because it should never be inlined "
337                << IC;
338       });
339     } else {
340       ORE.emit([&]() {
341         return OptimizationRemarkMissed(DEBUG_TYPE, "TooCostly", Call)
342                << NV("Callee", Callee) << " not inlined into "
343                << NV("Caller", Caller) << " because too costly to inline "
344                << IC;
345       });
346     }
347     setInlineRemark(CB, inlineCostStr(IC));
348     return None;
349   }
350 
351   int TotalSecondaryCost = 0;
352   if (EnableDeferral &&
353       shouldBeDeferred(Caller, IC, TotalSecondaryCost, GetInlineCost)) {
354     LLVM_DEBUG(dbgs() << "    NOT Inlining: " << CB
355                       << " Cost = " << IC.getCost()
356                       << ", outer Cost = " << TotalSecondaryCost << '\n');
357     ORE.emit([&]() {
358       return OptimizationRemarkMissed(DEBUG_TYPE, "IncreaseCostInOtherContexts",
359                                       Call)
360              << "Not inlining. Cost of inlining " << NV("Callee", Callee)
361              << " increases the cost of inlining " << NV("Caller", Caller)
362              << " in other contexts";
363     });
364     setInlineRemark(CB, "deferred");
365     // IC does not bool() to false, so get an InlineCost that will.
366     // This will not be inspected to make an error message.
367     return None;
368   }
369 
370   LLVM_DEBUG(dbgs() << "    Inlining " << inlineCostStr(IC) << ", Call: " << CB
371                     << '\n');
372   return IC;
373 }
374 
375 std::string llvm::getCallSiteLocation(DebugLoc DLoc) {
376   std::ostringstream CallSiteLoc;
377   bool First = true;
378   for (DILocation *DIL = DLoc.get(); DIL; DIL = DIL->getInlinedAt()) {
379     if (!First)
380       CallSiteLoc << " @ ";
381     // Note that negative line offset is actually possible, but we use
382     // unsigned int to match line offset representation in remarks so
383     // it's directly consumable by relay advisor.
384     uint32_t Offset =
385         DIL->getLine() - DIL->getScope()->getSubprogram()->getLine();
386     uint32_t Discriminator = DIL->getBaseDiscriminator();
387     StringRef Name = DIL->getScope()->getSubprogram()->getLinkageName();
388     if (Name.empty())
389       Name = DIL->getScope()->getSubprogram()->getName();
390     CallSiteLoc << Name.str() << ":" << llvm::utostr(Offset) << ":"
391                 << llvm::utostr(DIL->getColumn());
392     if (Discriminator)
393       CallSiteLoc << "." << llvm::utostr(Discriminator);
394     First = false;
395   }
396 
397   return CallSiteLoc.str();
398 }
399 
400 void llvm::addLocationToRemarks(OptimizationRemark &Remark, DebugLoc DLoc) {
401   if (!DLoc.get()) {
402     return;
403   }
404 
405   bool First = true;
406   Remark << " at callsite ";
407   for (DILocation *DIL = DLoc.get(); DIL; DIL = DIL->getInlinedAt()) {
408     if (!First)
409       Remark << " @ ";
410     unsigned int Offset = DIL->getLine();
411     Offset -= DIL->getScope()->getSubprogram()->getLine();
412     unsigned int Discriminator = DIL->getBaseDiscriminator();
413     StringRef Name = DIL->getScope()->getSubprogram()->getLinkageName();
414     if (Name.empty())
415       Name = DIL->getScope()->getSubprogram()->getName();
416     Remark << Name << ":" << ore::NV("Line", Offset) << ":"
417            << ore::NV("Column", DIL->getColumn());
418     if (Discriminator)
419       Remark << "." << ore::NV("Disc", Discriminator);
420     First = false;
421   }
422 
423   Remark << ";";
424 }
425 
426 void llvm::emitInlinedInto(OptimizationRemarkEmitter &ORE, DebugLoc DLoc,
427                            const BasicBlock *Block, const Function &Callee,
428                            const Function &Caller, const InlineCost &IC,
429                            bool ForProfileContext, const char *PassName) {
430   ORE.emit([&]() {
431     bool AlwaysInline = IC.isAlways();
432     StringRef RemarkName = AlwaysInline ? "AlwaysInline" : "Inlined";
433     OptimizationRemark Remark(PassName ? PassName : DEBUG_TYPE, RemarkName,
434                               DLoc, Block);
435     Remark << ore::NV("Callee", &Callee) << " inlined into ";
436     Remark << ore::NV("Caller", &Caller);
437     if (ForProfileContext)
438       Remark << " to match profiling context";
439     Remark << " with " << IC;
440     addLocationToRemarks(Remark, DLoc);
441     return Remark;
442   });
443 }
444 
445 InlineAdvisor::InlineAdvisor(Module &M, FunctionAnalysisManager &FAM)
446     : M(M), FAM(FAM) {
447   if (InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No) {
448     ImportedFunctionsStats =
449         std::make_unique<ImportedFunctionsInliningStatistics>();
450     ImportedFunctionsStats->setModuleInfo(M);
451   }
452 }
453 
454 InlineAdvisor::~InlineAdvisor() {
455   if (ImportedFunctionsStats) {
456     assert(InlinerFunctionImportStats != InlinerFunctionImportStatsOpts::No);
457     ImportedFunctionsStats->dump(InlinerFunctionImportStats ==
458                                  InlinerFunctionImportStatsOpts::Verbose);
459   }
460 
461   freeDeletedFunctions();
462 }
463 
464 std::unique_ptr<InlineAdvice> InlineAdvisor::getMandatoryAdvice(CallBase &CB,
465                                                                 bool Advice) {
466   return std::make_unique<InlineAdvice>(this, CB, getCallerORE(CB), Advice);
467 }
468 
469 InlineAdvisor::MandatoryInliningKind
470 InlineAdvisor::getMandatoryKind(CallBase &CB, FunctionAnalysisManager &FAM,
471                                 OptimizationRemarkEmitter &ORE) {
472   auto &Callee = *CB.getCalledFunction();
473 
474   auto GetTLI = [&](Function &F) -> const TargetLibraryInfo & {
475     return FAM.getResult<TargetLibraryAnalysis>(F);
476   };
477 
478   auto &TIR = FAM.getResult<TargetIRAnalysis>(Callee);
479 
480   auto TrivialDecision =
481       llvm::getAttributeBasedInliningDecision(CB, &Callee, TIR, GetTLI);
482 
483   if (TrivialDecision.hasValue()) {
484     if (TrivialDecision->isSuccess())
485       return MandatoryInliningKind::Always;
486     else
487       return MandatoryInliningKind::Never;
488   }
489   return MandatoryInliningKind::NotMandatory;
490 }
491 
492 std::unique_ptr<InlineAdvice> InlineAdvisor::getAdvice(CallBase &CB,
493                                                        bool MandatoryOnly) {
494   if (!MandatoryOnly)
495     return getAdviceImpl(CB);
496   bool Advice = CB.getCaller() != CB.getCalledFunction() &&
497                 MandatoryInliningKind::Always ==
498                     getMandatoryKind(CB, FAM, getCallerORE(CB));
499   return getMandatoryAdvice(CB, Advice);
500 }
501 
502 OptimizationRemarkEmitter &InlineAdvisor::getCallerORE(CallBase &CB) {
503   return FAM.getResult<OptimizationRemarkEmitterAnalysis>(*CB.getCaller());
504 }
505