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