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