1 //===- InlineCost.cpp - Cost analysis for inliner -------------------------===//
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 inline cost analysis.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Analysis/InlineCost.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/SetVector.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/AssumptionCache.h"
20 #include "llvm/Analysis/BlockFrequencyInfo.h"
21 #include "llvm/Analysis/CodeMetrics.h"
22 #include "llvm/Analysis/ConstantFolding.h"
23 #include "llvm/Analysis/InstructionSimplify.h"
24 #include "llvm/Analysis/LoopInfo.h"
25 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
26 #include "llvm/Analysis/ProfileSummaryInfo.h"
27 #include "llvm/Analysis/TargetLibraryInfo.h"
28 #include "llvm/Analysis/TargetTransformInfo.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/Config/llvm-config.h"
31 #include "llvm/IR/AssemblyAnnotationWriter.h"
32 #include "llvm/IR/CallingConv.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/Dominators.h"
35 #include "llvm/IR/GetElementPtrTypeIterator.h"
36 #include "llvm/IR/GlobalAlias.h"
37 #include "llvm/IR/InstVisitor.h"
38 #include "llvm/IR/IntrinsicInst.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/IR/PatternMatch.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include <limits>
46 
47 using namespace llvm;
48 
49 #define DEBUG_TYPE "inline-cost"
50 
51 STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed");
52 
53 static cl::opt<int>
54     DefaultThreshold("inlinedefault-threshold", cl::Hidden, cl::init(225),
55                      cl::desc("Default amount of inlining to perform"));
56 
57 // We introduce this option since there is a minor compile-time win by avoiding
58 // addition of TTI attributes (target-features in particular) to inline
59 // candidates when they are guaranteed to be the same as top level methods in
60 // some use cases. If we avoid adding the attribute, we need an option to avoid
61 // checking these attributes.
62 static cl::opt<bool> IgnoreTTIInlineCompatible(
63     "ignore-tti-inline-compatible", cl::Hidden, cl::init(false),
64     cl::desc("Ignore TTI attributes compatibility check between callee/caller "
65              "during inline cost calculation"));
66 
67 static cl::opt<bool> PrintInstructionComments(
68     "print-instruction-comments", cl::Hidden, cl::init(false),
69     cl::desc("Prints comments for instruction based on inline cost analysis"));
70 
71 static cl::opt<int> InlineThreshold(
72     "inline-threshold", cl::Hidden, cl::init(225),
73     cl::desc("Control the amount of inlining to perform (default = 225)"));
74 
75 static cl::opt<int> HintThreshold(
76     "inlinehint-threshold", cl::Hidden, cl::init(325),
77     cl::desc("Threshold for inlining functions with inline hint"));
78 
79 static cl::opt<int>
80     ColdCallSiteThreshold("inline-cold-callsite-threshold", cl::Hidden,
81                           cl::init(45),
82                           cl::desc("Threshold for inlining cold callsites"));
83 
84 static cl::opt<bool> InlineEnableCostBenefitAnalysis(
85     "inline-enable-cost-benefit-analysis", cl::Hidden, cl::init(false),
86     cl::desc("Enable the cost-benefit analysis for the inliner"));
87 
88 static cl::opt<int> InlineSavingsMultiplier(
89     "inline-savings-multiplier", cl::Hidden, cl::init(8),
90     cl::desc("Multiplier to multiply cycle savings by during inlining"));
91 
92 static cl::opt<int>
93     InlineSizeAllowance("inline-size-allowance", cl::Hidden, cl::init(100),
94                         cl::desc("The maximum size of a callee that get's "
95                                  "inlined without sufficient cycle savings"));
96 
97 // We introduce this threshold to help performance of instrumentation based
98 // PGO before we actually hook up inliner with analysis passes such as BPI and
99 // BFI.
100 static cl::opt<int> ColdThreshold(
101     "inlinecold-threshold", cl::Hidden, cl::init(45),
102     cl::desc("Threshold for inlining functions with cold attribute"));
103 
104 static cl::opt<int>
105     HotCallSiteThreshold("hot-callsite-threshold", cl::Hidden, cl::init(3000),
106                          cl::desc("Threshold for hot callsites "));
107 
108 static cl::opt<int> LocallyHotCallSiteThreshold(
109     "locally-hot-callsite-threshold", cl::Hidden, cl::init(525),
110     cl::desc("Threshold for locally hot callsites "));
111 
112 static cl::opt<int> ColdCallSiteRelFreq(
113     "cold-callsite-rel-freq", cl::Hidden, cl::init(2),
114     cl::desc("Maximum block frequency, expressed as a percentage of caller's "
115              "entry frequency, for a callsite to be cold in the absence of "
116              "profile information."));
117 
118 static cl::opt<int> HotCallSiteRelFreq(
119     "hot-callsite-rel-freq", cl::Hidden, cl::init(60),
120     cl::desc("Minimum block frequency, expressed as a multiple of caller's "
121              "entry frequency, for a callsite to be hot in the absence of "
122              "profile information."));
123 
124 static cl::opt<int> CallPenalty(
125     "inline-call-penalty", cl::Hidden, cl::init(25),
126     cl::desc("Call penalty that is applied per callsite when inlining"));
127 
128 static cl::opt<size_t>
129     StackSizeThreshold("inline-max-stacksize", cl::Hidden,
130                        cl::init(std::numeric_limits<size_t>::max()),
131                        cl::ZeroOrMore,
132                        cl::desc("Do not inline functions with a stack size "
133                                 "that exceeds the specified limit"));
134 
135 static cl::opt<bool> OptComputeFullInlineCost(
136     "inline-cost-full", cl::Hidden,
137     cl::desc("Compute the full inline cost of a call site even when the cost "
138              "exceeds the threshold."));
139 
140 static cl::opt<bool> InlineCallerSupersetNoBuiltin(
141     "inline-caller-superset-nobuiltin", cl::Hidden, cl::init(true),
142     cl::desc("Allow inlining when caller has a superset of callee's nobuiltin "
143              "attributes."));
144 
145 static cl::opt<bool> DisableGEPConstOperand(
146     "disable-gep-const-evaluation", cl::Hidden, cl::init(false),
147     cl::desc("Disables evaluation of GetElementPtr with constant operands"));
148 
149 namespace llvm {
150 Optional<int> getStringFnAttrAsInt(CallBase &CB, StringRef AttrKind) {
151   Attribute Attr = CB.getFnAttr(AttrKind);
152   int AttrValue;
153   if (Attr.getValueAsString().getAsInteger(10, AttrValue))
154     return None;
155   return AttrValue;
156 }
157 } // namespace llvm
158 
159 namespace {
160 class InlineCostCallAnalyzer;
161 
162 // This struct is used to store information about inline cost of a
163 // particular instruction
164 struct InstructionCostDetail {
165   int CostBefore = 0;
166   int CostAfter = 0;
167   int ThresholdBefore = 0;
168   int ThresholdAfter = 0;
169 
170   int getThresholdDelta() const { return ThresholdAfter - ThresholdBefore; }
171 
172   int getCostDelta() const { return CostAfter - CostBefore; }
173 
174   bool hasThresholdChanged() const { return ThresholdAfter != ThresholdBefore; }
175 };
176 
177 class InlineCostAnnotationWriter : public AssemblyAnnotationWriter {
178 private:
179   InlineCostCallAnalyzer *const ICCA;
180 
181 public:
182   InlineCostAnnotationWriter(InlineCostCallAnalyzer *ICCA) : ICCA(ICCA) {}
183   virtual void emitInstructionAnnot(const Instruction *I,
184                                     formatted_raw_ostream &OS) override;
185 };
186 
187 /// Carry out call site analysis, in order to evaluate inlinability.
188 /// NOTE: the type is currently used as implementation detail of functions such
189 /// as llvm::getInlineCost. Note the function_ref constructor parameters - the
190 /// expectation is that they come from the outer scope, from the wrapper
191 /// functions. If we want to support constructing CallAnalyzer objects where
192 /// lambdas are provided inline at construction, or where the object needs to
193 /// otherwise survive past the scope of the provided functions, we need to
194 /// revisit the argument types.
195 class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> {
196   typedef InstVisitor<CallAnalyzer, bool> Base;
197   friend class InstVisitor<CallAnalyzer, bool>;
198 
199 protected:
200   virtual ~CallAnalyzer() = default;
201   /// The TargetTransformInfo available for this compilation.
202   const TargetTransformInfo &TTI;
203 
204   /// Getter for the cache of @llvm.assume intrinsics.
205   function_ref<AssumptionCache &(Function &)> GetAssumptionCache;
206 
207   /// Getter for BlockFrequencyInfo
208   function_ref<BlockFrequencyInfo &(Function &)> GetBFI;
209 
210   /// Profile summary information.
211   ProfileSummaryInfo *PSI;
212 
213   /// The called function.
214   Function &F;
215 
216   // Cache the DataLayout since we use it a lot.
217   const DataLayout &DL;
218 
219   /// The OptimizationRemarkEmitter available for this compilation.
220   OptimizationRemarkEmitter *ORE;
221 
222   /// The candidate callsite being analyzed. Please do not use this to do
223   /// analysis in the caller function; we want the inline cost query to be
224   /// easily cacheable. Instead, use the cover function paramHasAttr.
225   CallBase &CandidateCall;
226 
227   /// Extension points for handling callsite features.
228   // Called before a basic block was analyzed.
229   virtual void onBlockStart(const BasicBlock *BB) {}
230 
231   /// Called after a basic block was analyzed.
232   virtual void onBlockAnalyzed(const BasicBlock *BB) {}
233 
234   /// Called before an instruction was analyzed
235   virtual void onInstructionAnalysisStart(const Instruction *I) {}
236 
237   /// Called after an instruction was analyzed
238   virtual void onInstructionAnalysisFinish(const Instruction *I) {}
239 
240   /// Called at the end of the analysis of the callsite. Return the outcome of
241   /// the analysis, i.e. 'InlineResult(true)' if the inlining may happen, or
242   /// the reason it can't.
243   virtual InlineResult finalizeAnalysis() { return InlineResult::success(); }
244   /// Called when we're about to start processing a basic block, and every time
245   /// we are done processing an instruction. Return true if there is no point in
246   /// continuing the analysis (e.g. we've determined already the call site is
247   /// too expensive to inline)
248   virtual bool shouldStop() { return false; }
249 
250   /// Called before the analysis of the callee body starts (with callsite
251   /// contexts propagated).  It checks callsite-specific information. Return a
252   /// reason analysis can't continue if that's the case, or 'true' if it may
253   /// continue.
254   virtual InlineResult onAnalysisStart() { return InlineResult::success(); }
255   /// Called if the analysis engine decides SROA cannot be done for the given
256   /// alloca.
257   virtual void onDisableSROA(AllocaInst *Arg) {}
258 
259   /// Called the analysis engine determines load elimination won't happen.
260   virtual void onDisableLoadElimination() {}
261 
262   /// Called when we visit a CallBase, before the analysis starts. Return false
263   /// to stop further processing of the instruction.
264   virtual bool onCallBaseVisitStart(CallBase &Call) { return true; }
265 
266   /// Called to account for a call.
267   virtual void onCallPenalty() {}
268 
269   /// Called to account for the expectation the inlining would result in a load
270   /// elimination.
271   virtual void onLoadEliminationOpportunity() {}
272 
273   /// Called to account for the cost of argument setup for the Call in the
274   /// callee's body (not the callsite currently under analysis).
275   virtual void onCallArgumentSetup(const CallBase &Call) {}
276 
277   /// Called to account for a load relative intrinsic.
278   virtual void onLoadRelativeIntrinsic() {}
279 
280   /// Called to account for a lowered call.
281   virtual void onLoweredCall(Function *F, CallBase &Call, bool IsIndirectCall) {
282   }
283 
284   /// Account for a jump table of given size. Return false to stop further
285   /// processing the switch instruction
286   virtual bool onJumpTable(unsigned JumpTableSize) { return true; }
287 
288   /// Account for a case cluster of given size. Return false to stop further
289   /// processing of the instruction.
290   virtual bool onCaseCluster(unsigned NumCaseCluster) { return true; }
291 
292   /// Called at the end of processing a switch instruction, with the given
293   /// number of case clusters.
294   virtual void onFinalizeSwitch(unsigned JumpTableSize,
295                                 unsigned NumCaseCluster) {}
296 
297   /// Called to account for any other instruction not specifically accounted
298   /// for.
299   virtual void onMissedSimplification() {}
300 
301   /// Start accounting potential benefits due to SROA for the given alloca.
302   virtual void onInitializeSROAArg(AllocaInst *Arg) {}
303 
304   /// Account SROA savings for the AllocaInst value.
305   virtual void onAggregateSROAUse(AllocaInst *V) {}
306 
307   bool handleSROA(Value *V, bool DoNotDisable) {
308     // Check for SROA candidates in comparisons.
309     if (auto *SROAArg = getSROAArgForValueOrNull(V)) {
310       if (DoNotDisable) {
311         onAggregateSROAUse(SROAArg);
312         return true;
313       }
314       disableSROAForArg(SROAArg);
315     }
316     return false;
317   }
318 
319   bool IsCallerRecursive = false;
320   bool IsRecursiveCall = false;
321   bool ExposesReturnsTwice = false;
322   bool HasDynamicAlloca = false;
323   bool ContainsNoDuplicateCall = false;
324   bool HasReturn = false;
325   bool HasIndirectBr = false;
326   bool HasUninlineableIntrinsic = false;
327   bool InitsVargArgs = false;
328 
329   /// Number of bytes allocated statically by the callee.
330   uint64_t AllocatedSize = 0;
331   unsigned NumInstructions = 0;
332   unsigned NumVectorInstructions = 0;
333 
334   /// While we walk the potentially-inlined instructions, we build up and
335   /// maintain a mapping of simplified values specific to this callsite. The
336   /// idea is to propagate any special information we have about arguments to
337   /// this call through the inlinable section of the function, and account for
338   /// likely simplifications post-inlining. The most important aspect we track
339   /// is CFG altering simplifications -- when we prove a basic block dead, that
340   /// can cause dramatic shifts in the cost of inlining a function.
341   DenseMap<Value *, Constant *> SimplifiedValues;
342 
343   /// Keep track of the values which map back (through function arguments) to
344   /// allocas on the caller stack which could be simplified through SROA.
345   DenseMap<Value *, AllocaInst *> SROAArgValues;
346 
347   /// Keep track of Allocas for which we believe we may get SROA optimization.
348   DenseSet<AllocaInst *> EnabledSROAAllocas;
349 
350   /// Keep track of values which map to a pointer base and constant offset.
351   DenseMap<Value *, std::pair<Value *, APInt>> ConstantOffsetPtrs;
352 
353   /// Keep track of dead blocks due to the constant arguments.
354   SmallPtrSet<BasicBlock *, 16> DeadBlocks;
355 
356   /// The mapping of the blocks to their known unique successors due to the
357   /// constant arguments.
358   DenseMap<BasicBlock *, BasicBlock *> KnownSuccessors;
359 
360   /// Model the elimination of repeated loads that is expected to happen
361   /// whenever we simplify away the stores that would otherwise cause them to be
362   /// loads.
363   bool EnableLoadElimination = true;
364 
365   /// Whether we allow inlining for recursive call.
366   bool AllowRecursiveCall = false;
367 
368   SmallPtrSet<Value *, 16> LoadAddrSet;
369 
370   AllocaInst *getSROAArgForValueOrNull(Value *V) const {
371     auto It = SROAArgValues.find(V);
372     if (It == SROAArgValues.end() || EnabledSROAAllocas.count(It->second) == 0)
373       return nullptr;
374     return It->second;
375   }
376 
377   // Custom simplification helper routines.
378   bool isAllocaDerivedArg(Value *V);
379   void disableSROAForArg(AllocaInst *SROAArg);
380   void disableSROA(Value *V);
381   void findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB);
382   void disableLoadElimination();
383   bool isGEPFree(GetElementPtrInst &GEP);
384   bool canFoldInboundsGEP(GetElementPtrInst &I);
385   bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
386   bool simplifyCallSite(Function *F, CallBase &Call);
387   bool simplifyInstruction(Instruction &I);
388   bool simplifyIntrinsicCallIsConstant(CallBase &CB);
389   ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
390 
391   /// Return true if the given argument to the function being considered for
392   /// inlining has the given attribute set either at the call site or the
393   /// function declaration.  Primarily used to inspect call site specific
394   /// attributes since these can be more precise than the ones on the callee
395   /// itself.
396   bool paramHasAttr(Argument *A, Attribute::AttrKind Attr);
397 
398   /// Return true if the given value is known non null within the callee if
399   /// inlined through this particular callsite.
400   bool isKnownNonNullInCallee(Value *V);
401 
402   /// Return true if size growth is allowed when inlining the callee at \p Call.
403   bool allowSizeGrowth(CallBase &Call);
404 
405   // Custom analysis routines.
406   InlineResult analyzeBlock(BasicBlock *BB,
407                             SmallPtrSetImpl<const Value *> &EphValues);
408 
409   // Disable several entry points to the visitor so we don't accidentally use
410   // them by declaring but not defining them here.
411   void visit(Module *);
412   void visit(Module &);
413   void visit(Function *);
414   void visit(Function &);
415   void visit(BasicBlock *);
416   void visit(BasicBlock &);
417 
418   // Provide base case for our instruction visit.
419   bool visitInstruction(Instruction &I);
420 
421   // Our visit overrides.
422   bool visitAlloca(AllocaInst &I);
423   bool visitPHI(PHINode &I);
424   bool visitGetElementPtr(GetElementPtrInst &I);
425   bool visitBitCast(BitCastInst &I);
426   bool visitPtrToInt(PtrToIntInst &I);
427   bool visitIntToPtr(IntToPtrInst &I);
428   bool visitCastInst(CastInst &I);
429   bool visitCmpInst(CmpInst &I);
430   bool visitSub(BinaryOperator &I);
431   bool visitBinaryOperator(BinaryOperator &I);
432   bool visitFNeg(UnaryOperator &I);
433   bool visitLoad(LoadInst &I);
434   bool visitStore(StoreInst &I);
435   bool visitExtractValue(ExtractValueInst &I);
436   bool visitInsertValue(InsertValueInst &I);
437   bool visitCallBase(CallBase &Call);
438   bool visitReturnInst(ReturnInst &RI);
439   bool visitBranchInst(BranchInst &BI);
440   bool visitSelectInst(SelectInst &SI);
441   bool visitSwitchInst(SwitchInst &SI);
442   bool visitIndirectBrInst(IndirectBrInst &IBI);
443   bool visitResumeInst(ResumeInst &RI);
444   bool visitCleanupReturnInst(CleanupReturnInst &RI);
445   bool visitCatchReturnInst(CatchReturnInst &RI);
446   bool visitUnreachableInst(UnreachableInst &I);
447 
448 public:
449   CallAnalyzer(Function &Callee, CallBase &Call, const TargetTransformInfo &TTI,
450                function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
451                function_ref<BlockFrequencyInfo &(Function &)> GetBFI = nullptr,
452                ProfileSummaryInfo *PSI = nullptr,
453                OptimizationRemarkEmitter *ORE = nullptr)
454       : TTI(TTI), GetAssumptionCache(GetAssumptionCache), GetBFI(GetBFI),
455         PSI(PSI), F(Callee), DL(F.getParent()->getDataLayout()), ORE(ORE),
456         CandidateCall(Call) {}
457 
458   InlineResult analyze();
459 
460   Optional<Constant *> getSimplifiedValue(Instruction *I) {
461     if (SimplifiedValues.find(I) != SimplifiedValues.end())
462       return SimplifiedValues[I];
463     return None;
464   }
465 
466   // Keep a bunch of stats about the cost savings found so we can print them
467   // out when debugging.
468   unsigned NumConstantArgs = 0;
469   unsigned NumConstantOffsetPtrArgs = 0;
470   unsigned NumAllocaArgs = 0;
471   unsigned NumConstantPtrCmps = 0;
472   unsigned NumConstantPtrDiffs = 0;
473   unsigned NumInstructionsSimplified = 0;
474 
475   void dump();
476 };
477 
478 // Considering forming a binary search, we should find the number of nodes
479 // which is same as the number of comparisons when lowered. For a given
480 // number of clusters, n, we can define a recursive function, f(n), to find
481 // the number of nodes in the tree. The recursion is :
482 // f(n) = 1 + f(n/2) + f (n - n/2), when n > 3,
483 // and f(n) = n, when n <= 3.
484 // This will lead a binary tree where the leaf should be either f(2) or f(3)
485 // when n > 3.  So, the number of comparisons from leaves should be n, while
486 // the number of non-leaf should be :
487 //   2^(log2(n) - 1) - 1
488 //   = 2^log2(n) * 2^-1 - 1
489 //   = n / 2 - 1.
490 // Considering comparisons from leaf and non-leaf nodes, we can estimate the
491 // number of comparisons in a simple closed form :
492 //   n + n / 2 - 1 = n * 3 / 2 - 1
493 int64_t getExpectedNumberOfCompare(int NumCaseCluster) {
494   return 3 * static_cast<int64_t>(NumCaseCluster) / 2 - 1;
495 }
496 
497 /// FIXME: if it is necessary to derive from InlineCostCallAnalyzer, note
498 /// the FIXME in onLoweredCall, when instantiating an InlineCostCallAnalyzer
499 class InlineCostCallAnalyzer final : public CallAnalyzer {
500   const int CostUpperBound = INT_MAX - InlineConstants::InstrCost - 1;
501   const bool ComputeFullInlineCost;
502   int LoadEliminationCost = 0;
503   /// Bonus to be applied when percentage of vector instructions in callee is
504   /// high (see more details in updateThreshold).
505   int VectorBonus = 0;
506   /// Bonus to be applied when the callee has only one reachable basic block.
507   int SingleBBBonus = 0;
508 
509   /// Tunable parameters that control the analysis.
510   const InlineParams &Params;
511 
512   // This DenseMap stores the delta change in cost and threshold after
513   // accounting for the given instruction. The map is filled only with the
514   // flag PrintInstructionComments on.
515   DenseMap<const Instruction *, InstructionCostDetail> InstructionCostDetailMap;
516 
517   /// Upper bound for the inlining cost. Bonuses are being applied to account
518   /// for speculative "expected profit" of the inlining decision.
519   int Threshold = 0;
520 
521   /// Attempt to evaluate indirect calls to boost its inline cost.
522   const bool BoostIndirectCalls;
523 
524   /// Ignore the threshold when finalizing analysis.
525   const bool IgnoreThreshold;
526 
527   // True if the cost-benefit-analysis-based inliner is enabled.
528   const bool CostBenefitAnalysisEnabled;
529 
530   /// Inlining cost measured in abstract units, accounts for all the
531   /// instructions expected to be executed for a given function invocation.
532   /// Instructions that are statically proven to be dead based on call-site
533   /// arguments are not counted here.
534   int Cost = 0;
535 
536   // The cumulative cost at the beginning of the basic block being analyzed.  At
537   // the end of analyzing each basic block, "Cost - CostAtBBStart" represents
538   // the size of that basic block.
539   int CostAtBBStart = 0;
540 
541   // The static size of live but cold basic blocks.  This is "static" in the
542   // sense that it's not weighted by profile counts at all.
543   int ColdSize = 0;
544 
545   // Whether inlining is decided by cost-threshold analysis.
546   bool DecidedByCostThreshold = false;
547 
548   // Whether inlining is decided by cost-benefit analysis.
549   bool DecidedByCostBenefit = false;
550 
551   // The cost-benefit pair computed by cost-benefit analysis.
552   Optional<CostBenefitPair> CostBenefit = None;
553 
554   bool SingleBB = true;
555 
556   unsigned SROACostSavings = 0;
557   unsigned SROACostSavingsLost = 0;
558 
559   /// The mapping of caller Alloca values to their accumulated cost savings. If
560   /// we have to disable SROA for one of the allocas, this tells us how much
561   /// cost must be added.
562   DenseMap<AllocaInst *, int> SROAArgCosts;
563 
564   /// Return true if \p Call is a cold callsite.
565   bool isColdCallSite(CallBase &Call, BlockFrequencyInfo *CallerBFI);
566 
567   /// Update Threshold based on callsite properties such as callee
568   /// attributes and callee hotness for PGO builds. The Callee is explicitly
569   /// passed to support analyzing indirect calls whose target is inferred by
570   /// analysis.
571   void updateThreshold(CallBase &Call, Function &Callee);
572   /// Return a higher threshold if \p Call is a hot callsite.
573   Optional<int> getHotCallSiteThreshold(CallBase &Call,
574                                         BlockFrequencyInfo *CallerBFI);
575 
576   /// Handle a capped 'int' increment for Cost.
577   void addCost(int64_t Inc, int64_t UpperBound = INT_MAX) {
578     assert(UpperBound > 0 && UpperBound <= INT_MAX && "invalid upper bound");
579     Cost = std::min<int>(UpperBound, Cost + Inc);
580   }
581 
582   void onDisableSROA(AllocaInst *Arg) override {
583     auto CostIt = SROAArgCosts.find(Arg);
584     if (CostIt == SROAArgCosts.end())
585       return;
586     addCost(CostIt->second);
587     SROACostSavings -= CostIt->second;
588     SROACostSavingsLost += CostIt->second;
589     SROAArgCosts.erase(CostIt);
590   }
591 
592   void onDisableLoadElimination() override {
593     addCost(LoadEliminationCost);
594     LoadEliminationCost = 0;
595   }
596 
597   bool onCallBaseVisitStart(CallBase &Call) override {
598     if (Optional<int> AttrCallThresholdBonus =
599             getStringFnAttrAsInt(Call, "call-threshold-bonus"))
600       Threshold += *AttrCallThresholdBonus;
601 
602     if (Optional<int> AttrCallCost =
603             getStringFnAttrAsInt(Call, "call-inline-cost")) {
604       addCost(*AttrCallCost);
605       // Prevent further processing of the call since we want to override its
606       // inline cost, not just add to it.
607       return false;
608     }
609     return true;
610   }
611 
612   void onCallPenalty() override { addCost(CallPenalty); }
613   void onCallArgumentSetup(const CallBase &Call) override {
614     // Pay the price of the argument setup. We account for the average 1
615     // instruction per call argument setup here.
616     addCost(Call.arg_size() * InlineConstants::InstrCost);
617   }
618   void onLoadRelativeIntrinsic() override {
619     // This is normally lowered to 4 LLVM instructions.
620     addCost(3 * InlineConstants::InstrCost);
621   }
622   void onLoweredCall(Function *F, CallBase &Call,
623                      bool IsIndirectCall) override {
624     // We account for the average 1 instruction per call argument setup here.
625     addCost(Call.arg_size() * InlineConstants::InstrCost);
626 
627     // If we have a constant that we are calling as a function, we can peer
628     // through it and see the function target. This happens not infrequently
629     // during devirtualization and so we want to give it a hefty bonus for
630     // inlining, but cap that bonus in the event that inlining wouldn't pan out.
631     // Pretend to inline the function, with a custom threshold.
632     if (IsIndirectCall && BoostIndirectCalls) {
633       auto IndirectCallParams = Params;
634       IndirectCallParams.DefaultThreshold =
635           InlineConstants::IndirectCallThreshold;
636       /// FIXME: if InlineCostCallAnalyzer is derived from, this may need
637       /// to instantiate the derived class.
638       InlineCostCallAnalyzer CA(*F, Call, IndirectCallParams, TTI,
639                                 GetAssumptionCache, GetBFI, PSI, ORE, false);
640       if (CA.analyze().isSuccess()) {
641         // We were able to inline the indirect call! Subtract the cost from the
642         // threshold to get the bonus we want to apply, but don't go below zero.
643         Cost -= std::max(0, CA.getThreshold() - CA.getCost());
644       }
645     } else
646       // Otherwise simply add the cost for merely making the call.
647       addCost(CallPenalty);
648   }
649 
650   void onFinalizeSwitch(unsigned JumpTableSize,
651                         unsigned NumCaseCluster) override {
652     // If suitable for a jump table, consider the cost for the table size and
653     // branch to destination.
654     // Maximum valid cost increased in this function.
655     if (JumpTableSize) {
656       int64_t JTCost =
657           static_cast<int64_t>(JumpTableSize) * InlineConstants::InstrCost +
658           4 * InlineConstants::InstrCost;
659 
660       addCost(JTCost, static_cast<int64_t>(CostUpperBound));
661       return;
662     }
663 
664     if (NumCaseCluster <= 3) {
665       // Suppose a comparison includes one compare and one conditional branch.
666       addCost(NumCaseCluster * 2 * InlineConstants::InstrCost);
667       return;
668     }
669 
670     int64_t ExpectedNumberOfCompare =
671         getExpectedNumberOfCompare(NumCaseCluster);
672     int64_t SwitchCost =
673         ExpectedNumberOfCompare * 2 * InlineConstants::InstrCost;
674 
675     addCost(SwitchCost, static_cast<int64_t>(CostUpperBound));
676   }
677   void onMissedSimplification() override {
678     addCost(InlineConstants::InstrCost);
679   }
680 
681   void onInitializeSROAArg(AllocaInst *Arg) override {
682     assert(Arg != nullptr &&
683            "Should not initialize SROA costs for null value.");
684     SROAArgCosts[Arg] = 0;
685   }
686 
687   void onAggregateSROAUse(AllocaInst *SROAArg) override {
688     auto CostIt = SROAArgCosts.find(SROAArg);
689     assert(CostIt != SROAArgCosts.end() &&
690            "expected this argument to have a cost");
691     CostIt->second += InlineConstants::InstrCost;
692     SROACostSavings += InlineConstants::InstrCost;
693   }
694 
695   void onBlockStart(const BasicBlock *BB) override { CostAtBBStart = Cost; }
696 
697   void onBlockAnalyzed(const BasicBlock *BB) override {
698     if (CostBenefitAnalysisEnabled) {
699       // Keep track of the static size of live but cold basic blocks.  For now,
700       // we define a cold basic block to be one that's never executed.
701       assert(GetBFI && "GetBFI must be available");
702       BlockFrequencyInfo *BFI = &(GetBFI(F));
703       assert(BFI && "BFI must be available");
704       auto ProfileCount = BFI->getBlockProfileCount(BB);
705       assert(ProfileCount);
706       if (ProfileCount.getValue() == 0)
707         ColdSize += Cost - CostAtBBStart;
708     }
709 
710     auto *TI = BB->getTerminator();
711     // If we had any successors at this point, than post-inlining is likely to
712     // have them as well. Note that we assume any basic blocks which existed
713     // due to branches or switches which folded above will also fold after
714     // inlining.
715     if (SingleBB && TI->getNumSuccessors() > 1) {
716       // Take off the bonus we applied to the threshold.
717       Threshold -= SingleBBBonus;
718       SingleBB = false;
719     }
720   }
721 
722   void onInstructionAnalysisStart(const Instruction *I) override {
723     // This function is called to store the initial cost of inlining before
724     // the given instruction was assessed.
725     if (!PrintInstructionComments)
726       return;
727     InstructionCostDetailMap[I].CostBefore = Cost;
728     InstructionCostDetailMap[I].ThresholdBefore = Threshold;
729   }
730 
731   void onInstructionAnalysisFinish(const Instruction *I) override {
732     // This function is called to find new values of cost and threshold after
733     // the instruction has been assessed.
734     if (!PrintInstructionComments)
735       return;
736     InstructionCostDetailMap[I].CostAfter = Cost;
737     InstructionCostDetailMap[I].ThresholdAfter = Threshold;
738   }
739 
740   bool isCostBenefitAnalysisEnabled() {
741     if (!PSI || !PSI->hasProfileSummary())
742       return false;
743 
744     if (!GetBFI)
745       return false;
746 
747     if (InlineEnableCostBenefitAnalysis.getNumOccurrences()) {
748       // Honor the explicit request from the user.
749       if (!InlineEnableCostBenefitAnalysis)
750         return false;
751     } else {
752       // Otherwise, require instrumentation profile.
753       if (!PSI->hasInstrumentationProfile())
754         return false;
755     }
756 
757     auto *Caller = CandidateCall.getParent()->getParent();
758     if (!Caller->getEntryCount())
759       return false;
760 
761     BlockFrequencyInfo *CallerBFI = &(GetBFI(*Caller));
762     if (!CallerBFI)
763       return false;
764 
765     // For now, limit to hot call site.
766     if (!PSI->isHotCallSite(CandidateCall, CallerBFI))
767       return false;
768 
769     // Make sure we have a nonzero entry count.
770     auto EntryCount = F.getEntryCount();
771     if (!EntryCount || !EntryCount->getCount())
772       return false;
773 
774     BlockFrequencyInfo *CalleeBFI = &(GetBFI(F));
775     if (!CalleeBFI)
776       return false;
777 
778     return true;
779   }
780 
781   // Determine whether we should inline the given call site, taking into account
782   // both the size cost and the cycle savings.  Return None if we don't have
783   // suficient profiling information to determine.
784   Optional<bool> costBenefitAnalysis() {
785     if (!CostBenefitAnalysisEnabled)
786       return None;
787 
788     // buildInlinerPipeline in the pass builder sets HotCallSiteThreshold to 0
789     // for the prelink phase of the AutoFDO + ThinLTO build.  Honor the logic by
790     // falling back to the cost-based metric.
791     // TODO: Improve this hacky condition.
792     if (Threshold == 0)
793       return None;
794 
795     assert(GetBFI);
796     BlockFrequencyInfo *CalleeBFI = &(GetBFI(F));
797     assert(CalleeBFI);
798 
799     // The cycle savings expressed as the sum of InlineConstants::InstrCost
800     // multiplied by the estimated dynamic count of each instruction we can
801     // avoid.  Savings come from the call site cost, such as argument setup and
802     // the call instruction, as well as the instructions that are folded.
803     //
804     // We use 128-bit APInt here to avoid potential overflow.  This variable
805     // should stay well below 10^^24 (or 2^^80) in practice.  This "worst" case
806     // assumes that we can avoid or fold a billion instructions, each with a
807     // profile count of 10^^15 -- roughly the number of cycles for a 24-hour
808     // period on a 4GHz machine.
809     APInt CycleSavings(128, 0);
810 
811     for (auto &BB : F) {
812       APInt CurrentSavings(128, 0);
813       for (auto &I : BB) {
814         if (BranchInst *BI = dyn_cast<BranchInst>(&I)) {
815           // Count a conditional branch as savings if it becomes unconditional.
816           if (BI->isConditional() &&
817               isa_and_nonnull<ConstantInt>(
818                   SimplifiedValues.lookup(BI->getCondition()))) {
819             CurrentSavings += InlineConstants::InstrCost;
820           }
821         } else if (Value *V = dyn_cast<Value>(&I)) {
822           // Count an instruction as savings if we can fold it.
823           if (SimplifiedValues.count(V)) {
824             CurrentSavings += InlineConstants::InstrCost;
825           }
826         }
827       }
828 
829       auto ProfileCount = CalleeBFI->getBlockProfileCount(&BB);
830       assert(ProfileCount);
831       CurrentSavings *= ProfileCount.getValue();
832       CycleSavings += CurrentSavings;
833     }
834 
835     // Compute the cycle savings per call.
836     auto EntryProfileCount = F.getEntryCount();
837     assert(EntryProfileCount && EntryProfileCount->getCount());
838     auto EntryCount = EntryProfileCount->getCount();
839     CycleSavings += EntryCount / 2;
840     CycleSavings = CycleSavings.udiv(EntryCount);
841 
842     // Compute the total savings for the call site.
843     auto *CallerBB = CandidateCall.getParent();
844     BlockFrequencyInfo *CallerBFI = &(GetBFI(*(CallerBB->getParent())));
845     CycleSavings += getCallsiteCost(this->CandidateCall, DL);
846     CycleSavings *= *CallerBFI->getBlockProfileCount(CallerBB);
847 
848     // Remove the cost of the cold basic blocks.
849     int Size = Cost - ColdSize;
850 
851     // Allow tiny callees to be inlined regardless of whether they meet the
852     // savings threshold.
853     Size = Size > InlineSizeAllowance ? Size - InlineSizeAllowance : 1;
854 
855     CostBenefit.emplace(APInt(128, Size), CycleSavings);
856 
857     // Return true if the savings justify the cost of inlining.  Specifically,
858     // we evaluate the following inequality:
859     //
860     //  CycleSavings      PSI->getOrCompHotCountThreshold()
861     // -------------- >= -----------------------------------
862     //       Size              InlineSavingsMultiplier
863     //
864     // Note that the left hand side is specific to a call site.  The right hand
865     // side is a constant for the entire executable.
866     APInt LHS = CycleSavings;
867     LHS *= InlineSavingsMultiplier;
868     APInt RHS(128, PSI->getOrCompHotCountThreshold());
869     RHS *= Size;
870     return LHS.uge(RHS);
871   }
872 
873   InlineResult finalizeAnalysis() override {
874     // Loops generally act a lot like calls in that they act like barriers to
875     // movement, require a certain amount of setup, etc. So when optimising for
876     // size, we penalise any call sites that perform loops. We do this after all
877     // other costs here, so will likely only be dealing with relatively small
878     // functions (and hence DT and LI will hopefully be cheap).
879     auto *Caller = CandidateCall.getFunction();
880     if (Caller->hasMinSize()) {
881       DominatorTree DT(F);
882       LoopInfo LI(DT);
883       int NumLoops = 0;
884       for (Loop *L : LI) {
885         // Ignore loops that will not be executed
886         if (DeadBlocks.count(L->getHeader()))
887           continue;
888         NumLoops++;
889       }
890       addCost(NumLoops * InlineConstants::LoopPenalty);
891     }
892 
893     // We applied the maximum possible vector bonus at the beginning. Now,
894     // subtract the excess bonus, if any, from the Threshold before
895     // comparing against Cost.
896     if (NumVectorInstructions <= NumInstructions / 10)
897       Threshold -= VectorBonus;
898     else if (NumVectorInstructions <= NumInstructions / 2)
899       Threshold -= VectorBonus / 2;
900 
901     if (Optional<int> AttrCost =
902             getStringFnAttrAsInt(CandidateCall, "function-inline-cost"))
903       Cost = *AttrCost;
904 
905     if (Optional<int> AttrCostMult = getStringFnAttrAsInt(
906             CandidateCall,
907             InlineConstants::FunctionInlineCostMultiplierAttributeName))
908       Cost *= *AttrCostMult;
909 
910     if (Optional<int> AttrThreshold =
911             getStringFnAttrAsInt(CandidateCall, "function-inline-threshold"))
912       Threshold = *AttrThreshold;
913 
914     if (auto Result = costBenefitAnalysis()) {
915       DecidedByCostBenefit = true;
916       if (*Result)
917         return InlineResult::success();
918       else
919         return InlineResult::failure("Cost over threshold.");
920     }
921 
922     if (IgnoreThreshold)
923       return InlineResult::success();
924 
925     DecidedByCostThreshold = true;
926     return Cost < std::max(1, Threshold)
927                ? InlineResult::success()
928                : InlineResult::failure("Cost over threshold.");
929   }
930 
931   bool shouldStop() override {
932     if (IgnoreThreshold || ComputeFullInlineCost)
933       return false;
934     // Bail out the moment we cross the threshold. This means we'll under-count
935     // the cost, but only when undercounting doesn't matter.
936     if (Cost < Threshold)
937       return false;
938     DecidedByCostThreshold = true;
939     return true;
940   }
941 
942   void onLoadEliminationOpportunity() override {
943     LoadEliminationCost += InlineConstants::InstrCost;
944   }
945 
946   InlineResult onAnalysisStart() override {
947     // Perform some tweaks to the cost and threshold based on the direct
948     // callsite information.
949 
950     // We want to more aggressively inline vector-dense kernels, so up the
951     // threshold, and we'll lower it if the % of vector instructions gets too
952     // low. Note that these bonuses are some what arbitrary and evolved over
953     // time by accident as much as because they are principled bonuses.
954     //
955     // FIXME: It would be nice to remove all such bonuses. At least it would be
956     // nice to base the bonus values on something more scientific.
957     assert(NumInstructions == 0);
958     assert(NumVectorInstructions == 0);
959 
960     // Update the threshold based on callsite properties
961     updateThreshold(CandidateCall, F);
962 
963     // While Threshold depends on commandline options that can take negative
964     // values, we want to enforce the invariant that the computed threshold and
965     // bonuses are non-negative.
966     assert(Threshold >= 0);
967     assert(SingleBBBonus >= 0);
968     assert(VectorBonus >= 0);
969 
970     // Speculatively apply all possible bonuses to Threshold. If cost exceeds
971     // this Threshold any time, and cost cannot decrease, we can stop processing
972     // the rest of the function body.
973     Threshold += (SingleBBBonus + VectorBonus);
974 
975     // Give out bonuses for the callsite, as the instructions setting them up
976     // will be gone after inlining.
977     addCost(-getCallsiteCost(this->CandidateCall, DL));
978 
979     // If this function uses the coldcc calling convention, prefer not to inline
980     // it.
981     if (F.getCallingConv() == CallingConv::Cold)
982       Cost += InlineConstants::ColdccPenalty;
983 
984     LLVM_DEBUG(dbgs() << "      Initial cost: " << Cost << "\n");
985 
986     // Check if we're done. This can happen due to bonuses and penalties.
987     if (Cost >= Threshold && !ComputeFullInlineCost)
988       return InlineResult::failure("high cost");
989 
990     return InlineResult::success();
991   }
992 
993 public:
994   InlineCostCallAnalyzer(
995       Function &Callee, CallBase &Call, const InlineParams &Params,
996       const TargetTransformInfo &TTI,
997       function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
998       function_ref<BlockFrequencyInfo &(Function &)> GetBFI = nullptr,
999       ProfileSummaryInfo *PSI = nullptr,
1000       OptimizationRemarkEmitter *ORE = nullptr, bool BoostIndirect = true,
1001       bool IgnoreThreshold = false)
1002       : CallAnalyzer(Callee, Call, TTI, GetAssumptionCache, GetBFI, PSI, ORE),
1003         ComputeFullInlineCost(OptComputeFullInlineCost ||
1004                               Params.ComputeFullInlineCost || ORE ||
1005                               isCostBenefitAnalysisEnabled()),
1006         Params(Params), Threshold(Params.DefaultThreshold),
1007         BoostIndirectCalls(BoostIndirect), IgnoreThreshold(IgnoreThreshold),
1008         CostBenefitAnalysisEnabled(isCostBenefitAnalysisEnabled()),
1009         Writer(this) {
1010     AllowRecursiveCall = *Params.AllowRecursiveCall;
1011   }
1012 
1013   /// Annotation Writer for instruction details
1014   InlineCostAnnotationWriter Writer;
1015 
1016   void dump();
1017 
1018   // Prints the same analysis as dump(), but its definition is not dependent
1019   // on the build.
1020   void print(raw_ostream &OS);
1021 
1022   Optional<InstructionCostDetail> getCostDetails(const Instruction *I) {
1023     if (InstructionCostDetailMap.find(I) != InstructionCostDetailMap.end())
1024       return InstructionCostDetailMap[I];
1025     return None;
1026   }
1027 
1028   virtual ~InlineCostCallAnalyzer() = default;
1029   int getThreshold() const { return Threshold; }
1030   int getCost() const { return Cost; }
1031   Optional<CostBenefitPair> getCostBenefitPair() { return CostBenefit; }
1032   bool wasDecidedByCostBenefit() const { return DecidedByCostBenefit; }
1033   bool wasDecidedByCostThreshold() const { return DecidedByCostThreshold; }
1034 };
1035 
1036 class InlineCostFeaturesAnalyzer final : public CallAnalyzer {
1037 private:
1038   InlineCostFeatures Cost = {};
1039 
1040   // FIXME: These constants are taken from the heuristic-based cost visitor.
1041   // These should be removed entirely in a later revision to avoid reliance on
1042   // heuristics in the ML inliner.
1043   static constexpr int JTCostMultiplier = 4;
1044   static constexpr int CaseClusterCostMultiplier = 2;
1045   static constexpr int SwitchCostMultiplier = 2;
1046 
1047   // FIXME: These are taken from the heuristic-based cost visitor: we should
1048   // eventually abstract these to the CallAnalyzer to avoid duplication.
1049   unsigned SROACostSavingOpportunities = 0;
1050   int VectorBonus = 0;
1051   int SingleBBBonus = 0;
1052   int Threshold = 5;
1053 
1054   DenseMap<AllocaInst *, unsigned> SROACosts;
1055 
1056   void increment(InlineCostFeatureIndex Feature, int64_t Delta = 1) {
1057     Cost[static_cast<size_t>(Feature)] += Delta;
1058   }
1059 
1060   void set(InlineCostFeatureIndex Feature, int64_t Value) {
1061     Cost[static_cast<size_t>(Feature)] = Value;
1062   }
1063 
1064   void onDisableSROA(AllocaInst *Arg) override {
1065     auto CostIt = SROACosts.find(Arg);
1066     if (CostIt == SROACosts.end())
1067       return;
1068 
1069     increment(InlineCostFeatureIndex::SROALosses, CostIt->second);
1070     SROACostSavingOpportunities -= CostIt->second;
1071     SROACosts.erase(CostIt);
1072   }
1073 
1074   void onDisableLoadElimination() override {
1075     set(InlineCostFeatureIndex::LoadElimination, 1);
1076   }
1077 
1078   void onCallPenalty() override {
1079     increment(InlineCostFeatureIndex::CallPenalty, CallPenalty);
1080   }
1081 
1082   void onCallArgumentSetup(const CallBase &Call) override {
1083     increment(InlineCostFeatureIndex::CallArgumentSetup,
1084               Call.arg_size() * InlineConstants::InstrCost);
1085   }
1086 
1087   void onLoadRelativeIntrinsic() override {
1088     increment(InlineCostFeatureIndex::LoadRelativeIntrinsic,
1089               3 * InlineConstants::InstrCost);
1090   }
1091 
1092   void onLoweredCall(Function *F, CallBase &Call,
1093                      bool IsIndirectCall) override {
1094     increment(InlineCostFeatureIndex::LoweredCallArgSetup,
1095               Call.arg_size() * InlineConstants::InstrCost);
1096 
1097     if (IsIndirectCall) {
1098       InlineParams IndirectCallParams = {/* DefaultThreshold*/ 0,
1099                                          /*HintThreshold*/ {},
1100                                          /*ColdThreshold*/ {},
1101                                          /*OptSizeThreshold*/ {},
1102                                          /*OptMinSizeThreshold*/ {},
1103                                          /*HotCallSiteThreshold*/ {},
1104                                          /*LocallyHotCallSiteThreshold*/ {},
1105                                          /*ColdCallSiteThreshold*/ {},
1106                                          /*ComputeFullInlineCost*/ true,
1107                                          /*EnableDeferral*/ true};
1108       IndirectCallParams.DefaultThreshold =
1109           InlineConstants::IndirectCallThreshold;
1110 
1111       InlineCostCallAnalyzer CA(*F, Call, IndirectCallParams, TTI,
1112                                 GetAssumptionCache, GetBFI, PSI, ORE, false,
1113                                 true);
1114       if (CA.analyze().isSuccess()) {
1115         increment(InlineCostFeatureIndex::NestedInlineCostEstimate,
1116                   CA.getCost());
1117         increment(InlineCostFeatureIndex::NestedInlines, 1);
1118       }
1119     } else {
1120       onCallPenalty();
1121     }
1122   }
1123 
1124   void onFinalizeSwitch(unsigned JumpTableSize,
1125                         unsigned NumCaseCluster) override {
1126 
1127     if (JumpTableSize) {
1128       int64_t JTCost =
1129           static_cast<int64_t>(JumpTableSize) * InlineConstants::InstrCost +
1130           JTCostMultiplier * InlineConstants::InstrCost;
1131       increment(InlineCostFeatureIndex::JumpTablePenalty, JTCost);
1132       return;
1133     }
1134 
1135     if (NumCaseCluster <= 3) {
1136       increment(InlineCostFeatureIndex::CaseClusterPenalty,
1137                 NumCaseCluster * CaseClusterCostMultiplier *
1138                     InlineConstants::InstrCost);
1139       return;
1140     }
1141 
1142     int64_t ExpectedNumberOfCompare =
1143         getExpectedNumberOfCompare(NumCaseCluster);
1144 
1145     int64_t SwitchCost = ExpectedNumberOfCompare * SwitchCostMultiplier *
1146                          InlineConstants::InstrCost;
1147     increment(InlineCostFeatureIndex::SwitchPenalty, SwitchCost);
1148   }
1149 
1150   void onMissedSimplification() override {
1151     increment(InlineCostFeatureIndex::UnsimplifiedCommonInstructions,
1152               InlineConstants::InstrCost);
1153   }
1154 
1155   void onInitializeSROAArg(AllocaInst *Arg) override { SROACosts[Arg] = 0; }
1156   void onAggregateSROAUse(AllocaInst *Arg) override {
1157     SROACosts.find(Arg)->second += InlineConstants::InstrCost;
1158     SROACostSavingOpportunities += InlineConstants::InstrCost;
1159   }
1160 
1161   void onBlockAnalyzed(const BasicBlock *BB) override {
1162     if (BB->getTerminator()->getNumSuccessors() > 1)
1163       set(InlineCostFeatureIndex::IsMultipleBlocks, 1);
1164     Threshold -= SingleBBBonus;
1165   }
1166 
1167   InlineResult finalizeAnalysis() override {
1168     auto *Caller = CandidateCall.getFunction();
1169     if (Caller->hasMinSize()) {
1170       DominatorTree DT(F);
1171       LoopInfo LI(DT);
1172       for (Loop *L : LI) {
1173         // Ignore loops that will not be executed
1174         if (DeadBlocks.count(L->getHeader()))
1175           continue;
1176         increment(InlineCostFeatureIndex::NumLoops,
1177                   InlineConstants::LoopPenalty);
1178       }
1179     }
1180     set(InlineCostFeatureIndex::DeadBlocks, DeadBlocks.size());
1181     set(InlineCostFeatureIndex::SimplifiedInstructions,
1182         NumInstructionsSimplified);
1183     set(InlineCostFeatureIndex::ConstantArgs, NumConstantArgs);
1184     set(InlineCostFeatureIndex::ConstantOffsetPtrArgs,
1185         NumConstantOffsetPtrArgs);
1186     set(InlineCostFeatureIndex::SROASavings, SROACostSavingOpportunities);
1187 
1188     if (NumVectorInstructions <= NumInstructions / 10)
1189       Threshold -= VectorBonus;
1190     else if (NumVectorInstructions <= NumInstructions / 2)
1191       Threshold -= VectorBonus / 2;
1192 
1193     set(InlineCostFeatureIndex::Threshold, Threshold);
1194 
1195     return InlineResult::success();
1196   }
1197 
1198   bool shouldStop() override { return false; }
1199 
1200   void onLoadEliminationOpportunity() override {
1201     increment(InlineCostFeatureIndex::LoadElimination, 1);
1202   }
1203 
1204   InlineResult onAnalysisStart() override {
1205     increment(InlineCostFeatureIndex::CallSiteCost,
1206               -1 * getCallsiteCost(this->CandidateCall, DL));
1207 
1208     set(InlineCostFeatureIndex::ColdCcPenalty,
1209         (F.getCallingConv() == CallingConv::Cold));
1210 
1211     set(InlineCostFeatureIndex::LastCallToStaticBonus,
1212         (F.hasLocalLinkage() && F.hasOneLiveUse() &&
1213          &F == CandidateCall.getCalledFunction()));
1214 
1215     // FIXME: we shouldn't repeat this logic in both the Features and Cost
1216     // analyzer - instead, we should abstract it to a common method in the
1217     // CallAnalyzer
1218     int SingleBBBonusPercent = 50;
1219     int VectorBonusPercent = TTI.getInlinerVectorBonusPercent();
1220     Threshold += TTI.adjustInliningThreshold(&CandidateCall);
1221     Threshold *= TTI.getInliningThresholdMultiplier();
1222     SingleBBBonus = Threshold * SingleBBBonusPercent / 100;
1223     VectorBonus = Threshold * VectorBonusPercent / 100;
1224     Threshold += (SingleBBBonus + VectorBonus);
1225 
1226     return InlineResult::success();
1227   }
1228 
1229 public:
1230   InlineCostFeaturesAnalyzer(
1231       const TargetTransformInfo &TTI,
1232       function_ref<AssumptionCache &(Function &)> &GetAssumptionCache,
1233       function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
1234       ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE, Function &Callee,
1235       CallBase &Call)
1236       : CallAnalyzer(Callee, Call, TTI, GetAssumptionCache, GetBFI, PSI) {}
1237 
1238   const InlineCostFeatures &features() const { return Cost; }
1239 };
1240 
1241 } // namespace
1242 
1243 /// Test whether the given value is an Alloca-derived function argument.
1244 bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
1245   return SROAArgValues.count(V);
1246 }
1247 
1248 void CallAnalyzer::disableSROAForArg(AllocaInst *SROAArg) {
1249   onDisableSROA(SROAArg);
1250   EnabledSROAAllocas.erase(SROAArg);
1251   disableLoadElimination();
1252 }
1253 
1254 void InlineCostAnnotationWriter::emitInstructionAnnot(
1255     const Instruction *I, formatted_raw_ostream &OS) {
1256   // The cost of inlining of the given instruction is printed always.
1257   // The threshold delta is printed only when it is non-zero. It happens
1258   // when we decided to give a bonus at a particular instruction.
1259   Optional<InstructionCostDetail> Record = ICCA->getCostDetails(I);
1260   if (!Record)
1261     OS << "; No analysis for the instruction";
1262   else {
1263     OS << "; cost before = " << Record->CostBefore
1264        << ", cost after = " << Record->CostAfter
1265        << ", threshold before = " << Record->ThresholdBefore
1266        << ", threshold after = " << Record->ThresholdAfter << ", ";
1267     OS << "cost delta = " << Record->getCostDelta();
1268     if (Record->hasThresholdChanged())
1269       OS << ", threshold delta = " << Record->getThresholdDelta();
1270   }
1271   auto C = ICCA->getSimplifiedValue(const_cast<Instruction *>(I));
1272   if (C) {
1273     OS << ", simplified to ";
1274     (*C)->print(OS, true);
1275   }
1276   OS << "\n";
1277 }
1278 
1279 /// If 'V' maps to a SROA candidate, disable SROA for it.
1280 void CallAnalyzer::disableSROA(Value *V) {
1281   if (auto *SROAArg = getSROAArgForValueOrNull(V)) {
1282     disableSROAForArg(SROAArg);
1283   }
1284 }
1285 
1286 void CallAnalyzer::disableLoadElimination() {
1287   if (EnableLoadElimination) {
1288     onDisableLoadElimination();
1289     EnableLoadElimination = false;
1290   }
1291 }
1292 
1293 /// Accumulate a constant GEP offset into an APInt if possible.
1294 ///
1295 /// Returns false if unable to compute the offset for any reason. Respects any
1296 /// simplified values known during the analysis of this callsite.
1297 bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
1298   unsigned IntPtrWidth = DL.getIndexTypeSizeInBits(GEP.getType());
1299   assert(IntPtrWidth == Offset.getBitWidth());
1300 
1301   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
1302        GTI != GTE; ++GTI) {
1303     ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
1304     if (!OpC)
1305       if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
1306         OpC = dyn_cast<ConstantInt>(SimpleOp);
1307     if (!OpC)
1308       return false;
1309     if (OpC->isZero())
1310       continue;
1311 
1312     // Handle a struct index, which adds its field offset to the pointer.
1313     if (StructType *STy = GTI.getStructTypeOrNull()) {
1314       unsigned ElementIdx = OpC->getZExtValue();
1315       const StructLayout *SL = DL.getStructLayout(STy);
1316       Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
1317       continue;
1318     }
1319 
1320     APInt TypeSize(IntPtrWidth, DL.getTypeAllocSize(GTI.getIndexedType()));
1321     Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
1322   }
1323   return true;
1324 }
1325 
1326 /// Use TTI to check whether a GEP is free.
1327 ///
1328 /// Respects any simplified values known during the analysis of this callsite.
1329 bool CallAnalyzer::isGEPFree(GetElementPtrInst &GEP) {
1330   SmallVector<Value *, 4> Operands;
1331   Operands.push_back(GEP.getOperand(0));
1332   for (const Use &Op : GEP.indices())
1333     if (Constant *SimpleOp = SimplifiedValues.lookup(Op))
1334       Operands.push_back(SimpleOp);
1335     else
1336       Operands.push_back(Op);
1337   return TTI.getUserCost(&GEP, Operands,
1338                          TargetTransformInfo::TCK_SizeAndLatency) ==
1339          TargetTransformInfo::TCC_Free;
1340 }
1341 
1342 bool CallAnalyzer::visitAlloca(AllocaInst &I) {
1343   disableSROA(I.getOperand(0));
1344 
1345   // Check whether inlining will turn a dynamic alloca into a static
1346   // alloca and handle that case.
1347   if (I.isArrayAllocation()) {
1348     Constant *Size = SimplifiedValues.lookup(I.getArraySize());
1349     if (auto *AllocSize = dyn_cast_or_null<ConstantInt>(Size)) {
1350       // Sometimes a dynamic alloca could be converted into a static alloca
1351       // after this constant prop, and become a huge static alloca on an
1352       // unconditional CFG path. Avoid inlining if this is going to happen above
1353       // a threshold.
1354       // FIXME: If the threshold is removed or lowered too much, we could end up
1355       // being too pessimistic and prevent inlining non-problematic code. This
1356       // could result in unintended perf regressions. A better overall strategy
1357       // is needed to track stack usage during inlining.
1358       Type *Ty = I.getAllocatedType();
1359       AllocatedSize = SaturatingMultiplyAdd(
1360           AllocSize->getLimitedValue(),
1361           DL.getTypeAllocSize(Ty).getKnownMinSize(), AllocatedSize);
1362       if (AllocatedSize > InlineConstants::MaxSimplifiedDynamicAllocaToInline)
1363         HasDynamicAlloca = true;
1364       return false;
1365     }
1366   }
1367 
1368   // Accumulate the allocated size.
1369   if (I.isStaticAlloca()) {
1370     Type *Ty = I.getAllocatedType();
1371     AllocatedSize =
1372         SaturatingAdd(DL.getTypeAllocSize(Ty).getKnownMinSize(), AllocatedSize);
1373   }
1374 
1375   // FIXME: This is overly conservative. Dynamic allocas are inefficient for
1376   // a variety of reasons, and so we would like to not inline them into
1377   // functions which don't currently have a dynamic alloca. This simply
1378   // disables inlining altogether in the presence of a dynamic alloca.
1379   if (!I.isStaticAlloca())
1380     HasDynamicAlloca = true;
1381 
1382   return false;
1383 }
1384 
1385 bool CallAnalyzer::visitPHI(PHINode &I) {
1386   // FIXME: We need to propagate SROA *disabling* through phi nodes, even
1387   // though we don't want to propagate it's bonuses. The idea is to disable
1388   // SROA if it *might* be used in an inappropriate manner.
1389 
1390   // Phi nodes are always zero-cost.
1391   // FIXME: Pointer sizes may differ between different address spaces, so do we
1392   // need to use correct address space in the call to getPointerSizeInBits here?
1393   // Or could we skip the getPointerSizeInBits call completely? As far as I can
1394   // see the ZeroOffset is used as a dummy value, so we can probably use any
1395   // bit width for the ZeroOffset?
1396   APInt ZeroOffset = APInt::getZero(DL.getPointerSizeInBits(0));
1397   bool CheckSROA = I.getType()->isPointerTy();
1398 
1399   // Track the constant or pointer with constant offset we've seen so far.
1400   Constant *FirstC = nullptr;
1401   std::pair<Value *, APInt> FirstBaseAndOffset = {nullptr, ZeroOffset};
1402   Value *FirstV = nullptr;
1403 
1404   for (unsigned i = 0, e = I.getNumIncomingValues(); i != e; ++i) {
1405     BasicBlock *Pred = I.getIncomingBlock(i);
1406     // If the incoming block is dead, skip the incoming block.
1407     if (DeadBlocks.count(Pred))
1408       continue;
1409     // If the parent block of phi is not the known successor of the incoming
1410     // block, skip the incoming block.
1411     BasicBlock *KnownSuccessor = KnownSuccessors[Pred];
1412     if (KnownSuccessor && KnownSuccessor != I.getParent())
1413       continue;
1414 
1415     Value *V = I.getIncomingValue(i);
1416     // If the incoming value is this phi itself, skip the incoming value.
1417     if (&I == V)
1418       continue;
1419 
1420     Constant *C = dyn_cast<Constant>(V);
1421     if (!C)
1422       C = SimplifiedValues.lookup(V);
1423 
1424     std::pair<Value *, APInt> BaseAndOffset = {nullptr, ZeroOffset};
1425     if (!C && CheckSROA)
1426       BaseAndOffset = ConstantOffsetPtrs.lookup(V);
1427 
1428     if (!C && !BaseAndOffset.first)
1429       // The incoming value is neither a constant nor a pointer with constant
1430       // offset, exit early.
1431       return true;
1432 
1433     if (FirstC) {
1434       if (FirstC == C)
1435         // If we've seen a constant incoming value before and it is the same
1436         // constant we see this time, continue checking the next incoming value.
1437         continue;
1438       // Otherwise early exit because we either see a different constant or saw
1439       // a constant before but we have a pointer with constant offset this time.
1440       return true;
1441     }
1442 
1443     if (FirstV) {
1444       // The same logic as above, but check pointer with constant offset here.
1445       if (FirstBaseAndOffset == BaseAndOffset)
1446         continue;
1447       return true;
1448     }
1449 
1450     if (C) {
1451       // This is the 1st time we've seen a constant, record it.
1452       FirstC = C;
1453       continue;
1454     }
1455 
1456     // The remaining case is that this is the 1st time we've seen a pointer with
1457     // constant offset, record it.
1458     FirstV = V;
1459     FirstBaseAndOffset = BaseAndOffset;
1460   }
1461 
1462   // Check if we can map phi to a constant.
1463   if (FirstC) {
1464     SimplifiedValues[&I] = FirstC;
1465     return true;
1466   }
1467 
1468   // Check if we can map phi to a pointer with constant offset.
1469   if (FirstBaseAndOffset.first) {
1470     ConstantOffsetPtrs[&I] = FirstBaseAndOffset;
1471 
1472     if (auto *SROAArg = getSROAArgForValueOrNull(FirstV))
1473       SROAArgValues[&I] = SROAArg;
1474   }
1475 
1476   return true;
1477 }
1478 
1479 /// Check we can fold GEPs of constant-offset call site argument pointers.
1480 /// This requires target data and inbounds GEPs.
1481 ///
1482 /// \return true if the specified GEP can be folded.
1483 bool CallAnalyzer::canFoldInboundsGEP(GetElementPtrInst &I) {
1484   // Check if we have a base + offset for the pointer.
1485   std::pair<Value *, APInt> BaseAndOffset =
1486       ConstantOffsetPtrs.lookup(I.getPointerOperand());
1487   if (!BaseAndOffset.first)
1488     return false;
1489 
1490   // Check if the offset of this GEP is constant, and if so accumulate it
1491   // into Offset.
1492   if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second))
1493     return false;
1494 
1495   // Add the result as a new mapping to Base + Offset.
1496   ConstantOffsetPtrs[&I] = BaseAndOffset;
1497 
1498   return true;
1499 }
1500 
1501 bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
1502   auto *SROAArg = getSROAArgForValueOrNull(I.getPointerOperand());
1503 
1504   // Lambda to check whether a GEP's indices are all constant.
1505   auto IsGEPOffsetConstant = [&](GetElementPtrInst &GEP) {
1506     for (const Use &Op : GEP.indices())
1507       if (!isa<Constant>(Op) && !SimplifiedValues.lookup(Op))
1508         return false;
1509     return true;
1510   };
1511 
1512   if (!DisableGEPConstOperand)
1513     if (simplifyInstruction(I))
1514       return true;
1515 
1516   if ((I.isInBounds() && canFoldInboundsGEP(I)) || IsGEPOffsetConstant(I)) {
1517     if (SROAArg)
1518       SROAArgValues[&I] = SROAArg;
1519 
1520     // Constant GEPs are modeled as free.
1521     return true;
1522   }
1523 
1524   // Variable GEPs will require math and will disable SROA.
1525   if (SROAArg)
1526     disableSROAForArg(SROAArg);
1527   return isGEPFree(I);
1528 }
1529 
1530 /// Simplify \p I if its operands are constants and update SimplifiedValues.
1531 bool CallAnalyzer::simplifyInstruction(Instruction &I) {
1532   SmallVector<Constant *> COps;
1533   for (Value *Op : I.operands()) {
1534     Constant *COp = dyn_cast<Constant>(Op);
1535     if (!COp)
1536       COp = SimplifiedValues.lookup(Op);
1537     if (!COp)
1538       return false;
1539     COps.push_back(COp);
1540   }
1541   auto *C = ConstantFoldInstOperands(&I, COps, DL);
1542   if (!C)
1543     return false;
1544   SimplifiedValues[&I] = C;
1545   return true;
1546 }
1547 
1548 /// Try to simplify a call to llvm.is.constant.
1549 ///
1550 /// Duplicate the argument checking from CallAnalyzer::simplifyCallSite since
1551 /// we expect calls of this specific intrinsic to be infrequent.
1552 ///
1553 /// FIXME: Given that we know CB's parent (F) caller
1554 /// (CandidateCall->getParent()->getParent()), we might be able to determine
1555 /// whether inlining F into F's caller would change how the call to
1556 /// llvm.is.constant would evaluate.
1557 bool CallAnalyzer::simplifyIntrinsicCallIsConstant(CallBase &CB) {
1558   Value *Arg = CB.getArgOperand(0);
1559   auto *C = dyn_cast<Constant>(Arg);
1560 
1561   if (!C)
1562     C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(Arg));
1563 
1564   Type *RT = CB.getFunctionType()->getReturnType();
1565   SimplifiedValues[&CB] = ConstantInt::get(RT, C ? 1 : 0);
1566   return true;
1567 }
1568 
1569 bool CallAnalyzer::visitBitCast(BitCastInst &I) {
1570   // Propagate constants through bitcasts.
1571   if (simplifyInstruction(I))
1572     return true;
1573 
1574   // Track base/offsets through casts
1575   std::pair<Value *, APInt> BaseAndOffset =
1576       ConstantOffsetPtrs.lookup(I.getOperand(0));
1577   // Casts don't change the offset, just wrap it up.
1578   if (BaseAndOffset.first)
1579     ConstantOffsetPtrs[&I] = BaseAndOffset;
1580 
1581   // Also look for SROA candidates here.
1582   if (auto *SROAArg = getSROAArgForValueOrNull(I.getOperand(0)))
1583     SROAArgValues[&I] = SROAArg;
1584 
1585   // Bitcasts are always zero cost.
1586   return true;
1587 }
1588 
1589 bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
1590   // Propagate constants through ptrtoint.
1591   if (simplifyInstruction(I))
1592     return true;
1593 
1594   // Track base/offset pairs when converted to a plain integer provided the
1595   // integer is large enough to represent the pointer.
1596   unsigned IntegerSize = I.getType()->getScalarSizeInBits();
1597   unsigned AS = I.getOperand(0)->getType()->getPointerAddressSpace();
1598   if (IntegerSize == DL.getPointerSizeInBits(AS)) {
1599     std::pair<Value *, APInt> BaseAndOffset =
1600         ConstantOffsetPtrs.lookup(I.getOperand(0));
1601     if (BaseAndOffset.first)
1602       ConstantOffsetPtrs[&I] = BaseAndOffset;
1603   }
1604 
1605   // This is really weird. Technically, ptrtoint will disable SROA. However,
1606   // unless that ptrtoint is *used* somewhere in the live basic blocks after
1607   // inlining, it will be nuked, and SROA should proceed. All of the uses which
1608   // would block SROA would also block SROA if applied directly to a pointer,
1609   // and so we can just add the integer in here. The only places where SROA is
1610   // preserved either cannot fire on an integer, or won't in-and-of themselves
1611   // disable SROA (ext) w/o some later use that we would see and disable.
1612   if (auto *SROAArg = getSROAArgForValueOrNull(I.getOperand(0)))
1613     SROAArgValues[&I] = SROAArg;
1614 
1615   return TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency) ==
1616          TargetTransformInfo::TCC_Free;
1617 }
1618 
1619 bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
1620   // Propagate constants through ptrtoint.
1621   if (simplifyInstruction(I))
1622     return true;
1623 
1624   // Track base/offset pairs when round-tripped through a pointer without
1625   // modifications provided the integer is not too large.
1626   Value *Op = I.getOperand(0);
1627   unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
1628   if (IntegerSize <= DL.getPointerTypeSizeInBits(I.getType())) {
1629     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
1630     if (BaseAndOffset.first)
1631       ConstantOffsetPtrs[&I] = BaseAndOffset;
1632   }
1633 
1634   // "Propagate" SROA here in the same manner as we do for ptrtoint above.
1635   if (auto *SROAArg = getSROAArgForValueOrNull(Op))
1636     SROAArgValues[&I] = SROAArg;
1637 
1638   return TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency) ==
1639          TargetTransformInfo::TCC_Free;
1640 }
1641 
1642 bool CallAnalyzer::visitCastInst(CastInst &I) {
1643   // Propagate constants through casts.
1644   if (simplifyInstruction(I))
1645     return true;
1646 
1647   // Disable SROA in the face of arbitrary casts we don't explicitly list
1648   // elsewhere.
1649   disableSROA(I.getOperand(0));
1650 
1651   // If this is a floating-point cast, and the target says this operation
1652   // is expensive, this may eventually become a library call. Treat the cost
1653   // as such.
1654   switch (I.getOpcode()) {
1655   case Instruction::FPTrunc:
1656   case Instruction::FPExt:
1657   case Instruction::UIToFP:
1658   case Instruction::SIToFP:
1659   case Instruction::FPToUI:
1660   case Instruction::FPToSI:
1661     if (TTI.getFPOpCost(I.getType()) == TargetTransformInfo::TCC_Expensive)
1662       onCallPenalty();
1663     break;
1664   default:
1665     break;
1666   }
1667 
1668   return TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency) ==
1669          TargetTransformInfo::TCC_Free;
1670 }
1671 
1672 bool CallAnalyzer::paramHasAttr(Argument *A, Attribute::AttrKind Attr) {
1673   return CandidateCall.paramHasAttr(A->getArgNo(), Attr);
1674 }
1675 
1676 bool CallAnalyzer::isKnownNonNullInCallee(Value *V) {
1677   // Does the *call site* have the NonNull attribute set on an argument?  We
1678   // use the attribute on the call site to memoize any analysis done in the
1679   // caller. This will also trip if the callee function has a non-null
1680   // parameter attribute, but that's a less interesting case because hopefully
1681   // the callee would already have been simplified based on that.
1682   if (Argument *A = dyn_cast<Argument>(V))
1683     if (paramHasAttr(A, Attribute::NonNull))
1684       return true;
1685 
1686   // Is this an alloca in the caller?  This is distinct from the attribute case
1687   // above because attributes aren't updated within the inliner itself and we
1688   // always want to catch the alloca derived case.
1689   if (isAllocaDerivedArg(V))
1690     // We can actually predict the result of comparisons between an
1691     // alloca-derived value and null. Note that this fires regardless of
1692     // SROA firing.
1693     return true;
1694 
1695   return false;
1696 }
1697 
1698 bool CallAnalyzer::allowSizeGrowth(CallBase &Call) {
1699   // If the normal destination of the invoke or the parent block of the call
1700   // site is unreachable-terminated, there is little point in inlining this
1701   // unless there is literally zero cost.
1702   // FIXME: Note that it is possible that an unreachable-terminated block has a
1703   // hot entry. For example, in below scenario inlining hot_call_X() may be
1704   // beneficial :
1705   // main() {
1706   //   hot_call_1();
1707   //   ...
1708   //   hot_call_N()
1709   //   exit(0);
1710   // }
1711   // For now, we are not handling this corner case here as it is rare in real
1712   // code. In future, we should elaborate this based on BPI and BFI in more
1713   // general threshold adjusting heuristics in updateThreshold().
1714   if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
1715     if (isa<UnreachableInst>(II->getNormalDest()->getTerminator()))
1716       return false;
1717   } else if (isa<UnreachableInst>(Call.getParent()->getTerminator()))
1718     return false;
1719 
1720   return true;
1721 }
1722 
1723 bool InlineCostCallAnalyzer::isColdCallSite(CallBase &Call,
1724                                             BlockFrequencyInfo *CallerBFI) {
1725   // If global profile summary is available, then callsite's coldness is
1726   // determined based on that.
1727   if (PSI && PSI->hasProfileSummary())
1728     return PSI->isColdCallSite(Call, CallerBFI);
1729 
1730   // Otherwise we need BFI to be available.
1731   if (!CallerBFI)
1732     return false;
1733 
1734   // Determine if the callsite is cold relative to caller's entry. We could
1735   // potentially cache the computation of scaled entry frequency, but the added
1736   // complexity is not worth it unless this scaling shows up high in the
1737   // profiles.
1738   const BranchProbability ColdProb(ColdCallSiteRelFreq, 100);
1739   auto CallSiteBB = Call.getParent();
1740   auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB);
1741   auto CallerEntryFreq =
1742       CallerBFI->getBlockFreq(&(Call.getCaller()->getEntryBlock()));
1743   return CallSiteFreq < CallerEntryFreq * ColdProb;
1744 }
1745 
1746 Optional<int>
1747 InlineCostCallAnalyzer::getHotCallSiteThreshold(CallBase &Call,
1748                                                 BlockFrequencyInfo *CallerBFI) {
1749 
1750   // If global profile summary is available, then callsite's hotness is
1751   // determined based on that.
1752   if (PSI && PSI->hasProfileSummary() && PSI->isHotCallSite(Call, CallerBFI))
1753     return Params.HotCallSiteThreshold;
1754 
1755   // Otherwise we need BFI to be available and to have a locally hot callsite
1756   // threshold.
1757   if (!CallerBFI || !Params.LocallyHotCallSiteThreshold)
1758     return None;
1759 
1760   // Determine if the callsite is hot relative to caller's entry. We could
1761   // potentially cache the computation of scaled entry frequency, but the added
1762   // complexity is not worth it unless this scaling shows up high in the
1763   // profiles.
1764   auto CallSiteBB = Call.getParent();
1765   auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB).getFrequency();
1766   auto CallerEntryFreq = CallerBFI->getEntryFreq();
1767   if (CallSiteFreq >= CallerEntryFreq * HotCallSiteRelFreq)
1768     return Params.LocallyHotCallSiteThreshold;
1769 
1770   // Otherwise treat it normally.
1771   return None;
1772 }
1773 
1774 void InlineCostCallAnalyzer::updateThreshold(CallBase &Call, Function &Callee) {
1775   // If no size growth is allowed for this inlining, set Threshold to 0.
1776   if (!allowSizeGrowth(Call)) {
1777     Threshold = 0;
1778     return;
1779   }
1780 
1781   Function *Caller = Call.getCaller();
1782 
1783   // return min(A, B) if B is valid.
1784   auto MinIfValid = [](int A, Optional<int> B) {
1785     return B ? std::min(A, B.getValue()) : A;
1786   };
1787 
1788   // return max(A, B) if B is valid.
1789   auto MaxIfValid = [](int A, Optional<int> B) {
1790     return B ? std::max(A, B.getValue()) : A;
1791   };
1792 
1793   // Various bonus percentages. These are multiplied by Threshold to get the
1794   // bonus values.
1795   // SingleBBBonus: This bonus is applied if the callee has a single reachable
1796   // basic block at the given callsite context. This is speculatively applied
1797   // and withdrawn if more than one basic block is seen.
1798   //
1799   // LstCallToStaticBonus: This large bonus is applied to ensure the inlining
1800   // of the last call to a static function as inlining such functions is
1801   // guaranteed to reduce code size.
1802   //
1803   // These bonus percentages may be set to 0 based on properties of the caller
1804   // and the callsite.
1805   int SingleBBBonusPercent = 50;
1806   int VectorBonusPercent = TTI.getInlinerVectorBonusPercent();
1807   int LastCallToStaticBonus = InlineConstants::LastCallToStaticBonus;
1808 
1809   // Lambda to set all the above bonus and bonus percentages to 0.
1810   auto DisallowAllBonuses = [&]() {
1811     SingleBBBonusPercent = 0;
1812     VectorBonusPercent = 0;
1813     LastCallToStaticBonus = 0;
1814   };
1815 
1816   // Use the OptMinSizeThreshold or OptSizeThreshold knob if they are available
1817   // and reduce the threshold if the caller has the necessary attribute.
1818   if (Caller->hasMinSize()) {
1819     Threshold = MinIfValid(Threshold, Params.OptMinSizeThreshold);
1820     // For minsize, we want to disable the single BB bonus and the vector
1821     // bonuses, but not the last-call-to-static bonus. Inlining the last call to
1822     // a static function will, at the minimum, eliminate the parameter setup and
1823     // call/return instructions.
1824     SingleBBBonusPercent = 0;
1825     VectorBonusPercent = 0;
1826   } else if (Caller->hasOptSize())
1827     Threshold = MinIfValid(Threshold, Params.OptSizeThreshold);
1828 
1829   // Adjust the threshold based on inlinehint attribute and profile based
1830   // hotness information if the caller does not have MinSize attribute.
1831   if (!Caller->hasMinSize()) {
1832     if (Callee.hasFnAttribute(Attribute::InlineHint))
1833       Threshold = MaxIfValid(Threshold, Params.HintThreshold);
1834 
1835     // FIXME: After switching to the new passmanager, simplify the logic below
1836     // by checking only the callsite hotness/coldness as we will reliably
1837     // have local profile information.
1838     //
1839     // Callsite hotness and coldness can be determined if sample profile is
1840     // used (which adds hotness metadata to calls) or if caller's
1841     // BlockFrequencyInfo is available.
1842     BlockFrequencyInfo *CallerBFI = GetBFI ? &(GetBFI(*Caller)) : nullptr;
1843     auto HotCallSiteThreshold = getHotCallSiteThreshold(Call, CallerBFI);
1844     if (!Caller->hasOptSize() && HotCallSiteThreshold) {
1845       LLVM_DEBUG(dbgs() << "Hot callsite.\n");
1846       // FIXME: This should update the threshold only if it exceeds the
1847       // current threshold, but AutoFDO + ThinLTO currently relies on this
1848       // behavior to prevent inlining of hot callsites during ThinLTO
1849       // compile phase.
1850       Threshold = *HotCallSiteThreshold;
1851     } else if (isColdCallSite(Call, CallerBFI)) {
1852       LLVM_DEBUG(dbgs() << "Cold callsite.\n");
1853       // Do not apply bonuses for a cold callsite including the
1854       // LastCallToStatic bonus. While this bonus might result in code size
1855       // reduction, it can cause the size of a non-cold caller to increase
1856       // preventing it from being inlined.
1857       DisallowAllBonuses();
1858       Threshold = MinIfValid(Threshold, Params.ColdCallSiteThreshold);
1859     } else if (PSI) {
1860       // Use callee's global profile information only if we have no way of
1861       // determining this via callsite information.
1862       if (PSI->isFunctionEntryHot(&Callee)) {
1863         LLVM_DEBUG(dbgs() << "Hot callee.\n");
1864         // If callsite hotness can not be determined, we may still know
1865         // that the callee is hot and treat it as a weaker hint for threshold
1866         // increase.
1867         Threshold = MaxIfValid(Threshold, Params.HintThreshold);
1868       } else if (PSI->isFunctionEntryCold(&Callee)) {
1869         LLVM_DEBUG(dbgs() << "Cold callee.\n");
1870         // Do not apply bonuses for a cold callee including the
1871         // LastCallToStatic bonus. While this bonus might result in code size
1872         // reduction, it can cause the size of a non-cold caller to increase
1873         // preventing it from being inlined.
1874         DisallowAllBonuses();
1875         Threshold = MinIfValid(Threshold, Params.ColdThreshold);
1876       }
1877     }
1878   }
1879 
1880   Threshold += TTI.adjustInliningThreshold(&Call);
1881 
1882   // Finally, take the target-specific inlining threshold multiplier into
1883   // account.
1884   Threshold *= TTI.getInliningThresholdMultiplier();
1885 
1886   SingleBBBonus = Threshold * SingleBBBonusPercent / 100;
1887   VectorBonus = Threshold * VectorBonusPercent / 100;
1888 
1889   bool OnlyOneCallAndLocalLinkage = F.hasLocalLinkage() && F.hasOneLiveUse() &&
1890                                     &F == Call.getCalledFunction();
1891   // If there is only one call of the function, and it has internal linkage,
1892   // the cost of inlining it drops dramatically. It may seem odd to update
1893   // Cost in updateThreshold, but the bonus depends on the logic in this method.
1894   if (OnlyOneCallAndLocalLinkage)
1895     Cost -= LastCallToStaticBonus;
1896 }
1897 
1898 bool CallAnalyzer::visitCmpInst(CmpInst &I) {
1899   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1900   // First try to handle simplified comparisons.
1901   if (simplifyInstruction(I))
1902     return true;
1903 
1904   if (I.getOpcode() == Instruction::FCmp)
1905     return false;
1906 
1907   // Otherwise look for a comparison between constant offset pointers with
1908   // a common base.
1909   Value *LHSBase, *RHSBase;
1910   APInt LHSOffset, RHSOffset;
1911   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
1912   if (LHSBase) {
1913     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
1914     if (RHSBase && LHSBase == RHSBase) {
1915       // We have common bases, fold the icmp to a constant based on the
1916       // offsets.
1917       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
1918       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
1919       if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
1920         SimplifiedValues[&I] = C;
1921         ++NumConstantPtrCmps;
1922         return true;
1923       }
1924     }
1925   }
1926 
1927   // If the comparison is an equality comparison with null, we can simplify it
1928   // if we know the value (argument) can't be null
1929   if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)) &&
1930       isKnownNonNullInCallee(I.getOperand(0))) {
1931     bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
1932     SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
1933                                       : ConstantInt::getFalse(I.getType());
1934     return true;
1935   }
1936   return handleSROA(I.getOperand(0), isa<ConstantPointerNull>(I.getOperand(1)));
1937 }
1938 
1939 bool CallAnalyzer::visitSub(BinaryOperator &I) {
1940   // Try to handle a special case: we can fold computing the difference of two
1941   // constant-related pointers.
1942   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1943   Value *LHSBase, *RHSBase;
1944   APInt LHSOffset, RHSOffset;
1945   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
1946   if (LHSBase) {
1947     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
1948     if (RHSBase && LHSBase == RHSBase) {
1949       // We have common bases, fold the subtract to a constant based on the
1950       // offsets.
1951       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
1952       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
1953       if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
1954         SimplifiedValues[&I] = C;
1955         ++NumConstantPtrDiffs;
1956         return true;
1957       }
1958     }
1959   }
1960 
1961   // Otherwise, fall back to the generic logic for simplifying and handling
1962   // instructions.
1963   return Base::visitSub(I);
1964 }
1965 
1966 bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
1967   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1968   Constant *CLHS = dyn_cast<Constant>(LHS);
1969   if (!CLHS)
1970     CLHS = SimplifiedValues.lookup(LHS);
1971   Constant *CRHS = dyn_cast<Constant>(RHS);
1972   if (!CRHS)
1973     CRHS = SimplifiedValues.lookup(RHS);
1974 
1975   Value *SimpleV = nullptr;
1976   if (auto FI = dyn_cast<FPMathOperator>(&I))
1977     SimpleV = simplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS,
1978                             FI->getFastMathFlags(), DL);
1979   else
1980     SimpleV =
1981         simplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS, DL);
1982 
1983   if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
1984     SimplifiedValues[&I] = C;
1985 
1986   if (SimpleV)
1987     return true;
1988 
1989   // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
1990   disableSROA(LHS);
1991   disableSROA(RHS);
1992 
1993   // If the instruction is floating point, and the target says this operation
1994   // is expensive, this may eventually become a library call. Treat the cost
1995   // as such. Unless it's fneg which can be implemented with an xor.
1996   using namespace llvm::PatternMatch;
1997   if (I.getType()->isFloatingPointTy() &&
1998       TTI.getFPOpCost(I.getType()) == TargetTransformInfo::TCC_Expensive &&
1999       !match(&I, m_FNeg(m_Value())))
2000     onCallPenalty();
2001 
2002   return false;
2003 }
2004 
2005 bool CallAnalyzer::visitFNeg(UnaryOperator &I) {
2006   Value *Op = I.getOperand(0);
2007   Constant *COp = dyn_cast<Constant>(Op);
2008   if (!COp)
2009     COp = SimplifiedValues.lookup(Op);
2010 
2011   Value *SimpleV = simplifyFNegInst(
2012       COp ? COp : Op, cast<FPMathOperator>(I).getFastMathFlags(), DL);
2013 
2014   if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
2015     SimplifiedValues[&I] = C;
2016 
2017   if (SimpleV)
2018     return true;
2019 
2020   // Disable any SROA on arguments to arbitrary, unsimplified fneg.
2021   disableSROA(Op);
2022 
2023   return false;
2024 }
2025 
2026 bool CallAnalyzer::visitLoad(LoadInst &I) {
2027   if (handleSROA(I.getPointerOperand(), I.isSimple()))
2028     return true;
2029 
2030   // If the data is already loaded from this address and hasn't been clobbered
2031   // by any stores or calls, this load is likely to be redundant and can be
2032   // eliminated.
2033   if (EnableLoadElimination &&
2034       !LoadAddrSet.insert(I.getPointerOperand()).second && I.isUnordered()) {
2035     onLoadEliminationOpportunity();
2036     return true;
2037   }
2038 
2039   return false;
2040 }
2041 
2042 bool CallAnalyzer::visitStore(StoreInst &I) {
2043   if (handleSROA(I.getPointerOperand(), I.isSimple()))
2044     return true;
2045 
2046   // The store can potentially clobber loads and prevent repeated loads from
2047   // being eliminated.
2048   // FIXME:
2049   // 1. We can probably keep an initial set of eliminatable loads substracted
2050   // from the cost even when we finally see a store. We just need to disable
2051   // *further* accumulation of elimination savings.
2052   // 2. We should probably at some point thread MemorySSA for the callee into
2053   // this and then use that to actually compute *really* precise savings.
2054   disableLoadElimination();
2055   return false;
2056 }
2057 
2058 bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) {
2059   // Constant folding for extract value is trivial.
2060   if (simplifyInstruction(I))
2061     return true;
2062 
2063   // SROA can't look through these, but they may be free.
2064   return Base::visitExtractValue(I);
2065 }
2066 
2067 bool CallAnalyzer::visitInsertValue(InsertValueInst &I) {
2068   // Constant folding for insert value is trivial.
2069   if (simplifyInstruction(I))
2070     return true;
2071 
2072   // SROA can't look through these, but they may be free.
2073   return Base::visitInsertValue(I);
2074 }
2075 
2076 /// Try to simplify a call site.
2077 ///
2078 /// Takes a concrete function and callsite and tries to actually simplify it by
2079 /// analyzing the arguments and call itself with instsimplify. Returns true if
2080 /// it has simplified the callsite to some other entity (a constant), making it
2081 /// free.
2082 bool CallAnalyzer::simplifyCallSite(Function *F, CallBase &Call) {
2083   // FIXME: Using the instsimplify logic directly for this is inefficient
2084   // because we have to continually rebuild the argument list even when no
2085   // simplifications can be performed. Until that is fixed with remapping
2086   // inside of instsimplify, directly constant fold calls here.
2087   if (!canConstantFoldCallTo(&Call, F))
2088     return false;
2089 
2090   // Try to re-map the arguments to constants.
2091   SmallVector<Constant *, 4> ConstantArgs;
2092   ConstantArgs.reserve(Call.arg_size());
2093   for (Value *I : Call.args()) {
2094     Constant *C = dyn_cast<Constant>(I);
2095     if (!C)
2096       C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(I));
2097     if (!C)
2098       return false; // This argument doesn't map to a constant.
2099 
2100     ConstantArgs.push_back(C);
2101   }
2102   if (Constant *C = ConstantFoldCall(&Call, F, ConstantArgs)) {
2103     SimplifiedValues[&Call] = C;
2104     return true;
2105   }
2106 
2107   return false;
2108 }
2109 
2110 bool CallAnalyzer::visitCallBase(CallBase &Call) {
2111   if (!onCallBaseVisitStart(Call))
2112     return true;
2113 
2114   if (Call.hasFnAttr(Attribute::ReturnsTwice) &&
2115       !F.hasFnAttribute(Attribute::ReturnsTwice)) {
2116     // This aborts the entire analysis.
2117     ExposesReturnsTwice = true;
2118     return false;
2119   }
2120   if (isa<CallInst>(Call) && cast<CallInst>(Call).cannotDuplicate())
2121     ContainsNoDuplicateCall = true;
2122 
2123   Function *F = Call.getCalledFunction();
2124   bool IsIndirectCall = !F;
2125   if (IsIndirectCall) {
2126     // Check if this happens to be an indirect function call to a known function
2127     // in this inline context. If not, we've done all we can.
2128     Value *Callee = Call.getCalledOperand();
2129     F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
2130     if (!F || F->getFunctionType() != Call.getFunctionType()) {
2131       onCallArgumentSetup(Call);
2132 
2133       if (!Call.onlyReadsMemory())
2134         disableLoadElimination();
2135       return Base::visitCallBase(Call);
2136     }
2137   }
2138 
2139   assert(F && "Expected a call to a known function");
2140 
2141   // When we have a concrete function, first try to simplify it directly.
2142   if (simplifyCallSite(F, Call))
2143     return true;
2144 
2145   // Next check if it is an intrinsic we know about.
2146   // FIXME: Lift this into part of the InstVisitor.
2147   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&Call)) {
2148     switch (II->getIntrinsicID()) {
2149     default:
2150       if (!Call.onlyReadsMemory() && !isAssumeLikeIntrinsic(II))
2151         disableLoadElimination();
2152       return Base::visitCallBase(Call);
2153 
2154     case Intrinsic::load_relative:
2155       onLoadRelativeIntrinsic();
2156       return false;
2157 
2158     case Intrinsic::memset:
2159     case Intrinsic::memcpy:
2160     case Intrinsic::memmove:
2161       disableLoadElimination();
2162       // SROA can usually chew through these intrinsics, but they aren't free.
2163       return false;
2164     case Intrinsic::icall_branch_funnel:
2165     case Intrinsic::localescape:
2166       HasUninlineableIntrinsic = true;
2167       return false;
2168     case Intrinsic::vastart:
2169       InitsVargArgs = true;
2170       return false;
2171     case Intrinsic::launder_invariant_group:
2172     case Intrinsic::strip_invariant_group:
2173       if (auto *SROAArg = getSROAArgForValueOrNull(II->getOperand(0)))
2174         SROAArgValues[II] = SROAArg;
2175       return true;
2176     case Intrinsic::is_constant:
2177       return simplifyIntrinsicCallIsConstant(Call);
2178     }
2179   }
2180 
2181   if (F == Call.getFunction()) {
2182     // This flag will fully abort the analysis, so don't bother with anything
2183     // else.
2184     IsRecursiveCall = true;
2185     if (!AllowRecursiveCall)
2186       return false;
2187   }
2188 
2189   if (TTI.isLoweredToCall(F)) {
2190     onLoweredCall(F, Call, IsIndirectCall);
2191   }
2192 
2193   if (!(Call.onlyReadsMemory() || (IsIndirectCall && F->onlyReadsMemory())))
2194     disableLoadElimination();
2195   return Base::visitCallBase(Call);
2196 }
2197 
2198 bool CallAnalyzer::visitReturnInst(ReturnInst &RI) {
2199   // At least one return instruction will be free after inlining.
2200   bool Free = !HasReturn;
2201   HasReturn = true;
2202   return Free;
2203 }
2204 
2205 bool CallAnalyzer::visitBranchInst(BranchInst &BI) {
2206   // We model unconditional branches as essentially free -- they really
2207   // shouldn't exist at all, but handling them makes the behavior of the
2208   // inliner more regular and predictable. Interestingly, conditional branches
2209   // which will fold away are also free.
2210   return BI.isUnconditional() || isa<ConstantInt>(BI.getCondition()) ||
2211          isa_and_nonnull<ConstantInt>(
2212              SimplifiedValues.lookup(BI.getCondition()));
2213 }
2214 
2215 bool CallAnalyzer::visitSelectInst(SelectInst &SI) {
2216   bool CheckSROA = SI.getType()->isPointerTy();
2217   Value *TrueVal = SI.getTrueValue();
2218   Value *FalseVal = SI.getFalseValue();
2219 
2220   Constant *TrueC = dyn_cast<Constant>(TrueVal);
2221   if (!TrueC)
2222     TrueC = SimplifiedValues.lookup(TrueVal);
2223   Constant *FalseC = dyn_cast<Constant>(FalseVal);
2224   if (!FalseC)
2225     FalseC = SimplifiedValues.lookup(FalseVal);
2226   Constant *CondC =
2227       dyn_cast_or_null<Constant>(SimplifiedValues.lookup(SI.getCondition()));
2228 
2229   if (!CondC) {
2230     // Select C, X, X => X
2231     if (TrueC == FalseC && TrueC) {
2232       SimplifiedValues[&SI] = TrueC;
2233       return true;
2234     }
2235 
2236     if (!CheckSROA)
2237       return Base::visitSelectInst(SI);
2238 
2239     std::pair<Value *, APInt> TrueBaseAndOffset =
2240         ConstantOffsetPtrs.lookup(TrueVal);
2241     std::pair<Value *, APInt> FalseBaseAndOffset =
2242         ConstantOffsetPtrs.lookup(FalseVal);
2243     if (TrueBaseAndOffset == FalseBaseAndOffset && TrueBaseAndOffset.first) {
2244       ConstantOffsetPtrs[&SI] = TrueBaseAndOffset;
2245 
2246       if (auto *SROAArg = getSROAArgForValueOrNull(TrueVal))
2247         SROAArgValues[&SI] = SROAArg;
2248       return true;
2249     }
2250 
2251     return Base::visitSelectInst(SI);
2252   }
2253 
2254   // Select condition is a constant.
2255   Value *SelectedV = CondC->isAllOnesValue()  ? TrueVal
2256                      : (CondC->isNullValue()) ? FalseVal
2257                                               : nullptr;
2258   if (!SelectedV) {
2259     // Condition is a vector constant that is not all 1s or all 0s.  If all
2260     // operands are constants, ConstantExpr::getSelect() can handle the cases
2261     // such as select vectors.
2262     if (TrueC && FalseC) {
2263       if (auto *C = ConstantExpr::getSelect(CondC, TrueC, FalseC)) {
2264         SimplifiedValues[&SI] = C;
2265         return true;
2266       }
2267     }
2268     return Base::visitSelectInst(SI);
2269   }
2270 
2271   // Condition is either all 1s or all 0s. SI can be simplified.
2272   if (Constant *SelectedC = dyn_cast<Constant>(SelectedV)) {
2273     SimplifiedValues[&SI] = SelectedC;
2274     return true;
2275   }
2276 
2277   if (!CheckSROA)
2278     return true;
2279 
2280   std::pair<Value *, APInt> BaseAndOffset =
2281       ConstantOffsetPtrs.lookup(SelectedV);
2282   if (BaseAndOffset.first) {
2283     ConstantOffsetPtrs[&SI] = BaseAndOffset;
2284 
2285     if (auto *SROAArg = getSROAArgForValueOrNull(SelectedV))
2286       SROAArgValues[&SI] = SROAArg;
2287   }
2288 
2289   return true;
2290 }
2291 
2292 bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) {
2293   // We model unconditional switches as free, see the comments on handling
2294   // branches.
2295   if (isa<ConstantInt>(SI.getCondition()))
2296     return true;
2297   if (Value *V = SimplifiedValues.lookup(SI.getCondition()))
2298     if (isa<ConstantInt>(V))
2299       return true;
2300 
2301   // Assume the most general case where the switch is lowered into
2302   // either a jump table, bit test, or a balanced binary tree consisting of
2303   // case clusters without merging adjacent clusters with the same
2304   // destination. We do not consider the switches that are lowered with a mix
2305   // of jump table/bit test/binary search tree. The cost of the switch is
2306   // proportional to the size of the tree or the size of jump table range.
2307   //
2308   // NB: We convert large switches which are just used to initialize large phi
2309   // nodes to lookup tables instead in simplifycfg, so this shouldn't prevent
2310   // inlining those. It will prevent inlining in cases where the optimization
2311   // does not (yet) fire.
2312 
2313   unsigned JumpTableSize = 0;
2314   BlockFrequencyInfo *BFI = GetBFI ? &(GetBFI(F)) : nullptr;
2315   unsigned NumCaseCluster =
2316       TTI.getEstimatedNumberOfCaseClusters(SI, JumpTableSize, PSI, BFI);
2317 
2318   onFinalizeSwitch(JumpTableSize, NumCaseCluster);
2319   return false;
2320 }
2321 
2322 bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) {
2323   // We never want to inline functions that contain an indirectbr.  This is
2324   // incorrect because all the blockaddress's (in static global initializers
2325   // for example) would be referring to the original function, and this
2326   // indirect jump would jump from the inlined copy of the function into the
2327   // original function which is extremely undefined behavior.
2328   // FIXME: This logic isn't really right; we can safely inline functions with
2329   // indirectbr's as long as no other function or global references the
2330   // blockaddress of a block within the current function.
2331   HasIndirectBr = true;
2332   return false;
2333 }
2334 
2335 bool CallAnalyzer::visitResumeInst(ResumeInst &RI) {
2336   // FIXME: It's not clear that a single instruction is an accurate model for
2337   // the inline cost of a resume instruction.
2338   return false;
2339 }
2340 
2341 bool CallAnalyzer::visitCleanupReturnInst(CleanupReturnInst &CRI) {
2342   // FIXME: It's not clear that a single instruction is an accurate model for
2343   // the inline cost of a cleanupret instruction.
2344   return false;
2345 }
2346 
2347 bool CallAnalyzer::visitCatchReturnInst(CatchReturnInst &CRI) {
2348   // FIXME: It's not clear that a single instruction is an accurate model for
2349   // the inline cost of a catchret instruction.
2350   return false;
2351 }
2352 
2353 bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) {
2354   // FIXME: It might be reasonably to discount the cost of instructions leading
2355   // to unreachable as they have the lowest possible impact on both runtime and
2356   // code size.
2357   return true; // No actual code is needed for unreachable.
2358 }
2359 
2360 bool CallAnalyzer::visitInstruction(Instruction &I) {
2361   // Some instructions are free. All of the free intrinsics can also be
2362   // handled by SROA, etc.
2363   if (TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency) ==
2364       TargetTransformInfo::TCC_Free)
2365     return true;
2366 
2367   // We found something we don't understand or can't handle. Mark any SROA-able
2368   // values in the operand list as no longer viable.
2369   for (const Use &Op : I.operands())
2370     disableSROA(Op);
2371 
2372   return false;
2373 }
2374 
2375 /// Analyze a basic block for its contribution to the inline cost.
2376 ///
2377 /// This method walks the analyzer over every instruction in the given basic
2378 /// block and accounts for their cost during inlining at this callsite. It
2379 /// aborts early if the threshold has been exceeded or an impossible to inline
2380 /// construct has been detected. It returns false if inlining is no longer
2381 /// viable, and true if inlining remains viable.
2382 InlineResult
2383 CallAnalyzer::analyzeBlock(BasicBlock *BB,
2384                            SmallPtrSetImpl<const Value *> &EphValues) {
2385   for (Instruction &I : *BB) {
2386     // FIXME: Currently, the number of instructions in a function regardless of
2387     // our ability to simplify them during inline to constants or dead code,
2388     // are actually used by the vector bonus heuristic. As long as that's true,
2389     // we have to special case debug intrinsics here to prevent differences in
2390     // inlining due to debug symbols. Eventually, the number of unsimplified
2391     // instructions shouldn't factor into the cost computation, but until then,
2392     // hack around it here.
2393     // Similarly, skip pseudo-probes.
2394     if (I.isDebugOrPseudoInst())
2395       continue;
2396 
2397     // Skip ephemeral values.
2398     if (EphValues.count(&I))
2399       continue;
2400 
2401     ++NumInstructions;
2402     if (isa<ExtractElementInst>(I) || I.getType()->isVectorTy())
2403       ++NumVectorInstructions;
2404 
2405     // If the instruction simplified to a constant, there is no cost to this
2406     // instruction. Visit the instructions using our InstVisitor to account for
2407     // all of the per-instruction logic. The visit tree returns true if we
2408     // consumed the instruction in any way, and false if the instruction's base
2409     // cost should count against inlining.
2410     onInstructionAnalysisStart(&I);
2411 
2412     if (Base::visit(&I))
2413       ++NumInstructionsSimplified;
2414     else
2415       onMissedSimplification();
2416 
2417     onInstructionAnalysisFinish(&I);
2418     using namespace ore;
2419     // If the visit this instruction detected an uninlinable pattern, abort.
2420     InlineResult IR = InlineResult::success();
2421     if (IsRecursiveCall && !AllowRecursiveCall)
2422       IR = InlineResult::failure("recursive");
2423     else if (ExposesReturnsTwice)
2424       IR = InlineResult::failure("exposes returns twice");
2425     else if (HasDynamicAlloca)
2426       IR = InlineResult::failure("dynamic alloca");
2427     else if (HasIndirectBr)
2428       IR = InlineResult::failure("indirect branch");
2429     else if (HasUninlineableIntrinsic)
2430       IR = InlineResult::failure("uninlinable intrinsic");
2431     else if (InitsVargArgs)
2432       IR = InlineResult::failure("varargs");
2433     if (!IR.isSuccess()) {
2434       if (ORE)
2435         ORE->emit([&]() {
2436           return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline",
2437                                           &CandidateCall)
2438                  << NV("Callee", &F) << " has uninlinable pattern ("
2439                  << NV("InlineResult", IR.getFailureReason())
2440                  << ") and cost is not fully computed";
2441         });
2442       return IR;
2443     }
2444 
2445     // If the caller is a recursive function then we don't want to inline
2446     // functions which allocate a lot of stack space because it would increase
2447     // the caller stack usage dramatically.
2448     if (IsCallerRecursive &&
2449         AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller) {
2450       auto IR =
2451           InlineResult::failure("recursive and allocates too much stack space");
2452       if (ORE)
2453         ORE->emit([&]() {
2454           return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline",
2455                                           &CandidateCall)
2456                  << NV("Callee", &F) << " is "
2457                  << NV("InlineResult", IR.getFailureReason())
2458                  << ". Cost is not fully computed";
2459         });
2460       return IR;
2461     }
2462 
2463     if (shouldStop())
2464       return InlineResult::failure(
2465           "Call site analysis is not favorable to inlining.");
2466   }
2467 
2468   return InlineResult::success();
2469 }
2470 
2471 /// Compute the base pointer and cumulative constant offsets for V.
2472 ///
2473 /// This strips all constant offsets off of V, leaving it the base pointer, and
2474 /// accumulates the total constant offset applied in the returned constant. It
2475 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
2476 /// no constant offsets applied.
2477 ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
2478   if (!V->getType()->isPointerTy())
2479     return nullptr;
2480 
2481   unsigned AS = V->getType()->getPointerAddressSpace();
2482   unsigned IntPtrWidth = DL.getIndexSizeInBits(AS);
2483   APInt Offset = APInt::getZero(IntPtrWidth);
2484 
2485   // Even though we don't look through PHI nodes, we could be called on an
2486   // instruction in an unreachable block, which may be on a cycle.
2487   SmallPtrSet<Value *, 4> Visited;
2488   Visited.insert(V);
2489   do {
2490     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
2491       if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
2492         return nullptr;
2493       V = GEP->getPointerOperand();
2494     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
2495       V = cast<Operator>(V)->getOperand(0);
2496     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2497       if (GA->isInterposable())
2498         break;
2499       V = GA->getAliasee();
2500     } else {
2501       break;
2502     }
2503     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
2504   } while (Visited.insert(V).second);
2505 
2506   Type *IdxPtrTy = DL.getIndexType(V->getType());
2507   return cast<ConstantInt>(ConstantInt::get(IdxPtrTy, Offset));
2508 }
2509 
2510 /// Find dead blocks due to deleted CFG edges during inlining.
2511 ///
2512 /// If we know the successor of the current block, \p CurrBB, has to be \p
2513 /// NextBB, the other successors of \p CurrBB are dead if these successors have
2514 /// no live incoming CFG edges.  If one block is found to be dead, we can
2515 /// continue growing the dead block list by checking the successors of the dead
2516 /// blocks to see if all their incoming edges are dead or not.
2517 void CallAnalyzer::findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB) {
2518   auto IsEdgeDead = [&](BasicBlock *Pred, BasicBlock *Succ) {
2519     // A CFG edge is dead if the predecessor is dead or the predecessor has a
2520     // known successor which is not the one under exam.
2521     return (DeadBlocks.count(Pred) ||
2522             (KnownSuccessors[Pred] && KnownSuccessors[Pred] != Succ));
2523   };
2524 
2525   auto IsNewlyDead = [&](BasicBlock *BB) {
2526     // If all the edges to a block are dead, the block is also dead.
2527     return (!DeadBlocks.count(BB) &&
2528             llvm::all_of(predecessors(BB),
2529                          [&](BasicBlock *P) { return IsEdgeDead(P, BB); }));
2530   };
2531 
2532   for (BasicBlock *Succ : successors(CurrBB)) {
2533     if (Succ == NextBB || !IsNewlyDead(Succ))
2534       continue;
2535     SmallVector<BasicBlock *, 4> NewDead;
2536     NewDead.push_back(Succ);
2537     while (!NewDead.empty()) {
2538       BasicBlock *Dead = NewDead.pop_back_val();
2539       if (DeadBlocks.insert(Dead).second)
2540         // Continue growing the dead block lists.
2541         for (BasicBlock *S : successors(Dead))
2542           if (IsNewlyDead(S))
2543             NewDead.push_back(S);
2544     }
2545   }
2546 }
2547 
2548 /// Analyze a call site for potential inlining.
2549 ///
2550 /// Returns true if inlining this call is viable, and false if it is not
2551 /// viable. It computes the cost and adjusts the threshold based on numerous
2552 /// factors and heuristics. If this method returns false but the computed cost
2553 /// is below the computed threshold, then inlining was forcibly disabled by
2554 /// some artifact of the routine.
2555 InlineResult CallAnalyzer::analyze() {
2556   ++NumCallsAnalyzed;
2557 
2558   auto Result = onAnalysisStart();
2559   if (!Result.isSuccess())
2560     return Result;
2561 
2562   if (F.empty())
2563     return InlineResult::success();
2564 
2565   Function *Caller = CandidateCall.getFunction();
2566   // Check if the caller function is recursive itself.
2567   for (User *U : Caller->users()) {
2568     CallBase *Call = dyn_cast<CallBase>(U);
2569     if (Call && Call->getFunction() == Caller) {
2570       IsCallerRecursive = true;
2571       break;
2572     }
2573   }
2574 
2575   // Populate our simplified values by mapping from function arguments to call
2576   // arguments with known important simplifications.
2577   auto CAI = CandidateCall.arg_begin();
2578   for (Argument &FAI : F.args()) {
2579     assert(CAI != CandidateCall.arg_end());
2580     if (Constant *C = dyn_cast<Constant>(CAI))
2581       SimplifiedValues[&FAI] = C;
2582 
2583     Value *PtrArg = *CAI;
2584     if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
2585       ConstantOffsetPtrs[&FAI] = std::make_pair(PtrArg, C->getValue());
2586 
2587       // We can SROA any pointer arguments derived from alloca instructions.
2588       if (auto *SROAArg = dyn_cast<AllocaInst>(PtrArg)) {
2589         SROAArgValues[&FAI] = SROAArg;
2590         onInitializeSROAArg(SROAArg);
2591         EnabledSROAAllocas.insert(SROAArg);
2592       }
2593     }
2594     ++CAI;
2595   }
2596   NumConstantArgs = SimplifiedValues.size();
2597   NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
2598   NumAllocaArgs = SROAArgValues.size();
2599 
2600   // FIXME: If a caller has multiple calls to a callee, we end up recomputing
2601   // the ephemeral values multiple times (and they're completely determined by
2602   // the callee, so this is purely duplicate work).
2603   SmallPtrSet<const Value *, 32> EphValues;
2604   CodeMetrics::collectEphemeralValues(&F, &GetAssumptionCache(F), EphValues);
2605 
2606   // The worklist of live basic blocks in the callee *after* inlining. We avoid
2607   // adding basic blocks of the callee which can be proven to be dead for this
2608   // particular call site in order to get more accurate cost estimates. This
2609   // requires a somewhat heavyweight iteration pattern: we need to walk the
2610   // basic blocks in a breadth-first order as we insert live successors. To
2611   // accomplish this, prioritizing for small iterations because we exit after
2612   // crossing our threshold, we use a small-size optimized SetVector.
2613   typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
2614                     SmallPtrSet<BasicBlock *, 16>>
2615       BBSetVector;
2616   BBSetVector BBWorklist;
2617   BBWorklist.insert(&F.getEntryBlock());
2618 
2619   // Note that we *must not* cache the size, this loop grows the worklist.
2620   for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
2621     if (shouldStop())
2622       break;
2623 
2624     BasicBlock *BB = BBWorklist[Idx];
2625     if (BB->empty())
2626       continue;
2627 
2628     onBlockStart(BB);
2629 
2630     // Disallow inlining a blockaddress with uses other than strictly callbr.
2631     // A blockaddress only has defined behavior for an indirect branch in the
2632     // same function, and we do not currently support inlining indirect
2633     // branches.  But, the inliner may not see an indirect branch that ends up
2634     // being dead code at a particular call site. If the blockaddress escapes
2635     // the function, e.g., via a global variable, inlining may lead to an
2636     // invalid cross-function reference.
2637     // FIXME: pr/39560: continue relaxing this overt restriction.
2638     if (BB->hasAddressTaken())
2639       for (User *U : BlockAddress::get(&*BB)->users())
2640         if (!isa<CallBrInst>(*U))
2641           return InlineResult::failure("blockaddress used outside of callbr");
2642 
2643     // Analyze the cost of this block. If we blow through the threshold, this
2644     // returns false, and we can bail on out.
2645     InlineResult IR = analyzeBlock(BB, EphValues);
2646     if (!IR.isSuccess())
2647       return IR;
2648 
2649     Instruction *TI = BB->getTerminator();
2650 
2651     // Add in the live successors by first checking whether we have terminator
2652     // that may be simplified based on the values simplified by this call.
2653     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2654       if (BI->isConditional()) {
2655         Value *Cond = BI->getCondition();
2656         if (ConstantInt *SimpleCond =
2657                 dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
2658           BasicBlock *NextBB = BI->getSuccessor(SimpleCond->isZero() ? 1 : 0);
2659           BBWorklist.insert(NextBB);
2660           KnownSuccessors[BB] = NextBB;
2661           findDeadBlocks(BB, NextBB);
2662           continue;
2663         }
2664       }
2665     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2666       Value *Cond = SI->getCondition();
2667       if (ConstantInt *SimpleCond =
2668               dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
2669         BasicBlock *NextBB = SI->findCaseValue(SimpleCond)->getCaseSuccessor();
2670         BBWorklist.insert(NextBB);
2671         KnownSuccessors[BB] = NextBB;
2672         findDeadBlocks(BB, NextBB);
2673         continue;
2674       }
2675     }
2676 
2677     // If we're unable to select a particular successor, just count all of
2678     // them.
2679     for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
2680          ++TIdx)
2681       BBWorklist.insert(TI->getSuccessor(TIdx));
2682 
2683     onBlockAnalyzed(BB);
2684   }
2685 
2686   bool OnlyOneCallAndLocalLinkage = F.hasLocalLinkage() && F.hasOneLiveUse() &&
2687                                     &F == CandidateCall.getCalledFunction();
2688   // If this is a noduplicate call, we can still inline as long as
2689   // inlining this would cause the removal of the caller (so the instruction
2690   // is not actually duplicated, just moved).
2691   if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall)
2692     return InlineResult::failure("noduplicate");
2693 
2694   // If the callee's stack size exceeds the user-specified threshold,
2695   // do not let it be inlined.
2696   if (AllocatedSize > StackSizeThreshold)
2697     return InlineResult::failure("stacksize");
2698 
2699   return finalizeAnalysis();
2700 }
2701 
2702 void InlineCostCallAnalyzer::print(raw_ostream &OS) {
2703 #define DEBUG_PRINT_STAT(x) OS << "      " #x ": " << x << "\n"
2704   if (PrintInstructionComments)
2705     F.print(OS, &Writer);
2706   DEBUG_PRINT_STAT(NumConstantArgs);
2707   DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
2708   DEBUG_PRINT_STAT(NumAllocaArgs);
2709   DEBUG_PRINT_STAT(NumConstantPtrCmps);
2710   DEBUG_PRINT_STAT(NumConstantPtrDiffs);
2711   DEBUG_PRINT_STAT(NumInstructionsSimplified);
2712   DEBUG_PRINT_STAT(NumInstructions);
2713   DEBUG_PRINT_STAT(SROACostSavings);
2714   DEBUG_PRINT_STAT(SROACostSavingsLost);
2715   DEBUG_PRINT_STAT(LoadEliminationCost);
2716   DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
2717   DEBUG_PRINT_STAT(Cost);
2718   DEBUG_PRINT_STAT(Threshold);
2719 #undef DEBUG_PRINT_STAT
2720 }
2721 
2722 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2723 /// Dump stats about this call's analysis.
2724 LLVM_DUMP_METHOD void InlineCostCallAnalyzer::dump() { print(dbgs()); }
2725 #endif
2726 
2727 /// Test that there are no attribute conflicts between Caller and Callee
2728 ///        that prevent inlining.
2729 static bool functionsHaveCompatibleAttributes(
2730     Function *Caller, Function *Callee, TargetTransformInfo &TTI,
2731     function_ref<const TargetLibraryInfo &(Function &)> &GetTLI) {
2732   // Note that CalleeTLI must be a copy not a reference. The legacy pass manager
2733   // caches the most recently created TLI in the TargetLibraryInfoWrapperPass
2734   // object, and always returns the same object (which is overwritten on each
2735   // GetTLI call). Therefore we copy the first result.
2736   auto CalleeTLI = GetTLI(*Callee);
2737   return (IgnoreTTIInlineCompatible ||
2738           TTI.areInlineCompatible(Caller, Callee)) &&
2739          GetTLI(*Caller).areInlineCompatible(CalleeTLI,
2740                                              InlineCallerSupersetNoBuiltin) &&
2741          AttributeFuncs::areInlineCompatible(*Caller, *Callee);
2742 }
2743 
2744 int llvm::getCallsiteCost(CallBase &Call, const DataLayout &DL) {
2745   int Cost = 0;
2746   for (unsigned I = 0, E = Call.arg_size(); I != E; ++I) {
2747     if (Call.isByValArgument(I)) {
2748       // We approximate the number of loads and stores needed by dividing the
2749       // size of the byval type by the target's pointer size.
2750       PointerType *PTy = cast<PointerType>(Call.getArgOperand(I)->getType());
2751       unsigned TypeSize = DL.getTypeSizeInBits(Call.getParamByValType(I));
2752       unsigned AS = PTy->getAddressSpace();
2753       unsigned PointerSize = DL.getPointerSizeInBits(AS);
2754       // Ceiling division.
2755       unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
2756 
2757       // If it generates more than 8 stores it is likely to be expanded as an
2758       // inline memcpy so we take that as an upper bound. Otherwise we assume
2759       // one load and one store per word copied.
2760       // FIXME: The maxStoresPerMemcpy setting from the target should be used
2761       // here instead of a magic number of 8, but it's not available via
2762       // DataLayout.
2763       NumStores = std::min(NumStores, 8U);
2764 
2765       Cost += 2 * NumStores * InlineConstants::InstrCost;
2766     } else {
2767       // For non-byval arguments subtract off one instruction per call
2768       // argument.
2769       Cost += InlineConstants::InstrCost;
2770     }
2771   }
2772   // The call instruction also disappears after inlining.
2773   Cost += InlineConstants::InstrCost + CallPenalty;
2774   return Cost;
2775 }
2776 
2777 InlineCost llvm::getInlineCost(
2778     CallBase &Call, const InlineParams &Params, TargetTransformInfo &CalleeTTI,
2779     function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
2780     function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
2781     function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
2782     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
2783   return getInlineCost(Call, Call.getCalledFunction(), Params, CalleeTTI,
2784                        GetAssumptionCache, GetTLI, GetBFI, PSI, ORE);
2785 }
2786 
2787 Optional<int> llvm::getInliningCostEstimate(
2788     CallBase &Call, TargetTransformInfo &CalleeTTI,
2789     function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
2790     function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
2791     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
2792   const InlineParams Params = {/* DefaultThreshold*/ 0,
2793                                /*HintThreshold*/ {},
2794                                /*ColdThreshold*/ {},
2795                                /*OptSizeThreshold*/ {},
2796                                /*OptMinSizeThreshold*/ {},
2797                                /*HotCallSiteThreshold*/ {},
2798                                /*LocallyHotCallSiteThreshold*/ {},
2799                                /*ColdCallSiteThreshold*/ {},
2800                                /*ComputeFullInlineCost*/ true,
2801                                /*EnableDeferral*/ true};
2802 
2803   InlineCostCallAnalyzer CA(*Call.getCalledFunction(), Call, Params, CalleeTTI,
2804                             GetAssumptionCache, GetBFI, PSI, ORE, true,
2805                             /*IgnoreThreshold*/ true);
2806   auto R = CA.analyze();
2807   if (!R.isSuccess())
2808     return None;
2809   return CA.getCost();
2810 }
2811 
2812 Optional<InlineCostFeatures> llvm::getInliningCostFeatures(
2813     CallBase &Call, TargetTransformInfo &CalleeTTI,
2814     function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
2815     function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
2816     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
2817   InlineCostFeaturesAnalyzer CFA(CalleeTTI, GetAssumptionCache, GetBFI, PSI,
2818                                  ORE, *Call.getCalledFunction(), Call);
2819   auto R = CFA.analyze();
2820   if (!R.isSuccess())
2821     return None;
2822   return CFA.features();
2823 }
2824 
2825 Optional<InlineResult> llvm::getAttributeBasedInliningDecision(
2826     CallBase &Call, Function *Callee, TargetTransformInfo &CalleeTTI,
2827     function_ref<const TargetLibraryInfo &(Function &)> GetTLI) {
2828 
2829   // Cannot inline indirect calls.
2830   if (!Callee)
2831     return InlineResult::failure("indirect call");
2832 
2833   // When callee coroutine function is inlined into caller coroutine function
2834   // before coro-split pass,
2835   // coro-early pass can not handle this quiet well.
2836   // So we won't inline the coroutine function if it have not been unsplited
2837   if (Callee->isPresplitCoroutine())
2838     return InlineResult::failure("unsplited coroutine call");
2839 
2840   // Never inline calls with byval arguments that does not have the alloca
2841   // address space. Since byval arguments can be replaced with a copy to an
2842   // alloca, the inlined code would need to be adjusted to handle that the
2843   // argument is in the alloca address space (so it is a little bit complicated
2844   // to solve).
2845   unsigned AllocaAS = Callee->getParent()->getDataLayout().getAllocaAddrSpace();
2846   for (unsigned I = 0, E = Call.arg_size(); I != E; ++I)
2847     if (Call.isByValArgument(I)) {
2848       PointerType *PTy = cast<PointerType>(Call.getArgOperand(I)->getType());
2849       if (PTy->getAddressSpace() != AllocaAS)
2850         return InlineResult::failure("byval arguments without alloca"
2851                                      " address space");
2852     }
2853 
2854   // Calls to functions with always-inline attributes should be inlined
2855   // whenever possible.
2856   if (Call.hasFnAttr(Attribute::AlwaysInline)) {
2857     if (Call.getAttributes().hasFnAttr(Attribute::NoInline))
2858       return InlineResult::failure("noinline call site attribute");
2859 
2860     auto IsViable = isInlineViable(*Callee);
2861     if (IsViable.isSuccess())
2862       return InlineResult::success();
2863     return InlineResult::failure(IsViable.getFailureReason());
2864   }
2865 
2866   // Never inline functions with conflicting attributes (unless callee has
2867   // always-inline attribute).
2868   Function *Caller = Call.getCaller();
2869   if (!functionsHaveCompatibleAttributes(Caller, Callee, CalleeTTI, GetTLI))
2870     return InlineResult::failure("conflicting attributes");
2871 
2872   // Don't inline this call if the caller has the optnone attribute.
2873   if (Caller->hasOptNone())
2874     return InlineResult::failure("optnone attribute");
2875 
2876   // Don't inline a function that treats null pointer as valid into a caller
2877   // that does not have this attribute.
2878   if (!Caller->nullPointerIsDefined() && Callee->nullPointerIsDefined())
2879     return InlineResult::failure("nullptr definitions incompatible");
2880 
2881   // Don't inline functions which can be interposed at link-time.
2882   if (Callee->isInterposable())
2883     return InlineResult::failure("interposable");
2884 
2885   // Don't inline functions marked noinline.
2886   if (Callee->hasFnAttribute(Attribute::NoInline))
2887     return InlineResult::failure("noinline function attribute");
2888 
2889   // Don't inline call sites marked noinline.
2890   if (Call.isNoInline())
2891     return InlineResult::failure("noinline call site attribute");
2892 
2893   return None;
2894 }
2895 
2896 InlineCost llvm::getInlineCost(
2897     CallBase &Call, Function *Callee, const InlineParams &Params,
2898     TargetTransformInfo &CalleeTTI,
2899     function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
2900     function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
2901     function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
2902     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
2903 
2904   auto UserDecision =
2905       llvm::getAttributeBasedInliningDecision(Call, Callee, CalleeTTI, GetTLI);
2906 
2907   if (UserDecision) {
2908     if (UserDecision->isSuccess())
2909       return llvm::InlineCost::getAlways("always inline attribute");
2910     return llvm::InlineCost::getNever(UserDecision->getFailureReason());
2911   }
2912 
2913   LLVM_DEBUG(llvm::dbgs() << "      Analyzing call of " << Callee->getName()
2914                           << "... (caller:" << Call.getCaller()->getName()
2915                           << ")\n");
2916 
2917   InlineCostCallAnalyzer CA(*Callee, Call, Params, CalleeTTI,
2918                             GetAssumptionCache, GetBFI, PSI, ORE);
2919   InlineResult ShouldInline = CA.analyze();
2920 
2921   LLVM_DEBUG(CA.dump());
2922 
2923   // Always make cost benefit based decision explicit.
2924   // We use always/never here since threshold is not meaningful,
2925   // as it's not what drives cost-benefit analysis.
2926   if (CA.wasDecidedByCostBenefit()) {
2927     if (ShouldInline.isSuccess())
2928       return InlineCost::getAlways("benefit over cost",
2929                                    CA.getCostBenefitPair());
2930     else
2931       return InlineCost::getNever("cost over benefit", CA.getCostBenefitPair());
2932   }
2933 
2934   if (CA.wasDecidedByCostThreshold())
2935     return InlineCost::get(CA.getCost(), CA.getThreshold());
2936 
2937   // No details on how the decision was made, simply return always or never.
2938   return ShouldInline.isSuccess()
2939              ? InlineCost::getAlways("empty function")
2940              : InlineCost::getNever(ShouldInline.getFailureReason());
2941 }
2942 
2943 InlineResult llvm::isInlineViable(Function &F) {
2944   bool ReturnsTwice = F.hasFnAttribute(Attribute::ReturnsTwice);
2945   for (BasicBlock &BB : F) {
2946     // Disallow inlining of functions which contain indirect branches.
2947     if (isa<IndirectBrInst>(BB.getTerminator()))
2948       return InlineResult::failure("contains indirect branches");
2949 
2950     // Disallow inlining of blockaddresses which are used by non-callbr
2951     // instructions.
2952     if (BB.hasAddressTaken())
2953       for (User *U : BlockAddress::get(&BB)->users())
2954         if (!isa<CallBrInst>(*U))
2955           return InlineResult::failure("blockaddress used outside of callbr");
2956 
2957     for (auto &II : BB) {
2958       CallBase *Call = dyn_cast<CallBase>(&II);
2959       if (!Call)
2960         continue;
2961 
2962       // Disallow recursive calls.
2963       Function *Callee = Call->getCalledFunction();
2964       if (&F == Callee)
2965         return InlineResult::failure("recursive call");
2966 
2967       // Disallow calls which expose returns-twice to a function not previously
2968       // attributed as such.
2969       if (!ReturnsTwice && isa<CallInst>(Call) &&
2970           cast<CallInst>(Call)->canReturnTwice())
2971         return InlineResult::failure("exposes returns-twice attribute");
2972 
2973       if (Callee)
2974         switch (Callee->getIntrinsicID()) {
2975         default:
2976           break;
2977         case llvm::Intrinsic::icall_branch_funnel:
2978           // Disallow inlining of @llvm.icall.branch.funnel because current
2979           // backend can't separate call targets from call arguments.
2980           return InlineResult::failure(
2981               "disallowed inlining of @llvm.icall.branch.funnel");
2982         case llvm::Intrinsic::localescape:
2983           // Disallow inlining functions that call @llvm.localescape. Doing this
2984           // correctly would require major changes to the inliner.
2985           return InlineResult::failure(
2986               "disallowed inlining of @llvm.localescape");
2987         case llvm::Intrinsic::vastart:
2988           // Disallow inlining of functions that initialize VarArgs with
2989           // va_start.
2990           return InlineResult::failure(
2991               "contains VarArgs initialized with va_start");
2992         }
2993     }
2994   }
2995 
2996   return InlineResult::success();
2997 }
2998 
2999 // APIs to create InlineParams based on command line flags and/or other
3000 // parameters.
3001 
3002 InlineParams llvm::getInlineParams(int Threshold) {
3003   InlineParams Params;
3004 
3005   // This field is the threshold to use for a callee by default. This is
3006   // derived from one or more of:
3007   //  * optimization or size-optimization levels,
3008   //  * a value passed to createFunctionInliningPass function, or
3009   //  * the -inline-threshold flag.
3010   //  If the -inline-threshold flag is explicitly specified, that is used
3011   //  irrespective of anything else.
3012   if (InlineThreshold.getNumOccurrences() > 0)
3013     Params.DefaultThreshold = InlineThreshold;
3014   else
3015     Params.DefaultThreshold = Threshold;
3016 
3017   // Set the HintThreshold knob from the -inlinehint-threshold.
3018   Params.HintThreshold = HintThreshold;
3019 
3020   // Set the HotCallSiteThreshold knob from the -hot-callsite-threshold.
3021   Params.HotCallSiteThreshold = HotCallSiteThreshold;
3022 
3023   // If the -locally-hot-callsite-threshold is explicitly specified, use it to
3024   // populate LocallyHotCallSiteThreshold. Later, we populate
3025   // Params.LocallyHotCallSiteThreshold from -locally-hot-callsite-threshold if
3026   // we know that optimization level is O3 (in the getInlineParams variant that
3027   // takes the opt and size levels).
3028   // FIXME: Remove this check (and make the assignment unconditional) after
3029   // addressing size regression issues at O2.
3030   if (LocallyHotCallSiteThreshold.getNumOccurrences() > 0)
3031     Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold;
3032 
3033   // Set the ColdCallSiteThreshold knob from the
3034   // -inline-cold-callsite-threshold.
3035   Params.ColdCallSiteThreshold = ColdCallSiteThreshold;
3036 
3037   // Set the OptMinSizeThreshold and OptSizeThreshold params only if the
3038   // -inlinehint-threshold commandline option is not explicitly given. If that
3039   // option is present, then its value applies even for callees with size and
3040   // minsize attributes.
3041   // If the -inline-threshold is not specified, set the ColdThreshold from the
3042   // -inlinecold-threshold even if it is not explicitly passed. If
3043   // -inline-threshold is specified, then -inlinecold-threshold needs to be
3044   // explicitly specified to set the ColdThreshold knob
3045   if (InlineThreshold.getNumOccurrences() == 0) {
3046     Params.OptMinSizeThreshold = InlineConstants::OptMinSizeThreshold;
3047     Params.OptSizeThreshold = InlineConstants::OptSizeThreshold;
3048     Params.ColdThreshold = ColdThreshold;
3049   } else if (ColdThreshold.getNumOccurrences() > 0) {
3050     Params.ColdThreshold = ColdThreshold;
3051   }
3052   return Params;
3053 }
3054 
3055 InlineParams llvm::getInlineParams() {
3056   return getInlineParams(DefaultThreshold);
3057 }
3058 
3059 // Compute the default threshold for inlining based on the opt level and the
3060 // size opt level.
3061 static int computeThresholdFromOptLevels(unsigned OptLevel,
3062                                          unsigned SizeOptLevel) {
3063   if (OptLevel > 2)
3064     return InlineConstants::OptAggressiveThreshold;
3065   if (SizeOptLevel == 1) // -Os
3066     return InlineConstants::OptSizeThreshold;
3067   if (SizeOptLevel == 2) // -Oz
3068     return InlineConstants::OptMinSizeThreshold;
3069   return DefaultThreshold;
3070 }
3071 
3072 InlineParams llvm::getInlineParams(unsigned OptLevel, unsigned SizeOptLevel) {
3073   auto Params =
3074       getInlineParams(computeThresholdFromOptLevels(OptLevel, SizeOptLevel));
3075   // At O3, use the value of -locally-hot-callsite-threshold option to populate
3076   // Params.LocallyHotCallSiteThreshold. Below O3, this flag has effect only
3077   // when it is specified explicitly.
3078   if (OptLevel > 2)
3079     Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold;
3080   return Params;
3081 }
3082 
3083 PreservedAnalyses
3084 InlineCostAnnotationPrinterPass::run(Function &F,
3085                                      FunctionAnalysisManager &FAM) {
3086   PrintInstructionComments = true;
3087   std::function<AssumptionCache &(Function &)> GetAssumptionCache =
3088       [&](Function &F) -> AssumptionCache & {
3089     return FAM.getResult<AssumptionAnalysis>(F);
3090   };
3091   Module *M = F.getParent();
3092   ProfileSummaryInfo PSI(*M);
3093   DataLayout DL(M);
3094   TargetTransformInfo TTI(DL);
3095   // FIXME: Redesign the usage of InlineParams to expand the scope of this pass.
3096   // In the current implementation, the type of InlineParams doesn't matter as
3097   // the pass serves only for verification of inliner's decisions.
3098   // We can add a flag which determines InlineParams for this run. Right now,
3099   // the default InlineParams are used.
3100   const InlineParams Params = llvm::getInlineParams();
3101   for (BasicBlock &BB : F) {
3102     for (Instruction &I : BB) {
3103       if (CallInst *CI = dyn_cast<CallInst>(&I)) {
3104         Function *CalledFunction = CI->getCalledFunction();
3105         if (!CalledFunction || CalledFunction->isDeclaration())
3106           continue;
3107         OptimizationRemarkEmitter ORE(CalledFunction);
3108         InlineCostCallAnalyzer ICCA(*CalledFunction, *CI, Params, TTI,
3109                                     GetAssumptionCache, nullptr, &PSI, &ORE);
3110         ICCA.analyze();
3111         OS << "      Analyzing call of " << CalledFunction->getName()
3112            << "... (caller:" << CI->getCaller()->getName() << ")\n";
3113         ICCA.print(OS);
3114         OS << "\n";
3115       }
3116     }
3117   }
3118   return PreservedAnalyses::all();
3119 }
3120