17adc3a2bSChandler Carruth //===- InlineCost.cpp - Cost analysis for inliner -------------------------===//
27adc3a2bSChandler Carruth //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67adc3a2bSChandler Carruth //
77adc3a2bSChandler Carruth //===----------------------------------------------------------------------===//
87adc3a2bSChandler Carruth //
97adc3a2bSChandler Carruth // This file implements inline cost analysis.
107adc3a2bSChandler Carruth //
117adc3a2bSChandler Carruth //===----------------------------------------------------------------------===//
127adc3a2bSChandler Carruth 
137adc3a2bSChandler Carruth #include "llvm/Analysis/InlineCost.h"
147adc3a2bSChandler Carruth #include "llvm/ADT/STLExtras.h"
157adc3a2bSChandler Carruth #include "llvm/ADT/SetVector.h"
167adc3a2bSChandler Carruth #include "llvm/ADT/SmallPtrSet.h"
177adc3a2bSChandler Carruth #include "llvm/ADT/SmallVector.h"
187adc3a2bSChandler Carruth #include "llvm/ADT/Statistic.h"
19aec2fa35SDaniel Jasper #include "llvm/Analysis/AssumptionCache.h"
2012585b01SEaswaran Raman #include "llvm/Analysis/BlockFrequencyInfo.h"
214c1a1d3cSReid Kleckner #include "llvm/Analysis/CFG.h"
227adc3a2bSChandler Carruth #include "llvm/Analysis/CodeMetrics.h"
237adc3a2bSChandler Carruth #include "llvm/Analysis/ConstantFolding.h"
247adc3a2bSChandler Carruth #include "llvm/Analysis/InstructionSimplify.h"
25ba9f245bSDavid Green #include "llvm/Analysis/LoopInfo.h"
2671069cf6SEaswaran Raman #include "llvm/Analysis/ProfileSummaryInfo.h"
27f9ca75f1STeresa Johnson #include "llvm/Analysis/TargetLibraryInfo.h"
287adc3a2bSChandler Carruth #include "llvm/Analysis/TargetTransformInfo.h"
29a4461515SHaicheng Wu #include "llvm/Analysis/ValueTracking.h"
30432a3883SNico Weber #include "llvm/Config/llvm-config.h"
31c965fd94SKirill Naumov #include "llvm/IR/AssemblyAnnotationWriter.h"
327adc3a2bSChandler Carruth #include "llvm/IR/CallingConv.h"
337adc3a2bSChandler Carruth #include "llvm/IR/DataLayout.h"
34ba9f245bSDavid Green #include "llvm/IR/Dominators.h"
357adc3a2bSChandler Carruth #include "llvm/IR/GetElementPtrTypeIterator.h"
367adc3a2bSChandler Carruth #include "llvm/IR/GlobalAlias.h"
377adc3a2bSChandler Carruth #include "llvm/IR/InstVisitor.h"
387adc3a2bSChandler Carruth #include "llvm/IR/IntrinsicInst.h"
397adc3a2bSChandler Carruth #include "llvm/IR/Operator.h"
407cebf0afSCraig Topper #include "llvm/IR/PatternMatch.h"
414c1a1d3cSReid Kleckner #include "llvm/Support/CommandLine.h"
427adc3a2bSChandler Carruth #include "llvm/Support/Debug.h"
43c965fd94SKirill Naumov #include "llvm/Support/FormattedStream.h"
447adc3a2bSChandler Carruth #include "llvm/Support/raw_ostream.h"
457adc3a2bSChandler Carruth 
467adc3a2bSChandler Carruth using namespace llvm;
477adc3a2bSChandler Carruth 
487adc3a2bSChandler Carruth #define DEBUG_TYPE "inline-cost"
497adc3a2bSChandler Carruth 
507adc3a2bSChandler Carruth STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed");
517adc3a2bSChandler Carruth 
527f37a802STeresa Johnson static cl::opt<int>
537f37a802STeresa Johnson     DefaultThreshold("inlinedefault-threshold", cl::Hidden, cl::init(225),
547f37a802STeresa Johnson                      cl::ZeroOrMore,
557f37a802STeresa Johnson                      cl::desc("Default amount of inlining to perform"));
567f37a802STeresa Johnson 
571022b5ebSKirill Naumov static cl::opt<bool> PrintInstructionComments(
581022b5ebSKirill Naumov     "print-instruction-comments", cl::Hidden, cl::init(false),
591022b5ebSKirill Naumov     cl::desc("Prints comments for instruction based on inline cost analysis"));
60c965fd94SKirill Naumov 
611c57cc2bSEaswaran Raman static cl::opt<int> InlineThreshold(
62f4bb2f0dSEaswaran Raman     "inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore,
63f4bb2f0dSEaswaran Raman     cl::desc("Control the amount of inlining to perform (default = 225)"));
64f4bb2f0dSEaswaran Raman 
65f4bb2f0dSEaswaran Raman static cl::opt<int> HintThreshold(
66fd3e7a93SDavid Callahan     "inlinehint-threshold", cl::Hidden, cl::init(325), cl::ZeroOrMore,
67f4bb2f0dSEaswaran Raman     cl::desc("Threshold for inlining functions with inline hint"));
68f4bb2f0dSEaswaran Raman 
6912585b01SEaswaran Raman static cl::opt<int>
7012585b01SEaswaran Raman     ColdCallSiteThreshold("inline-cold-callsite-threshold", cl::Hidden,
71fd3e7a93SDavid Callahan                           cl::init(45), cl::ZeroOrMore,
7212585b01SEaswaran Raman                           cl::desc("Threshold for inlining cold callsites"));
7312585b01SEaswaran Raman 
749895c701SKazu Hirata static cl::opt<bool> InlineEnableCostBenefitAnalysis(
759895c701SKazu Hirata     "inline-enable-cost-benefit-analysis", cl::Hidden, cl::init(false),
769895c701SKazu Hirata     cl::desc("Enable the cost-benefit analysis for the inliner"));
779895c701SKazu Hirata 
789895c701SKazu Hirata static cl::opt<int> InlineSavingsMultiplier(
799895c701SKazu Hirata     "inline-savings-multiplier", cl::Hidden, cl::init(8), cl::ZeroOrMore,
809895c701SKazu Hirata     cl::desc("Multiplier to multiply cycle savings by during inlining"));
819895c701SKazu Hirata 
829895c701SKazu Hirata static cl::opt<int>
839895c701SKazu Hirata     InlineSizeAllowance("inline-size-allowance", cl::Hidden, cl::init(100),
849895c701SKazu Hirata                         cl::ZeroOrMore,
859895c701SKazu Hirata                         cl::desc("The maximum size of a callee that get's "
869895c701SKazu Hirata                                  "inlined without sufficient cycle savings"));
879895c701SKazu Hirata 
88f4bb2f0dSEaswaran Raman // We introduce this threshold to help performance of instrumentation based
89f4bb2f0dSEaswaran Raman // PGO before we actually hook up inliner with analysis passes such as BPI and
90f4bb2f0dSEaswaran Raman // BFI.
91f4bb2f0dSEaswaran Raman static cl::opt<int> ColdThreshold(
92fd3e7a93SDavid Callahan     "inlinecold-threshold", cl::Hidden, cl::init(45), cl::ZeroOrMore,
93f4bb2f0dSEaswaran Raman     cl::desc("Threshold for inlining functions with cold attribute"));
94f4bb2f0dSEaswaran Raman 
95de39cb93SDehao Chen static cl::opt<int>
96de39cb93SDehao Chen     HotCallSiteThreshold("hot-callsite-threshold", cl::Hidden, cl::init(3000),
97de39cb93SDehao Chen                          cl::ZeroOrMore,
98de39cb93SDehao Chen                          cl::desc("Threshold for hot callsites "));
99de39cb93SDehao Chen 
100974d4eeaSEaswaran Raman static cl::opt<int> LocallyHotCallSiteThreshold(
101974d4eeaSEaswaran Raman     "locally-hot-callsite-threshold", cl::Hidden, cl::init(525), cl::ZeroOrMore,
102974d4eeaSEaswaran Raman     cl::desc("Threshold for locally hot callsites "));
103974d4eeaSEaswaran Raman 
104c5fa6358SEaswaran Raman static cl::opt<int> ColdCallSiteRelFreq(
105c5fa6358SEaswaran Raman     "cold-callsite-rel-freq", cl::Hidden, cl::init(2), cl::ZeroOrMore,
10602a2bb2fSHiroshi Inoue     cl::desc("Maximum block frequency, expressed as a percentage of caller's "
107c5fa6358SEaswaran Raman              "entry frequency, for a callsite to be cold in the absence of "
108c5fa6358SEaswaran Raman              "profile information."));
109c5fa6358SEaswaran Raman 
110974d4eeaSEaswaran Raman static cl::opt<int> HotCallSiteRelFreq(
111974d4eeaSEaswaran Raman     "hot-callsite-rel-freq", cl::Hidden, cl::init(60), cl::ZeroOrMore,
112ff77cc75SEaswaran Raman     cl::desc("Minimum block frequency, expressed as a multiple of caller's "
113974d4eeaSEaswaran Raman              "entry frequency, for a callsite to be hot in the absence of "
114974d4eeaSEaswaran Raman              "profile information."));
115974d4eeaSEaswaran Raman 
1164924bb00SEaswaran Raman static cl::opt<bool> OptComputeFullInlineCost(
117fd3e7a93SDavid Callahan     "inline-cost-full", cl::Hidden, cl::init(false), cl::ZeroOrMore,
1180812c5beSHaicheng Wu     cl::desc("Compute the full inline cost of a call site even when the cost "
1190812c5beSHaicheng Wu              "exceeds the threshold."));
1200812c5beSHaicheng Wu 
121ed03d948SMehdi Amini static cl::opt<bool> InlineCallerSupersetNoBuiltin(
122ed03d948SMehdi Amini     "inline-caller-superset-nobuiltin", cl::Hidden, cl::init(true),
123ed03d948SMehdi Amini     cl::ZeroOrMore,
124ed03d948SMehdi Amini     cl::desc("Allow inlining when caller has a superset of callee's nobuiltin "
125f9ca75f1STeresa Johnson              "attributes."));
126f9ca75f1STeresa Johnson 
127d48c7859SKirill Naumov static cl::opt<bool> DisableGEPConstOperand(
128d48c7859SKirill Naumov     "disable-gep-const-evaluation", cl::Hidden, cl::init(false),
129d48c7859SKirill Naumov     cl::desc("Disables evaluation of GetElementPtr with constant operands"));
130d48c7859SKirill Naumov 
1317adc3a2bSChandler Carruth namespace {
13206408758SMircea Trofin class InlineCostCallAnalyzer;
133c965fd94SKirill Naumov 
134c965fd94SKirill Naumov // This struct is used to store information about inline cost of a
135c965fd94SKirill Naumov // particular instruction
136c965fd94SKirill Naumov struct InstructionCostDetail {
137b4924f01SMircea Trofin   int CostBefore = 0;
138b4924f01SMircea Trofin   int CostAfter = 0;
139b4924f01SMircea Trofin   int ThresholdBefore = 0;
140b4924f01SMircea Trofin   int ThresholdAfter = 0;
141b4924f01SMircea Trofin 
142b4924f01SMircea Trofin   int getThresholdDelta() const { return ThresholdAfter - ThresholdBefore; }
143b4924f01SMircea Trofin 
144b4924f01SMircea Trofin   int getCostDelta() const { return CostAfter - CostBefore; }
145b4924f01SMircea Trofin 
146b4924f01SMircea Trofin   bool hasThresholdChanged() const { return ThresholdAfter != ThresholdBefore; }
147c965fd94SKirill Naumov };
148c965fd94SKirill Naumov 
1491022b5ebSKirill Naumov class InlineCostAnnotationWriter : public AssemblyAnnotationWriter {
1501022b5ebSKirill Naumov private:
1511022b5ebSKirill Naumov   InlineCostCallAnalyzer *const ICCA;
152c965fd94SKirill Naumov 
1531022b5ebSKirill Naumov public:
1541022b5ebSKirill Naumov   InlineCostAnnotationWriter(InlineCostCallAnalyzer *ICCA) : ICCA(ICCA) {}
155c965fd94SKirill Naumov   virtual void emitInstructionAnnot(const Instruction *I,
1561022b5ebSKirill Naumov                                     formatted_raw_ostream &OS) override;
157c965fd94SKirill Naumov };
158c965fd94SKirill Naumov 
15908e2386dSMircea Trofin /// Carry out call site analysis, in order to evaluate inlinability.
16008e2386dSMircea Trofin /// NOTE: the type is currently used as implementation detail of functions such
16108e2386dSMircea Trofin /// as llvm::getInlineCost. Note the function_ref constructor parameters - the
16208e2386dSMircea Trofin /// expectation is that they come from the outer scope, from the wrapper
16308e2386dSMircea Trofin /// functions. If we want to support constructing CallAnalyzer objects where
16408e2386dSMircea Trofin /// lambdas are provided inline at construction, or where the object needs to
16508e2386dSMircea Trofin /// otherwise survive past the scope of the provided functions, we need to
16608e2386dSMircea Trofin /// revisit the argument types.
1677adc3a2bSChandler Carruth class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> {
1687adc3a2bSChandler Carruth   typedef InstVisitor<CallAnalyzer, bool> Base;
1697adc3a2bSChandler Carruth   friend class InstVisitor<CallAnalyzer, bool>;
1707adc3a2bSChandler Carruth 
17106408758SMircea Trofin protected:
17206408758SMircea Trofin   virtual ~CallAnalyzer() {}
1737adc3a2bSChandler Carruth   /// The TargetTransformInfo available for this compilation.
1747adc3a2bSChandler Carruth   const TargetTransformInfo &TTI;
1757adc3a2bSChandler Carruth 
176aec2fa35SDaniel Jasper   /// Getter for the cache of @llvm.assume intrinsics.
17708e2386dSMircea Trofin   function_ref<AssumptionCache &(Function &)> GetAssumptionCache;
178aec2fa35SDaniel Jasper 
17912585b01SEaswaran Raman   /// Getter for BlockFrequencyInfo
18008e2386dSMircea Trofin   function_ref<BlockFrequencyInfo &(Function &)> GetBFI;
18112585b01SEaswaran Raman 
18271069cf6SEaswaran Raman   /// Profile summary information.
18371069cf6SEaswaran Raman   ProfileSummaryInfo *PSI;
18471069cf6SEaswaran Raman 
185f3d122cdSPiotr Padlewski   /// The called function.
1867adc3a2bSChandler Carruth   Function &F;
1877adc3a2bSChandler Carruth 
18885be8ca8SEric Christopher   // Cache the DataLayout since we use it a lot.
18985be8ca8SEric Christopher   const DataLayout &DL;
19085be8ca8SEric Christopher 
1910812c5beSHaicheng Wu   /// The OptimizationRemarkEmitter available for this compilation.
1920812c5beSHaicheng Wu   OptimizationRemarkEmitter *ORE;
1930812c5beSHaicheng Wu 
194f3d122cdSPiotr Padlewski   /// The candidate callsite being analyzed. Please do not use this to do
195f3d122cdSPiotr Padlewski   /// analysis in the caller function; we want the inline cost query to be
196f3d122cdSPiotr Padlewski   /// easily cacheable. Instead, use the cover function paramHasAttr.
197652168a9SFedor Sergeev   CallBase &CandidateCall;
1987adc3a2bSChandler Carruth 
19906408758SMircea Trofin   /// Extension points for handling callsite features.
2009895c701SKazu Hirata   // Called before a basic block was analyzed.
2019895c701SKazu Hirata   virtual void onBlockStart(const BasicBlock *BB) {}
2029895c701SKazu Hirata 
20306408758SMircea Trofin   /// Called after a basic block was analyzed.
20406408758SMircea Trofin   virtual void onBlockAnalyzed(const BasicBlock *BB) {}
2051c57cc2bSEaswaran Raman 
206c965fd94SKirill Naumov   /// Called before an instruction was analyzed
207c965fd94SKirill Naumov   virtual void onInstructionAnalysisStart(const Instruction *I) {}
208c965fd94SKirill Naumov 
209c965fd94SKirill Naumov   /// Called after an instruction was analyzed
210c965fd94SKirill Naumov   virtual void onInstructionAnalysisFinish(const Instruction *I) {}
211c965fd94SKirill Naumov 
21206408758SMircea Trofin   /// Called at the end of the analysis of the callsite. Return the outcome of
21306408758SMircea Trofin   /// the analysis, i.e. 'InlineResult(true)' if the inlining may happen, or
21406408758SMircea Trofin   /// the reason it can't.
2155466597fSMircea Trofin   virtual InlineResult finalizeAnalysis() { return InlineResult::success(); }
21606408758SMircea Trofin   /// Called when we're about to start processing a basic block, and every time
21706408758SMircea Trofin   /// we are done processing an instruction. Return true if there is no point in
21806408758SMircea Trofin   /// continuing the analysis (e.g. we've determined already the call site is
21906408758SMircea Trofin   /// too expensive to inline)
22006408758SMircea Trofin   virtual bool shouldStop() { return false; }
221eeae45dcSFedor Sergeev 
22206408758SMircea Trofin   /// Called before the analysis of the callee body starts (with callsite
22306408758SMircea Trofin   /// contexts propagated).  It checks callsite-specific information. Return a
22406408758SMircea Trofin   /// reason analysis can't continue if that's the case, or 'true' if it may
22506408758SMircea Trofin   /// continue.
2265466597fSMircea Trofin   virtual InlineResult onAnalysisStart() { return InlineResult::success(); }
22706408758SMircea Trofin   /// Called if the analysis engine decides SROA cannot be done for the given
22806408758SMircea Trofin   /// alloca.
22906408758SMircea Trofin   virtual void onDisableSROA(AllocaInst *Arg) {}
23006408758SMircea Trofin 
23106408758SMircea Trofin   /// Called the analysis engine determines load elimination won't happen.
23206408758SMircea Trofin   virtual void onDisableLoadElimination() {}
23306408758SMircea Trofin 
23406408758SMircea Trofin   /// Called to account for a call.
23506408758SMircea Trofin   virtual void onCallPenalty() {}
23606408758SMircea Trofin 
23706408758SMircea Trofin   /// Called to account for the expectation the inlining would result in a load
23806408758SMircea Trofin   /// elimination.
23906408758SMircea Trofin   virtual void onLoadEliminationOpportunity() {}
24006408758SMircea Trofin 
24106408758SMircea Trofin   /// Called to account for the cost of argument setup for the Call in the
24206408758SMircea Trofin   /// callee's body (not the callsite currently under analysis).
24306408758SMircea Trofin   virtual void onCallArgumentSetup(const CallBase &Call) {}
24406408758SMircea Trofin 
24506408758SMircea Trofin   /// Called to account for a load relative intrinsic.
24606408758SMircea Trofin   virtual void onLoadRelativeIntrinsic() {}
24706408758SMircea Trofin 
24806408758SMircea Trofin   /// Called to account for a lowered call.
24906408758SMircea Trofin   virtual void onLoweredCall(Function *F, CallBase &Call, bool IsIndirectCall) {
25006408758SMircea Trofin   }
25106408758SMircea Trofin 
25206408758SMircea Trofin   /// Account for a jump table of given size. Return false to stop further
25306408758SMircea Trofin   /// processing the switch instruction
25406408758SMircea Trofin   virtual bool onJumpTable(unsigned JumpTableSize) { return true; }
25506408758SMircea Trofin 
25606408758SMircea Trofin   /// Account for a case cluster of given size. Return false to stop further
25706408758SMircea Trofin   /// processing of the instruction.
25806408758SMircea Trofin   virtual bool onCaseCluster(unsigned NumCaseCluster) { return true; }
25906408758SMircea Trofin 
26006408758SMircea Trofin   /// Called at the end of processing a switch instruction, with the given
26106408758SMircea Trofin   /// number of case clusters.
26206408758SMircea Trofin   virtual void onFinalizeSwitch(unsigned JumpTableSize,
26306408758SMircea Trofin                                 unsigned NumCaseCluster) {}
26406408758SMircea Trofin 
26506408758SMircea Trofin   /// Called to account for any other instruction not specifically accounted
26606408758SMircea Trofin   /// for.
26714a16faeSMircea Trofin   virtual void onMissedSimplification() {}
26806408758SMircea Trofin 
26906408758SMircea Trofin   /// Start accounting potential benefits due to SROA for the given alloca.
27006408758SMircea Trofin   virtual void onInitializeSROAArg(AllocaInst *Arg) {}
27106408758SMircea Trofin 
27206408758SMircea Trofin   /// Account SROA savings for the AllocaInst value.
27306408758SMircea Trofin   virtual void onAggregateSROAUse(AllocaInst *V) {}
27406408758SMircea Trofin 
27506408758SMircea Trofin   bool handleSROA(Value *V, bool DoNotDisable) {
27606408758SMircea Trofin     // Check for SROA candidates in comparisons.
27706408758SMircea Trofin     if (auto *SROAArg = getSROAArgForValueOrNull(V)) {
27806408758SMircea Trofin       if (DoNotDisable) {
27906408758SMircea Trofin         onAggregateSROAUse(SROAArg);
28006408758SMircea Trofin         return true;
28106408758SMircea Trofin       }
28206408758SMircea Trofin       disableSROAForArg(SROAArg);
28306408758SMircea Trofin     }
28406408758SMircea Trofin     return false;
28506408758SMircea Trofin   }
2867adc3a2bSChandler Carruth 
287eeae45dcSFedor Sergeev   bool IsCallerRecursive = false;
288eeae45dcSFedor Sergeev   bool IsRecursiveCall = false;
289eeae45dcSFedor Sergeev   bool ExposesReturnsTwice = false;
290eeae45dcSFedor Sergeev   bool HasDynamicAlloca = false;
291eeae45dcSFedor Sergeev   bool ContainsNoDuplicateCall = false;
292eeae45dcSFedor Sergeev   bool HasReturn = false;
293eeae45dcSFedor Sergeev   bool HasIndirectBr = false;
294eeae45dcSFedor Sergeev   bool HasUninlineableIntrinsic = false;
295eeae45dcSFedor Sergeev   bool InitsVargArgs = false;
2967adc3a2bSChandler Carruth 
2977adc3a2bSChandler Carruth   /// Number of bytes allocated statically by the callee.
298eeae45dcSFedor Sergeev   uint64_t AllocatedSize = 0;
299eeae45dcSFedor Sergeev   unsigned NumInstructions = 0;
300eeae45dcSFedor Sergeev   unsigned NumVectorInstructions = 0;
301eeae45dcSFedor Sergeev 
302f3d122cdSPiotr Padlewski   /// While we walk the potentially-inlined instructions, we build up and
303f3d122cdSPiotr Padlewski   /// maintain a mapping of simplified values specific to this callsite. The
304f3d122cdSPiotr Padlewski   /// idea is to propagate any special information we have about arguments to
305f3d122cdSPiotr Padlewski   /// this call through the inlinable section of the function, and account for
306f3d122cdSPiotr Padlewski   /// likely simplifications post-inlining. The most important aspect we track
307f3d122cdSPiotr Padlewski   /// is CFG altering simplifications -- when we prove a basic block dead, that
308f3d122cdSPiotr Padlewski   /// can cause dramatic shifts in the cost of inlining a function.
3097adc3a2bSChandler Carruth   DenseMap<Value *, Constant *> SimplifiedValues;
3107adc3a2bSChandler Carruth 
311f3d122cdSPiotr Padlewski   /// Keep track of the values which map back (through function arguments) to
312f3d122cdSPiotr Padlewski   /// allocas on the caller stack which could be simplified through SROA.
31306408758SMircea Trofin   DenseMap<Value *, AllocaInst *> SROAArgValues;
314338a6016SMircea Trofin 
31506408758SMircea Trofin   /// Keep track of Allocas for which we believe we may get SROA optimization.
3162e42cc7aSMircea Trofin   DenseSet<AllocaInst *> EnabledSROAAllocas;
3177adc3a2bSChandler Carruth 
318f3d122cdSPiotr Padlewski   /// Keep track of values which map to a pointer base and constant offset.
3197adc3a2bSChandler Carruth   DenseMap<Value *, std::pair<Value *, APInt>> ConstantOffsetPtrs;
3207adc3a2bSChandler Carruth 
3213739e14aSHaicheng Wu   /// Keep track of dead blocks due to the constant arguments.
3223739e14aSHaicheng Wu   SetVector<BasicBlock *> DeadBlocks;
3233739e14aSHaicheng Wu 
3243739e14aSHaicheng Wu   /// The mapping of the blocks to their known unique successors due to the
3253739e14aSHaicheng Wu   /// constant arguments.
3263739e14aSHaicheng Wu   DenseMap<BasicBlock *, BasicBlock *> KnownSuccessors;
3273739e14aSHaicheng Wu 
328a4461515SHaicheng Wu   /// Model the elimination of repeated loads that is expected to happen
329a4461515SHaicheng Wu   /// whenever we simplify away the stores that would otherwise cause them to be
330a4461515SHaicheng Wu   /// loads.
331a4461515SHaicheng Wu   bool EnableLoadElimination;
332a4461515SHaicheng Wu   SmallPtrSet<Value *, 16> LoadAddrSet;
33306408758SMircea Trofin 
33406408758SMircea Trofin   AllocaInst *getSROAArgForValueOrNull(Value *V) const {
33506408758SMircea Trofin     auto It = SROAArgValues.find(V);
3362e42cc7aSMircea Trofin     if (It == SROAArgValues.end() || EnabledSROAAllocas.count(It->second) == 0)
33706408758SMircea Trofin       return nullptr;
33806408758SMircea Trofin     return It->second;
33906408758SMircea Trofin   }
340a4461515SHaicheng Wu 
3417adc3a2bSChandler Carruth   // Custom simplification helper routines.
3427adc3a2bSChandler Carruth   bool isAllocaDerivedArg(Value *V);
34306408758SMircea Trofin   void disableSROAForArg(AllocaInst *SROAArg);
3447adc3a2bSChandler Carruth   void disableSROA(Value *V);
3453739e14aSHaicheng Wu   void findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB);
346a4461515SHaicheng Wu   void disableLoadElimination();
347201b191bSHaicheng Wu   bool isGEPFree(GetElementPtrInst &GEP);
348d3558b5dSEvgeny Astigeevich   bool canFoldInboundsGEP(GetElementPtrInst &I);
3497adc3a2bSChandler Carruth   bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
350652168a9SFedor Sergeev   bool simplifyCallSite(Function *F, CallBase &Call);
351617f6364SEaswaran Raman   template <typename Callable>
352617f6364SEaswaran Raman   bool simplifyInstruction(Instruction &I, Callable Evaluate);
3537adc3a2bSChandler Carruth   ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
3547adc3a2bSChandler Carruth 
3557adc3a2bSChandler Carruth   /// Return true if the given argument to the function being considered for
3567adc3a2bSChandler Carruth   /// inlining has the given attribute set either at the call site or the
3577adc3a2bSChandler Carruth   /// function declaration.  Primarily used to inspect call site specific
3587adc3a2bSChandler Carruth   /// attributes since these can be more precise than the ones on the callee
3597adc3a2bSChandler Carruth   /// itself.
3607adc3a2bSChandler Carruth   bool paramHasAttr(Argument *A, Attribute::AttrKind Attr);
3617adc3a2bSChandler Carruth 
3627adc3a2bSChandler Carruth   /// Return true if the given value is known non null within the callee if
3637adc3a2bSChandler Carruth   /// inlined through this particular callsite.
3647adc3a2bSChandler Carruth   bool isKnownNonNullInCallee(Value *V);
3657adc3a2bSChandler Carruth 
366652168a9SFedor Sergeev   /// Return true if size growth is allowed when inlining the callee at \p Call.
367652168a9SFedor Sergeev   bool allowSizeGrowth(CallBase &Call);
3689a3fc17aSEaswaran Raman 
3697adc3a2bSChandler Carruth   // Custom analysis routines.
370c0aa4b75SDavid Bolvansky   InlineResult analyzeBlock(BasicBlock *BB,
371c0aa4b75SDavid Bolvansky                             SmallPtrSetImpl<const Value *> &EphValues);
3727adc3a2bSChandler Carruth 
3737adc3a2bSChandler Carruth   // Disable several entry points to the visitor so we don't accidentally use
3747adc3a2bSChandler Carruth   // them by declaring but not defining them here.
375567556aaSChad Rosier   void visit(Module *);
376567556aaSChad Rosier   void visit(Module &);
377567556aaSChad Rosier   void visit(Function *);
378567556aaSChad Rosier   void visit(Function &);
379567556aaSChad Rosier   void visit(BasicBlock *);
380567556aaSChad Rosier   void visit(BasicBlock &);
3817adc3a2bSChandler Carruth 
3827adc3a2bSChandler Carruth   // Provide base case for our instruction visit.
3837adc3a2bSChandler Carruth   bool visitInstruction(Instruction &I);
3847adc3a2bSChandler Carruth 
3857adc3a2bSChandler Carruth   // Our visit overrides.
3867adc3a2bSChandler Carruth   bool visitAlloca(AllocaInst &I);
3877adc3a2bSChandler Carruth   bool visitPHI(PHINode &I);
3887adc3a2bSChandler Carruth   bool visitGetElementPtr(GetElementPtrInst &I);
3897adc3a2bSChandler Carruth   bool visitBitCast(BitCastInst &I);
3907adc3a2bSChandler Carruth   bool visitPtrToInt(PtrToIntInst &I);
3917adc3a2bSChandler Carruth   bool visitIntToPtr(IntToPtrInst &I);
3927adc3a2bSChandler Carruth   bool visitCastInst(CastInst &I);
3937adc3a2bSChandler Carruth   bool visitCmpInst(CmpInst &I);
3947adc3a2bSChandler Carruth   bool visitSub(BinaryOperator &I);
3957adc3a2bSChandler Carruth   bool visitBinaryOperator(BinaryOperator &I);
3966cda33baSCraig Topper   bool visitFNeg(UnaryOperator &I);
3977adc3a2bSChandler Carruth   bool visitLoad(LoadInst &I);
3987adc3a2bSChandler Carruth   bool visitStore(StoreInst &I);
3997adc3a2bSChandler Carruth   bool visitExtractValue(ExtractValueInst &I);
4007adc3a2bSChandler Carruth   bool visitInsertValue(InsertValueInst &I);
401652168a9SFedor Sergeev   bool visitCallBase(CallBase &Call);
4027adc3a2bSChandler Carruth   bool visitReturnInst(ReturnInst &RI);
4037adc3a2bSChandler Carruth   bool visitBranchInst(BranchInst &BI);
4043ec848bcSHaicheng Wu   bool visitSelectInst(SelectInst &SI);
4057adc3a2bSChandler Carruth   bool visitSwitchInst(SwitchInst &SI);
4067adc3a2bSChandler Carruth   bool visitIndirectBrInst(IndirectBrInst &IBI);
4077adc3a2bSChandler Carruth   bool visitResumeInst(ResumeInst &RI);
4087adc3a2bSChandler Carruth   bool visitCleanupReturnInst(CleanupReturnInst &RI);
4097adc3a2bSChandler Carruth   bool visitCatchReturnInst(CatchReturnInst &RI);
4107adc3a2bSChandler Carruth   bool visitUnreachableInst(UnreachableInst &I);
4117adc3a2bSChandler Carruth 
4127adc3a2bSChandler Carruth public:
4137b639f50SJacob Hegna   CallAnalyzer(Function &Callee, CallBase &Call, const TargetTransformInfo &TTI,
41408e2386dSMircea Trofin                function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
41508e2386dSMircea Trofin                function_ref<BlockFrequencyInfo &(Function &)> GetBFI = nullptr,
41608e2386dSMircea Trofin                ProfileSummaryInfo *PSI = nullptr,
41708e2386dSMircea Trofin                OptimizationRemarkEmitter *ORE = nullptr)
41812585b01SEaswaran Raman       : TTI(TTI), GetAssumptionCache(GetAssumptionCache), GetBFI(GetBFI),
4190812c5beSHaicheng Wu         PSI(PSI), F(Callee), DL(F.getParent()->getDataLayout()), ORE(ORE),
42006408758SMircea Trofin         CandidateCall(Call), EnableLoadElimination(true) {}
4217adc3a2bSChandler Carruth 
42293ac81ccSMircea Trofin   InlineResult analyze();
4237adc3a2bSChandler Carruth 
4247f094f7fSKirill Naumov   Optional<Constant *> getSimplifiedValue(Instruction *I) {
4257f094f7fSKirill Naumov     if (SimplifiedValues.find(I) != SimplifiedValues.end())
4267f094f7fSKirill Naumov       return SimplifiedValues[I];
4277f094f7fSKirill Naumov     return None;
4287f094f7fSKirill Naumov   }
4297f094f7fSKirill Naumov 
4307adc3a2bSChandler Carruth   // Keep a bunch of stats about the cost savings found so we can print them
4317adc3a2bSChandler Carruth   // out when debugging.
432eeae45dcSFedor Sergeev   unsigned NumConstantArgs = 0;
433eeae45dcSFedor Sergeev   unsigned NumConstantOffsetPtrArgs = 0;
434eeae45dcSFedor Sergeev   unsigned NumAllocaArgs = 0;
435eeae45dcSFedor Sergeev   unsigned NumConstantPtrCmps = 0;
436eeae45dcSFedor Sergeev   unsigned NumConstantPtrDiffs = 0;
437eeae45dcSFedor Sergeev   unsigned NumInstructionsSimplified = 0;
43876aab66dSMircea Trofin 
43976aab66dSMircea Trofin   void dump();
44076aab66dSMircea Trofin };
441338a6016SMircea Trofin 
44299f00635SJacob Hegna // Considering forming a binary search, we should find the number of nodes
44399f00635SJacob Hegna // which is same as the number of comparisons when lowered. For a given
44499f00635SJacob Hegna // number of clusters, n, we can define a recursive function, f(n), to find
44599f00635SJacob Hegna // the number of nodes in the tree. The recursion is :
44699f00635SJacob Hegna // f(n) = 1 + f(n/2) + f (n - n/2), when n > 3,
44799f00635SJacob Hegna // and f(n) = n, when n <= 3.
44899f00635SJacob Hegna // This will lead a binary tree where the leaf should be either f(2) or f(3)
44999f00635SJacob Hegna // when n > 3.  So, the number of comparisons from leaves should be n, while
45099f00635SJacob Hegna // the number of non-leaf should be :
45199f00635SJacob Hegna //   2^(log2(n) - 1) - 1
45299f00635SJacob Hegna //   = 2^log2(n) * 2^-1 - 1
45399f00635SJacob Hegna //   = n / 2 - 1.
45499f00635SJacob Hegna // Considering comparisons from leaf and non-leaf nodes, we can estimate the
45599f00635SJacob Hegna // number of comparisons in a simple closed form :
45699f00635SJacob Hegna //   n + n / 2 - 1 = n * 3 / 2 - 1
45799f00635SJacob Hegna int64_t getExpectedNumberOfCompare(int NumCaseCluster) {
45899f00635SJacob Hegna   return 3 * static_cast<int64_t>(NumCaseCluster) / 2 - 1;
45999f00635SJacob Hegna }
46099f00635SJacob Hegna 
46106408758SMircea Trofin /// FIXME: if it is necessary to derive from InlineCostCallAnalyzer, note
46206408758SMircea Trofin /// the FIXME in onLoweredCall, when instantiating an InlineCostCallAnalyzer
46306408758SMircea Trofin class InlineCostCallAnalyzer final : public CallAnalyzer {
46406408758SMircea Trofin   const int CostUpperBound = INT_MAX - InlineConstants::InstrCost - 1;
46506408758SMircea Trofin   const bool ComputeFullInlineCost;
46606408758SMircea Trofin   int LoadEliminationCost = 0;
46706408758SMircea Trofin   /// Bonus to be applied when percentage of vector instructions in callee is
46806408758SMircea Trofin   /// high (see more details in updateThreshold).
46906408758SMircea Trofin   int VectorBonus = 0;
47006408758SMircea Trofin   /// Bonus to be applied when the callee has only one reachable basic block.
47106408758SMircea Trofin   int SingleBBBonus = 0;
47206408758SMircea Trofin 
47306408758SMircea Trofin   /// Tunable parameters that control the analysis.
47406408758SMircea Trofin   const InlineParams &Params;
47506408758SMircea Trofin 
4761022b5ebSKirill Naumov   // This DenseMap stores the delta change in cost and threshold after
4771022b5ebSKirill Naumov   // accounting for the given instruction. The map is filled only with the
4781022b5ebSKirill Naumov   // flag PrintInstructionComments on.
4791022b5ebSKirill Naumov   DenseMap<const Instruction *, InstructionCostDetail> InstructionCostDetailMap;
4801022b5ebSKirill Naumov 
48106408758SMircea Trofin   /// Upper bound for the inlining cost. Bonuses are being applied to account
48206408758SMircea Trofin   /// for speculative "expected profit" of the inlining decision.
48306408758SMircea Trofin   int Threshold = 0;
48406408758SMircea Trofin 
48506408758SMircea Trofin   /// Attempt to evaluate indirect calls to boost its inline cost.
48606408758SMircea Trofin   const bool BoostIndirectCalls;
48706408758SMircea Trofin 
4888a4013edSMircea Trofin   /// Ignore the threshold when finalizing analysis.
4898a4013edSMircea Trofin   const bool IgnoreThreshold;
4908a4013edSMircea Trofin 
4919895c701SKazu Hirata   // True if the cost-benefit-analysis-based inliner is enabled.
4929895c701SKazu Hirata   const bool CostBenefitAnalysisEnabled;
4939895c701SKazu Hirata 
49406408758SMircea Trofin   /// Inlining cost measured in abstract units, accounts for all the
49506408758SMircea Trofin   /// instructions expected to be executed for a given function invocation.
49606408758SMircea Trofin   /// Instructions that are statically proven to be dead based on call-site
49706408758SMircea Trofin   /// arguments are not counted here.
49806408758SMircea Trofin   int Cost = 0;
49906408758SMircea Trofin 
5009895c701SKazu Hirata   // The cumulative cost at the beginning of the basic block being analyzed.  At
5019895c701SKazu Hirata   // the end of analyzing each basic block, "Cost - CostAtBBStart" represents
5029895c701SKazu Hirata   // the size of that basic block.
5039895c701SKazu Hirata   int CostAtBBStart = 0;
5049895c701SKazu Hirata 
5059895c701SKazu Hirata   // The static size of live but cold basic blocks.  This is "static" in the
5069895c701SKazu Hirata   // sense that it's not weighted by profile counts at all.
5079895c701SKazu Hirata   int ColdSize = 0;
5089895c701SKazu Hirata 
5096869e6c1SWenlei He   // Whether inlining is decided by cost-benefit analysis.
5106869e6c1SWenlei He   bool DecidedByCostBenefit = false;
5116869e6c1SWenlei He 
51206408758SMircea Trofin   bool SingleBB = true;
51306408758SMircea Trofin 
51406408758SMircea Trofin   unsigned SROACostSavings = 0;
51506408758SMircea Trofin   unsigned SROACostSavingsLost = 0;
51606408758SMircea Trofin 
51706408758SMircea Trofin   /// The mapping of caller Alloca values to their accumulated cost savings. If
51806408758SMircea Trofin   /// we have to disable SROA for one of the allocas, this tells us how much
51906408758SMircea Trofin   /// cost must be added.
52006408758SMircea Trofin   DenseMap<AllocaInst *, int> SROAArgCosts;
52106408758SMircea Trofin 
52206408758SMircea Trofin   /// Return true if \p Call is a cold callsite.
52306408758SMircea Trofin   bool isColdCallSite(CallBase &Call, BlockFrequencyInfo *CallerBFI);
52406408758SMircea Trofin 
52506408758SMircea Trofin   /// Update Threshold based on callsite properties such as callee
52606408758SMircea Trofin   /// attributes and callee hotness for PGO builds. The Callee is explicitly
52706408758SMircea Trofin   /// passed to support analyzing indirect calls whose target is inferred by
52806408758SMircea Trofin   /// analysis.
52906408758SMircea Trofin   void updateThreshold(CallBase &Call, Function &Callee);
53006408758SMircea Trofin   /// Return a higher threshold if \p Call is a hot callsite.
53106408758SMircea Trofin   Optional<int> getHotCallSiteThreshold(CallBase &Call,
53206408758SMircea Trofin                                         BlockFrequencyInfo *CallerBFI);
53306408758SMircea Trofin 
53406408758SMircea Trofin   /// Handle a capped 'int' increment for Cost.
53506408758SMircea Trofin   void addCost(int64_t Inc, int64_t UpperBound = INT_MAX) {
53606408758SMircea Trofin     assert(UpperBound > 0 && UpperBound <= INT_MAX && "invalid upper bound");
53706408758SMircea Trofin     Cost = (int)std::min(UpperBound, Cost + Inc);
53806408758SMircea Trofin   }
53906408758SMircea Trofin 
54006408758SMircea Trofin   void onDisableSROA(AllocaInst *Arg) override {
54106408758SMircea Trofin     auto CostIt = SROAArgCosts.find(Arg);
54206408758SMircea Trofin     if (CostIt == SROAArgCosts.end())
54306408758SMircea Trofin       return;
54406408758SMircea Trofin     addCost(CostIt->second);
54506408758SMircea Trofin     SROACostSavings -= CostIt->second;
54606408758SMircea Trofin     SROACostSavingsLost += CostIt->second;
54706408758SMircea Trofin     SROAArgCosts.erase(CostIt);
54806408758SMircea Trofin   }
54906408758SMircea Trofin 
55006408758SMircea Trofin   void onDisableLoadElimination() override {
55106408758SMircea Trofin     addCost(LoadEliminationCost);
55206408758SMircea Trofin     LoadEliminationCost = 0;
55306408758SMircea Trofin   }
55406408758SMircea Trofin   void onCallPenalty() override { addCost(InlineConstants::CallPenalty); }
55506408758SMircea Trofin   void onCallArgumentSetup(const CallBase &Call) override {
55606408758SMircea Trofin     // Pay the price of the argument setup. We account for the average 1
55706408758SMircea Trofin     // instruction per call argument setup here.
55806408758SMircea Trofin     addCost(Call.arg_size() * InlineConstants::InstrCost);
55906408758SMircea Trofin   }
56006408758SMircea Trofin   void onLoadRelativeIntrinsic() override {
56106408758SMircea Trofin     // This is normally lowered to 4 LLVM instructions.
56206408758SMircea Trofin     addCost(3 * InlineConstants::InstrCost);
56306408758SMircea Trofin   }
56406408758SMircea Trofin   void onLoweredCall(Function *F, CallBase &Call,
56506408758SMircea Trofin                      bool IsIndirectCall) override {
56606408758SMircea Trofin     // We account for the average 1 instruction per call argument setup here.
56706408758SMircea Trofin     addCost(Call.arg_size() * InlineConstants::InstrCost);
56806408758SMircea Trofin 
56906408758SMircea Trofin     // If we have a constant that we are calling as a function, we can peer
57006408758SMircea Trofin     // through it and see the function target. This happens not infrequently
57106408758SMircea Trofin     // during devirtualization and so we want to give it a hefty bonus for
57206408758SMircea Trofin     // inlining, but cap that bonus in the event that inlining wouldn't pan out.
57306408758SMircea Trofin     // Pretend to inline the function, with a custom threshold.
57406408758SMircea Trofin     if (IsIndirectCall && BoostIndirectCalls) {
57506408758SMircea Trofin       auto IndirectCallParams = Params;
57606408758SMircea Trofin       IndirectCallParams.DefaultThreshold =
57706408758SMircea Trofin           InlineConstants::IndirectCallThreshold;
57806408758SMircea Trofin       /// FIXME: if InlineCostCallAnalyzer is derived from, this may need
57906408758SMircea Trofin       /// to instantiate the derived class.
58008e2386dSMircea Trofin       InlineCostCallAnalyzer CA(*F, Call, IndirectCallParams, TTI,
58108e2386dSMircea Trofin                                 GetAssumptionCache, GetBFI, PSI, ORE, false);
5825466597fSMircea Trofin       if (CA.analyze().isSuccess()) {
58306408758SMircea Trofin         // We were able to inline the indirect call! Subtract the cost from the
58406408758SMircea Trofin         // threshold to get the bonus we want to apply, but don't go below zero.
58506408758SMircea Trofin         Cost -= std::max(0, CA.getThreshold() - CA.getCost());
58606408758SMircea Trofin       }
58706408758SMircea Trofin     } else
58806408758SMircea Trofin       // Otherwise simply add the cost for merely making the call.
58906408758SMircea Trofin       addCost(InlineConstants::CallPenalty);
59006408758SMircea Trofin   }
59106408758SMircea Trofin 
59206408758SMircea Trofin   void onFinalizeSwitch(unsigned JumpTableSize,
59306408758SMircea Trofin                         unsigned NumCaseCluster) override {
59406408758SMircea Trofin     // If suitable for a jump table, consider the cost for the table size and
59506408758SMircea Trofin     // branch to destination.
59606408758SMircea Trofin     // Maximum valid cost increased in this function.
59706408758SMircea Trofin     if (JumpTableSize) {
59806408758SMircea Trofin       int64_t JTCost = (int64_t)JumpTableSize * InlineConstants::InstrCost +
59906408758SMircea Trofin                        4 * InlineConstants::InstrCost;
60006408758SMircea Trofin 
60106408758SMircea Trofin       addCost(JTCost, (int64_t)CostUpperBound);
60206408758SMircea Trofin       return;
60306408758SMircea Trofin     }
60499f00635SJacob Hegna 
60506408758SMircea Trofin     if (NumCaseCluster <= 3) {
60606408758SMircea Trofin       // Suppose a comparison includes one compare and one conditional branch.
60706408758SMircea Trofin       addCost(NumCaseCluster * 2 * InlineConstants::InstrCost);
60806408758SMircea Trofin       return;
60906408758SMircea Trofin     }
61006408758SMircea Trofin 
61199f00635SJacob Hegna     int64_t ExpectedNumberOfCompare =
61299f00635SJacob Hegna         getExpectedNumberOfCompare(NumCaseCluster);
61306408758SMircea Trofin     int64_t SwitchCost =
61406408758SMircea Trofin         ExpectedNumberOfCompare * 2 * InlineConstants::InstrCost;
61506408758SMircea Trofin 
61606408758SMircea Trofin     addCost(SwitchCost, (int64_t)CostUpperBound);
61706408758SMircea Trofin   }
61814a16faeSMircea Trofin   void onMissedSimplification() override {
61906408758SMircea Trofin     addCost(InlineConstants::InstrCost);
62006408758SMircea Trofin   }
62106408758SMircea Trofin 
62206408758SMircea Trofin   void onInitializeSROAArg(AllocaInst *Arg) override {
62306408758SMircea Trofin     assert(Arg != nullptr &&
62406408758SMircea Trofin            "Should not initialize SROA costs for null value.");
62506408758SMircea Trofin     SROAArgCosts[Arg] = 0;
62606408758SMircea Trofin   }
62706408758SMircea Trofin 
62806408758SMircea Trofin   void onAggregateSROAUse(AllocaInst *SROAArg) override {
62906408758SMircea Trofin     auto CostIt = SROAArgCosts.find(SROAArg);
63006408758SMircea Trofin     assert(CostIt != SROAArgCosts.end() &&
63106408758SMircea Trofin            "expected this argument to have a cost");
63206408758SMircea Trofin     CostIt->second += InlineConstants::InstrCost;
63306408758SMircea Trofin     SROACostSavings += InlineConstants::InstrCost;
63406408758SMircea Trofin   }
63506408758SMircea Trofin 
6369895c701SKazu Hirata   void onBlockStart(const BasicBlock *BB) override { CostAtBBStart = Cost; }
6379895c701SKazu Hirata 
63806408758SMircea Trofin   void onBlockAnalyzed(const BasicBlock *BB) override {
6399895c701SKazu Hirata     if (CostBenefitAnalysisEnabled) {
6409895c701SKazu Hirata       // Keep track of the static size of live but cold basic blocks.  For now,
6419895c701SKazu Hirata       // we define a cold basic block to be one that's never executed.
6429895c701SKazu Hirata       assert(GetBFI && "GetBFI must be available");
6439895c701SKazu Hirata       BlockFrequencyInfo *BFI = &(GetBFI(F));
6449895c701SKazu Hirata       assert(BFI && "BFI must be available");
6459895c701SKazu Hirata       auto ProfileCount = BFI->getBlockProfileCount(BB);
6469895c701SKazu Hirata       assert(ProfileCount.hasValue());
6479895c701SKazu Hirata       if (ProfileCount.getValue() == 0)
6489895c701SKazu Hirata         ColdSize += Cost - CostAtBBStart;
6499895c701SKazu Hirata     }
6509895c701SKazu Hirata 
65106408758SMircea Trofin     auto *TI = BB->getTerminator();
65206408758SMircea Trofin     // If we had any successors at this point, than post-inlining is likely to
65306408758SMircea Trofin     // have them as well. Note that we assume any basic blocks which existed
65406408758SMircea Trofin     // due to branches or switches which folded above will also fold after
65506408758SMircea Trofin     // inlining.
65606408758SMircea Trofin     if (SingleBB && TI->getNumSuccessors() > 1) {
65706408758SMircea Trofin       // Take off the bonus we applied to the threshold.
65806408758SMircea Trofin       Threshold -= SingleBBBonus;
65906408758SMircea Trofin       SingleBB = false;
66006408758SMircea Trofin     }
66106408758SMircea Trofin   }
6625466597fSMircea Trofin 
663c965fd94SKirill Naumov   void onInstructionAnalysisStart(const Instruction *I) override {
664c965fd94SKirill Naumov     // This function is called to store the initial cost of inlining before
665c965fd94SKirill Naumov     // the given instruction was assessed.
6661022b5ebSKirill Naumov     if (!PrintInstructionComments)
667c965fd94SKirill Naumov       return;
6681022b5ebSKirill Naumov     InstructionCostDetailMap[I].CostBefore = Cost;
6691022b5ebSKirill Naumov     InstructionCostDetailMap[I].ThresholdBefore = Threshold;
670c965fd94SKirill Naumov   }
671c965fd94SKirill Naumov 
672c965fd94SKirill Naumov   void onInstructionAnalysisFinish(const Instruction *I) override {
673c965fd94SKirill Naumov     // This function is called to find new values of cost and threshold after
674c965fd94SKirill Naumov     // the instruction has been assessed.
6751022b5ebSKirill Naumov     if (!PrintInstructionComments)
676c965fd94SKirill Naumov       return;
6771022b5ebSKirill Naumov     InstructionCostDetailMap[I].CostAfter = Cost;
6781022b5ebSKirill Naumov     InstructionCostDetailMap[I].ThresholdAfter = Threshold;
679c965fd94SKirill Naumov   }
680c965fd94SKirill Naumov 
6819895c701SKazu Hirata   bool isCostBenefitAnalysisEnabled() {
6829895c701SKazu Hirata     if (!PSI || !PSI->hasProfileSummary())
6839895c701SKazu Hirata       return false;
6849895c701SKazu Hirata 
6859895c701SKazu Hirata     if (!GetBFI)
6869895c701SKazu Hirata       return false;
6879895c701SKazu Hirata 
6889d375a40SKazu Hirata     if (InlineEnableCostBenefitAnalysis.getNumOccurrences()) {
6899d375a40SKazu Hirata       // Honor the explicit request from the user.
6909d375a40SKazu Hirata       if (!InlineEnableCostBenefitAnalysis)
6919d375a40SKazu Hirata         return false;
6929d375a40SKazu Hirata     } else {
6939d375a40SKazu Hirata       // Otherwise, require instrumentation profile.
6949d375a40SKazu Hirata       if (!PSI->hasInstrumentationProfile())
6959d375a40SKazu Hirata         return false;
6969d375a40SKazu Hirata     }
6979d375a40SKazu Hirata 
6989895c701SKazu Hirata     auto *Caller = CandidateCall.getParent()->getParent();
6999895c701SKazu Hirata     if (!Caller->getEntryCount())
7009895c701SKazu Hirata       return false;
7019895c701SKazu Hirata 
7029895c701SKazu Hirata     BlockFrequencyInfo *CallerBFI = &(GetBFI(*Caller));
7039895c701SKazu Hirata     if (!CallerBFI)
7049895c701SKazu Hirata       return false;
7059895c701SKazu Hirata 
7069895c701SKazu Hirata     // For now, limit to hot call site.
7079895c701SKazu Hirata     if (!PSI->isHotCallSite(CandidateCall, CallerBFI))
7089895c701SKazu Hirata       return false;
7099895c701SKazu Hirata 
7103c775d93SKazu Hirata     // Make sure we have a nonzero entry count.
7113c775d93SKazu Hirata     auto EntryCount = F.getEntryCount();
7123c775d93SKazu Hirata     if (!EntryCount || !EntryCount.getCount())
7139895c701SKazu Hirata       return false;
7149895c701SKazu Hirata 
7159895c701SKazu Hirata     BlockFrequencyInfo *CalleeBFI = &(GetBFI(F));
7169895c701SKazu Hirata     if (!CalleeBFI)
7179895c701SKazu Hirata       return false;
7189895c701SKazu Hirata 
7199895c701SKazu Hirata     return true;
7209895c701SKazu Hirata   }
7219895c701SKazu Hirata 
7229895c701SKazu Hirata   // Determine whether we should inline the given call site, taking into account
7239895c701SKazu Hirata   // both the size cost and the cycle savings.  Return None if we don't have
7249895c701SKazu Hirata   // suficient profiling information to determine.
7259895c701SKazu Hirata   Optional<bool> costBenefitAnalysis() {
7269895c701SKazu Hirata     if (!CostBenefitAnalysisEnabled)
7279895c701SKazu Hirata       return None;
7289895c701SKazu Hirata 
7299895c701SKazu Hirata     // buildInlinerPipeline in the pass builder sets HotCallSiteThreshold to 0
7309895c701SKazu Hirata     // for the prelink phase of the AutoFDO + ThinLTO build.  Honor the logic by
7319895c701SKazu Hirata     // falling back to the cost-based metric.
7329895c701SKazu Hirata     // TODO: Improve this hacky condition.
7339895c701SKazu Hirata     if (Threshold == 0)
7349895c701SKazu Hirata       return None;
7359895c701SKazu Hirata 
7369895c701SKazu Hirata     assert(GetBFI);
7379895c701SKazu Hirata     BlockFrequencyInfo *CalleeBFI = &(GetBFI(F));
7389895c701SKazu Hirata     assert(CalleeBFI);
7399895c701SKazu Hirata 
7409895c701SKazu Hirata     // The cycle savings expressed as the sum of InlineConstants::InstrCost
7419895c701SKazu Hirata     // multiplied by the estimated dynamic count of each instruction we can
7429895c701SKazu Hirata     // avoid.  Savings come from the call site cost, such as argument setup and
7439895c701SKazu Hirata     // the call instruction, as well as the instructions that are folded.
7449895c701SKazu Hirata     //
7459895c701SKazu Hirata     // We use 128-bit APInt here to avoid potential overflow.  This variable
7469895c701SKazu Hirata     // should stay well below 10^^24 (or 2^^80) in practice.  This "worst" case
7479895c701SKazu Hirata     // assumes that we can avoid or fold a billion instructions, each with a
7489895c701SKazu Hirata     // profile count of 10^^15 -- roughly the number of cycles for a 24-hour
7499895c701SKazu Hirata     // period on a 4GHz machine.
7509895c701SKazu Hirata     APInt CycleSavings(128, 0);
7519895c701SKazu Hirata 
7529895c701SKazu Hirata     for (auto &BB : F) {
7539895c701SKazu Hirata       APInt CurrentSavings(128, 0);
7549895c701SKazu Hirata       for (auto &I : BB) {
7559895c701SKazu Hirata         if (BranchInst *BI = dyn_cast<BranchInst>(&I)) {
7569895c701SKazu Hirata           // Count a conditional branch as savings if it becomes unconditional.
7579895c701SKazu Hirata           if (BI->isConditional() &&
7589895c701SKazu Hirata               dyn_cast_or_null<ConstantInt>(
7599895c701SKazu Hirata                   SimplifiedValues.lookup(BI->getCondition()))) {
7609895c701SKazu Hirata             CurrentSavings += InlineConstants::InstrCost;
7619895c701SKazu Hirata           }
7629895c701SKazu Hirata         } else if (Value *V = dyn_cast<Value>(&I)) {
7639895c701SKazu Hirata           // Count an instruction as savings if we can fold it.
7649895c701SKazu Hirata           if (SimplifiedValues.count(V)) {
7659895c701SKazu Hirata             CurrentSavings += InlineConstants::InstrCost;
7669895c701SKazu Hirata           }
7679895c701SKazu Hirata         }
7689895c701SKazu Hirata       }
7699895c701SKazu Hirata 
7709895c701SKazu Hirata       auto ProfileCount = CalleeBFI->getBlockProfileCount(&BB);
7719895c701SKazu Hirata       assert(ProfileCount.hasValue());
7729895c701SKazu Hirata       CurrentSavings *= ProfileCount.getValue();
7739895c701SKazu Hirata       CycleSavings += CurrentSavings;
7749895c701SKazu Hirata     }
7759895c701SKazu Hirata 
7769895c701SKazu Hirata     // Compute the cycle savings per call.
7779895c701SKazu Hirata     auto EntryProfileCount = F.getEntryCount();
7783c775d93SKazu Hirata     assert(EntryProfileCount.hasValue() && EntryProfileCount.getCount());
7799895c701SKazu Hirata     auto EntryCount = EntryProfileCount.getCount();
7809895c701SKazu Hirata     CycleSavings += EntryCount / 2;
7819895c701SKazu Hirata     CycleSavings = CycleSavings.udiv(EntryCount);
7829895c701SKazu Hirata 
7839895c701SKazu Hirata     // Compute the total savings for the call site.
7849895c701SKazu Hirata     auto *CallerBB = CandidateCall.getParent();
7859895c701SKazu Hirata     BlockFrequencyInfo *CallerBFI = &(GetBFI(*(CallerBB->getParent())));
7869895c701SKazu Hirata     CycleSavings += getCallsiteCost(this->CandidateCall, DL);
7879895c701SKazu Hirata     CycleSavings *= CallerBFI->getBlockProfileCount(CallerBB).getValue();
7889895c701SKazu Hirata 
7899895c701SKazu Hirata     // Remove the cost of the cold basic blocks.
7909895c701SKazu Hirata     int Size = Cost - ColdSize;
7919895c701SKazu Hirata 
7929895c701SKazu Hirata     // Allow tiny callees to be inlined regardless of whether they meet the
7939895c701SKazu Hirata     // savings threshold.
7949895c701SKazu Hirata     Size = Size > InlineSizeAllowance ? Size - InlineSizeAllowance : 1;
7959895c701SKazu Hirata 
7969895c701SKazu Hirata     // Return true if the savings justify the cost of inlining.  Specifically,
7979895c701SKazu Hirata     // we evaluate the following inequality:
7989895c701SKazu Hirata     //
7999895c701SKazu Hirata     //  CycleSavings      PSI->getOrCompHotCountThreshold()
8009895c701SKazu Hirata     // -------------- >= -----------------------------------
8019895c701SKazu Hirata     //       Size              InlineSavingsMultiplier
8029895c701SKazu Hirata     //
8039895c701SKazu Hirata     // Note that the left hand side is specific to a call site.  The right hand
8049895c701SKazu Hirata     // side is a constant for the entire executable.
8059895c701SKazu Hirata     APInt LHS = CycleSavings;
8069895c701SKazu Hirata     LHS *= InlineSavingsMultiplier;
8079895c701SKazu Hirata     APInt RHS(128, PSI->getOrCompHotCountThreshold());
8089895c701SKazu Hirata     RHS *= Size;
8099895c701SKazu Hirata     return LHS.uge(RHS);
8109895c701SKazu Hirata   }
8119895c701SKazu Hirata 
81206408758SMircea Trofin   InlineResult finalizeAnalysis() override {
81306408758SMircea Trofin     // Loops generally act a lot like calls in that they act like barriers to
81406408758SMircea Trofin     // movement, require a certain amount of setup, etc. So when optimising for
81506408758SMircea Trofin     // size, we penalise any call sites that perform loops. We do this after all
81606408758SMircea Trofin     // other costs here, so will likely only be dealing with relatively small
81706408758SMircea Trofin     // functions (and hence DT and LI will hopefully be cheap).
81806408758SMircea Trofin     auto *Caller = CandidateCall.getFunction();
81906408758SMircea Trofin     if (Caller->hasMinSize()) {
82006408758SMircea Trofin       DominatorTree DT(F);
82106408758SMircea Trofin       LoopInfo LI(DT);
82206408758SMircea Trofin       int NumLoops = 0;
82306408758SMircea Trofin       for (Loop *L : LI) {
82406408758SMircea Trofin         // Ignore loops that will not be executed
82506408758SMircea Trofin         if (DeadBlocks.count(L->getHeader()))
82606408758SMircea Trofin           continue;
82706408758SMircea Trofin         NumLoops++;
82806408758SMircea Trofin       }
82906408758SMircea Trofin       addCost(NumLoops * InlineConstants::CallPenalty);
83006408758SMircea Trofin     }
83106408758SMircea Trofin 
83206408758SMircea Trofin     // We applied the maximum possible vector bonus at the beginning. Now,
83306408758SMircea Trofin     // subtract the excess bonus, if any, from the Threshold before
83406408758SMircea Trofin     // comparing against Cost.
83506408758SMircea Trofin     if (NumVectorInstructions <= NumInstructions / 10)
83606408758SMircea Trofin       Threshold -= VectorBonus;
83706408758SMircea Trofin     else if (NumVectorInstructions <= NumInstructions / 2)
83806408758SMircea Trofin       Threshold -= VectorBonus / 2;
83906408758SMircea Trofin 
8409895c701SKazu Hirata     if (auto Result = costBenefitAnalysis()) {
8416869e6c1SWenlei He       DecidedByCostBenefit = true;
8429895c701SKazu Hirata       if (Result.getValue())
8439895c701SKazu Hirata         return InlineResult::success();
8449895c701SKazu Hirata       else
8459895c701SKazu Hirata         return InlineResult::failure("Cost over threshold.");
8469895c701SKazu Hirata     }
8479895c701SKazu Hirata 
8488a4013edSMircea Trofin     if (IgnoreThreshold || Cost < std::max(1, Threshold))
8495466597fSMircea Trofin       return InlineResult::success();
8505466597fSMircea Trofin     return InlineResult::failure("Cost over threshold.");
85106408758SMircea Trofin   }
85206408758SMircea Trofin   bool shouldStop() override {
85306408758SMircea Trofin     // Bail out the moment we cross the threshold. This means we'll under-count
85406408758SMircea Trofin     // the cost, but only when undercounting doesn't matter.
8558a4013edSMircea Trofin     return !IgnoreThreshold && Cost >= Threshold && !ComputeFullInlineCost;
85606408758SMircea Trofin   }
85706408758SMircea Trofin 
85806408758SMircea Trofin   void onLoadEliminationOpportunity() override {
85906408758SMircea Trofin     LoadEliminationCost += InlineConstants::InstrCost;
86006408758SMircea Trofin   }
86106408758SMircea Trofin 
86206408758SMircea Trofin   InlineResult onAnalysisStart() override {
86306408758SMircea Trofin     // Perform some tweaks to the cost and threshold based on the direct
86406408758SMircea Trofin     // callsite information.
86506408758SMircea Trofin 
86606408758SMircea Trofin     // We want to more aggressively inline vector-dense kernels, so up the
86706408758SMircea Trofin     // threshold, and we'll lower it if the % of vector instructions gets too
86806408758SMircea Trofin     // low. Note that these bonuses are some what arbitrary and evolved over
86906408758SMircea Trofin     // time by accident as much as because they are principled bonuses.
87006408758SMircea Trofin     //
87106408758SMircea Trofin     // FIXME: It would be nice to remove all such bonuses. At least it would be
87206408758SMircea Trofin     // nice to base the bonus values on something more scientific.
87306408758SMircea Trofin     assert(NumInstructions == 0);
87406408758SMircea Trofin     assert(NumVectorInstructions == 0);
87506408758SMircea Trofin 
87606408758SMircea Trofin     // Update the threshold based on callsite properties
87706408758SMircea Trofin     updateThreshold(CandidateCall, F);
87806408758SMircea Trofin 
87906408758SMircea Trofin     // While Threshold depends on commandline options that can take negative
88006408758SMircea Trofin     // values, we want to enforce the invariant that the computed threshold and
88106408758SMircea Trofin     // bonuses are non-negative.
88206408758SMircea Trofin     assert(Threshold >= 0);
88306408758SMircea Trofin     assert(SingleBBBonus >= 0);
88406408758SMircea Trofin     assert(VectorBonus >= 0);
88506408758SMircea Trofin 
88606408758SMircea Trofin     // Speculatively apply all possible bonuses to Threshold. If cost exceeds
88706408758SMircea Trofin     // this Threshold any time, and cost cannot decrease, we can stop processing
88806408758SMircea Trofin     // the rest of the function body.
88906408758SMircea Trofin     Threshold += (SingleBBBonus + VectorBonus);
89006408758SMircea Trofin 
89106408758SMircea Trofin     // Give out bonuses for the callsite, as the instructions setting them up
89206408758SMircea Trofin     // will be gone after inlining.
89306408758SMircea Trofin     addCost(-getCallsiteCost(this->CandidateCall, DL));
89406408758SMircea Trofin 
89506408758SMircea Trofin     // If this function uses the coldcc calling convention, prefer not to inline
89606408758SMircea Trofin     // it.
89706408758SMircea Trofin     if (F.getCallingConv() == CallingConv::Cold)
89806408758SMircea Trofin       Cost += InlineConstants::ColdccPenalty;
89906408758SMircea Trofin 
90006408758SMircea Trofin     // Check if we're done. This can happen due to bonuses and penalties.
90106408758SMircea Trofin     if (Cost >= Threshold && !ComputeFullInlineCost)
9025466597fSMircea Trofin       return InlineResult::failure("high cost");
90306408758SMircea Trofin 
9045466597fSMircea Trofin     return InlineResult::success();
90506408758SMircea Trofin   }
90606408758SMircea Trofin 
90706408758SMircea Trofin public:
90806408758SMircea Trofin   InlineCostCallAnalyzer(
90908e2386dSMircea Trofin       Function &Callee, CallBase &Call, const InlineParams &Params,
91006408758SMircea Trofin       const TargetTransformInfo &TTI,
91108e2386dSMircea Trofin       function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
91208e2386dSMircea Trofin       function_ref<BlockFrequencyInfo &(Function &)> GetBFI = nullptr,
91308e2386dSMircea Trofin       ProfileSummaryInfo *PSI = nullptr,
91408e2386dSMircea Trofin       OptimizationRemarkEmitter *ORE = nullptr, bool BoostIndirect = true,
9158a4013edSMircea Trofin       bool IgnoreThreshold = false)
91608e2386dSMircea Trofin       : CallAnalyzer(Callee, Call, TTI, GetAssumptionCache, GetBFI, PSI, ORE),
91706408758SMircea Trofin         ComputeFullInlineCost(OptComputeFullInlineCost ||
91865cd3cbbSKazu Hirata                               Params.ComputeFullInlineCost || ORE ||
91965cd3cbbSKazu Hirata                               isCostBenefitAnalysisEnabled()),
92006408758SMircea Trofin         Params(Params), Threshold(Params.DefaultThreshold),
9211022b5ebSKirill Naumov         BoostIndirectCalls(BoostIndirect), IgnoreThreshold(IgnoreThreshold),
9229895c701SKazu Hirata         CostBenefitAnalysisEnabled(isCostBenefitAnalysisEnabled()),
9231022b5ebSKirill Naumov         Writer(this) {}
924c965fd94SKirill Naumov 
9251022b5ebSKirill Naumov   /// Annotation Writer for instruction details
9261022b5ebSKirill Naumov   InlineCostAnnotationWriter Writer;
927c965fd94SKirill Naumov 
92806408758SMircea Trofin   void dump();
92906408758SMircea Trofin 
930ca899bf9SKirill Naumov   // Prints the same analysis as dump(), but its definition is not dependent
931ca899bf9SKirill Naumov   // on the build.
932ca899bf9SKirill Naumov   void print();
933ca899bf9SKirill Naumov 
9341022b5ebSKirill Naumov   Optional<InstructionCostDetail> getCostDetails(const Instruction *I) {
9351022b5ebSKirill Naumov     if (InstructionCostDetailMap.find(I) != InstructionCostDetailMap.end())
9361022b5ebSKirill Naumov       return InstructionCostDetailMap[I];
9371022b5ebSKirill Naumov     return None;
9381022b5ebSKirill Naumov   }
9391022b5ebSKirill Naumov 
94006408758SMircea Trofin   virtual ~InlineCostCallAnalyzer() {}
94106408758SMircea Trofin   int getThreshold() { return Threshold; }
94206408758SMircea Trofin   int getCost() { return Cost; }
9436869e6c1SWenlei He   bool wasDecidedByCostBenefit() { return DecidedByCostBenefit; }
94406408758SMircea Trofin };
94599f00635SJacob Hegna 
94699f00635SJacob Hegna class InlineCostFeaturesAnalyzer final : public CallAnalyzer {
94799f00635SJacob Hegna private:
94899f00635SJacob Hegna   InlineCostFeatures Cost = {};
94999f00635SJacob Hegna 
95099f00635SJacob Hegna   // FIXME: These constants are taken from the heuristic-based cost visitor.
95199f00635SJacob Hegna   // These should be removed entirely in a later revision to avoid reliance on
95299f00635SJacob Hegna   // heuristics in the ML inliner.
95399f00635SJacob Hegna   static constexpr int JTCostMultiplier = 4;
95499f00635SJacob Hegna   static constexpr int CaseClusterCostMultiplier = 2;
95599f00635SJacob Hegna   static constexpr int SwitchCostMultiplier = 2;
95699f00635SJacob Hegna 
95799f00635SJacob Hegna   // FIXME: These are taken from the heuristic-based cost visitor: we should
95899f00635SJacob Hegna   // eventually abstract these to the CallAnalyzer to avoid duplication.
95999f00635SJacob Hegna   unsigned SROACostSavingOpportunities = 0;
96099f00635SJacob Hegna   int VectorBonus = 0;
96199f00635SJacob Hegna   int SingleBBBonus = 0;
96299f00635SJacob Hegna   int Threshold = 5;
96399f00635SJacob Hegna 
96499f00635SJacob Hegna   DenseMap<AllocaInst *, unsigned> SROACosts;
96599f00635SJacob Hegna 
96699f00635SJacob Hegna   void increment(InlineCostFeatureIndex Feature, int64_t Delta = 1) {
96799f00635SJacob Hegna     Cost[static_cast<size_t>(Feature)] += Delta;
96899f00635SJacob Hegna   }
96999f00635SJacob Hegna 
97099f00635SJacob Hegna   void set(InlineCostFeatureIndex Feature, int64_t Value) {
97199f00635SJacob Hegna     Cost[static_cast<size_t>(Feature)] = Value;
97299f00635SJacob Hegna   }
97399f00635SJacob Hegna 
97499f00635SJacob Hegna   void onDisableSROA(AllocaInst *Arg) override {
97599f00635SJacob Hegna     auto CostIt = SROACosts.find(Arg);
97699f00635SJacob Hegna     if (CostIt == SROACosts.end())
97799f00635SJacob Hegna       return;
97899f00635SJacob Hegna 
97999f00635SJacob Hegna     increment(InlineCostFeatureIndex::SROALosses, CostIt->second);
98099f00635SJacob Hegna     SROACostSavingOpportunities -= CostIt->second;
98199f00635SJacob Hegna     SROACosts.erase(CostIt);
98299f00635SJacob Hegna   }
98399f00635SJacob Hegna 
98499f00635SJacob Hegna   void onDisableLoadElimination() override {
98599f00635SJacob Hegna     set(InlineCostFeatureIndex::LoadElimination, 1);
98699f00635SJacob Hegna   }
98799f00635SJacob Hegna 
98899f00635SJacob Hegna   void onCallPenalty() override {
98999f00635SJacob Hegna     increment(InlineCostFeatureIndex::CallPenalty,
99099f00635SJacob Hegna               InlineConstants::CallPenalty);
99199f00635SJacob Hegna   }
99299f00635SJacob Hegna 
99399f00635SJacob Hegna   void onCallArgumentSetup(const CallBase &Call) override {
99499f00635SJacob Hegna     increment(InlineCostFeatureIndex::CallArgumentSetup,
99599f00635SJacob Hegna               Call.arg_size() * InlineConstants::InstrCost);
99699f00635SJacob Hegna   }
99799f00635SJacob Hegna 
99899f00635SJacob Hegna   void onLoadRelativeIntrinsic() override {
99999f00635SJacob Hegna     increment(InlineCostFeatureIndex::LoadRelativeIntrinsic,
100099f00635SJacob Hegna               3 * InlineConstants::InstrCost);
100199f00635SJacob Hegna   }
100299f00635SJacob Hegna 
100399f00635SJacob Hegna   void onLoweredCall(Function *F, CallBase &Call,
100499f00635SJacob Hegna                      bool IsIndirectCall) override {
100599f00635SJacob Hegna     increment(InlineCostFeatureIndex::LoweredCallArgSetup,
100699f00635SJacob Hegna               Call.arg_size() * InlineConstants::InstrCost);
100799f00635SJacob Hegna 
100899f00635SJacob Hegna     if (IsIndirectCall) {
100999f00635SJacob Hegna       InlineParams IndirectCallParams = {/* DefaultThreshold*/ 0,
101099f00635SJacob Hegna                                          /*HintThreshold*/ {},
101199f00635SJacob Hegna                                          /*ColdThreshold*/ {},
101299f00635SJacob Hegna                                          /*OptSizeThreshold*/ {},
101399f00635SJacob Hegna                                          /*OptMinSizeThreshold*/ {},
101499f00635SJacob Hegna                                          /*HotCallSiteThreshold*/ {},
101599f00635SJacob Hegna                                          /*LocallyHotCallSiteThreshold*/ {},
101699f00635SJacob Hegna                                          /*ColdCallSiteThreshold*/ {},
101799f00635SJacob Hegna                                          /*ComputeFullInlineCost*/ true,
101899f00635SJacob Hegna                                          /*EnableDeferral*/ true};
101999f00635SJacob Hegna       IndirectCallParams.DefaultThreshold =
102099f00635SJacob Hegna           InlineConstants::IndirectCallThreshold;
102199f00635SJacob Hegna 
102299f00635SJacob Hegna       InlineCostCallAnalyzer CA(*F, Call, IndirectCallParams, TTI,
102399f00635SJacob Hegna                                 GetAssumptionCache, GetBFI, PSI, ORE, false,
102499f00635SJacob Hegna                                 true);
102599f00635SJacob Hegna       if (CA.analyze().isSuccess()) {
102699f00635SJacob Hegna         increment(InlineCostFeatureIndex::NestedInlineCostEstimate,
102799f00635SJacob Hegna                   CA.getCost());
102899f00635SJacob Hegna         increment(InlineCostFeatureIndex::NestedInlines, 1);
102999f00635SJacob Hegna       }
103099f00635SJacob Hegna     } else {
103199f00635SJacob Hegna       onCallPenalty();
103299f00635SJacob Hegna     }
103399f00635SJacob Hegna   }
103499f00635SJacob Hegna 
103599f00635SJacob Hegna   void onFinalizeSwitch(unsigned JumpTableSize,
103699f00635SJacob Hegna                         unsigned NumCaseCluster) override {
103799f00635SJacob Hegna 
103899f00635SJacob Hegna     if (JumpTableSize) {
103999f00635SJacob Hegna       int64_t JTCost =
104099f00635SJacob Hegna           static_cast<int64_t>(JumpTableSize) * InlineConstants::InstrCost +
104199f00635SJacob Hegna           JTCostMultiplier * InlineConstants::InstrCost;
104299f00635SJacob Hegna       increment(InlineCostFeatureIndex::JumpTablePenalty, JTCost);
104399f00635SJacob Hegna       return;
104499f00635SJacob Hegna     }
104599f00635SJacob Hegna 
104699f00635SJacob Hegna     if (NumCaseCluster <= 3) {
104799f00635SJacob Hegna       increment(InlineCostFeatureIndex::CaseClusterPenalty,
104899f00635SJacob Hegna                 NumCaseCluster * CaseClusterCostMultiplier *
104999f00635SJacob Hegna                     InlineConstants::InstrCost);
105099f00635SJacob Hegna       return;
105199f00635SJacob Hegna     }
105299f00635SJacob Hegna 
105399f00635SJacob Hegna     int64_t ExpectedNumberOfCompare =
105499f00635SJacob Hegna         getExpectedNumberOfCompare(NumCaseCluster);
105599f00635SJacob Hegna 
105699f00635SJacob Hegna     int64_t SwitchCost = ExpectedNumberOfCompare * SwitchCostMultiplier *
105799f00635SJacob Hegna                          InlineConstants::InstrCost;
105899f00635SJacob Hegna     increment(InlineCostFeatureIndex::SwitchPenalty, SwitchCost);
105999f00635SJacob Hegna   }
106099f00635SJacob Hegna 
106199f00635SJacob Hegna   void onMissedSimplification() override {
106299f00635SJacob Hegna     increment(InlineCostFeatureIndex::UnsimplifiedCommonInstructions,
106399f00635SJacob Hegna               InlineConstants::InstrCost);
106499f00635SJacob Hegna   }
106599f00635SJacob Hegna 
106699f00635SJacob Hegna   void onInitializeSROAArg(AllocaInst *Arg) override { SROACosts[Arg] = 0; }
106799f00635SJacob Hegna   void onAggregateSROAUse(AllocaInst *Arg) override {
106899f00635SJacob Hegna     SROACosts.find(Arg)->second += InlineConstants::InstrCost;
106999f00635SJacob Hegna     SROACostSavingOpportunities += InlineConstants::InstrCost;
107099f00635SJacob Hegna   }
107199f00635SJacob Hegna 
107299f00635SJacob Hegna   void onBlockAnalyzed(const BasicBlock *BB) override {
107399f00635SJacob Hegna     if (BB->getTerminator()->getNumSuccessors() > 1)
107499f00635SJacob Hegna       set(InlineCostFeatureIndex::IsMultipleBlocks, 1);
107599f00635SJacob Hegna     Threshold -= SingleBBBonus;
107699f00635SJacob Hegna   }
107799f00635SJacob Hegna 
107899f00635SJacob Hegna   InlineResult finalizeAnalysis() override {
107999f00635SJacob Hegna     auto *Caller = CandidateCall.getFunction();
108099f00635SJacob Hegna     if (Caller->hasMinSize()) {
108199f00635SJacob Hegna       DominatorTree DT(F);
108299f00635SJacob Hegna       LoopInfo LI(DT);
108399f00635SJacob Hegna       for (Loop *L : LI) {
108499f00635SJacob Hegna         // Ignore loops that will not be executed
108599f00635SJacob Hegna         if (DeadBlocks.count(L->getHeader()))
108699f00635SJacob Hegna           continue;
108799f00635SJacob Hegna         increment(InlineCostFeatureIndex::NumLoops,
108899f00635SJacob Hegna                   InlineConstants::CallPenalty);
108999f00635SJacob Hegna       }
109099f00635SJacob Hegna     }
109199f00635SJacob Hegna     set(InlineCostFeatureIndex::DeadBlocks, DeadBlocks.size());
109299f00635SJacob Hegna     set(InlineCostFeatureIndex::SimplifiedInstructions,
109399f00635SJacob Hegna         NumInstructionsSimplified);
109499f00635SJacob Hegna     set(InlineCostFeatureIndex::ConstantArgs, NumConstantArgs);
109599f00635SJacob Hegna     set(InlineCostFeatureIndex::ConstantOffsetPtrArgs,
109699f00635SJacob Hegna         NumConstantOffsetPtrArgs);
109799f00635SJacob Hegna     set(InlineCostFeatureIndex::SROASavings, SROACostSavingOpportunities);
109899f00635SJacob Hegna 
109999f00635SJacob Hegna     if (NumVectorInstructions <= NumInstructions / 10)
110099f00635SJacob Hegna       increment(InlineCostFeatureIndex::Threshold, -1 * VectorBonus);
110199f00635SJacob Hegna     else if (NumVectorInstructions <= NumInstructions / 2)
110299f00635SJacob Hegna       increment(InlineCostFeatureIndex::Threshold, -1 * (VectorBonus / 2));
110399f00635SJacob Hegna 
110499f00635SJacob Hegna     set(InlineCostFeatureIndex::Threshold, Threshold);
110599f00635SJacob Hegna 
110699f00635SJacob Hegna     return InlineResult::success();
110799f00635SJacob Hegna   }
110899f00635SJacob Hegna 
110999f00635SJacob Hegna   bool shouldStop() override { return false; }
111099f00635SJacob Hegna 
111199f00635SJacob Hegna   void onLoadEliminationOpportunity() override {
111299f00635SJacob Hegna     increment(InlineCostFeatureIndex::LoadElimination, 1);
111399f00635SJacob Hegna   }
111499f00635SJacob Hegna 
111599f00635SJacob Hegna   InlineResult onAnalysisStart() override {
111699f00635SJacob Hegna     increment(InlineCostFeatureIndex::CallSiteCost,
111799f00635SJacob Hegna               -1 * getCallsiteCost(this->CandidateCall, DL));
111899f00635SJacob Hegna 
111999f00635SJacob Hegna     set(InlineCostFeatureIndex::ColdCcPenalty,
112099f00635SJacob Hegna         (F.getCallingConv() == CallingConv::Cold));
112199f00635SJacob Hegna 
112299f00635SJacob Hegna     // FIXME: we shouldn't repeat this logic in both the Features and Cost
112399f00635SJacob Hegna     // analyzer - instead, we should abstract it to a common method in the
112499f00635SJacob Hegna     // CallAnalyzer
112599f00635SJacob Hegna     int SingleBBBonusPercent = 50;
112699f00635SJacob Hegna     int VectorBonusPercent = TTI.getInlinerVectorBonusPercent();
112799f00635SJacob Hegna     Threshold += TTI.adjustInliningThreshold(&CandidateCall);
112899f00635SJacob Hegna     Threshold *= TTI.getInliningThresholdMultiplier();
112999f00635SJacob Hegna     SingleBBBonus = Threshold * SingleBBBonusPercent / 100;
113099f00635SJacob Hegna     VectorBonus = Threshold * VectorBonusPercent / 100;
113199f00635SJacob Hegna     Threshold += (SingleBBBonus + VectorBonus);
113299f00635SJacob Hegna 
113399f00635SJacob Hegna     return InlineResult::success();
113499f00635SJacob Hegna   }
113599f00635SJacob Hegna 
113699f00635SJacob Hegna public:
113799f00635SJacob Hegna   InlineCostFeaturesAnalyzer(
113899f00635SJacob Hegna       const TargetTransformInfo &TTI,
113999f00635SJacob Hegna       function_ref<AssumptionCache &(Function &)> &GetAssumptionCache,
114099f00635SJacob Hegna       function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
114199f00635SJacob Hegna       ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE, Function &Callee,
114299f00635SJacob Hegna       CallBase &Call)
114399f00635SJacob Hegna       : CallAnalyzer(Callee, Call, TTI, GetAssumptionCache, GetBFI, PSI) {}
114499f00635SJacob Hegna 
114599f00635SJacob Hegna   const InlineCostFeatures &features() const { return Cost; }
114699f00635SJacob Hegna };
114799f00635SJacob Hegna 
11487adc3a2bSChandler Carruth } // namespace
11497adc3a2bSChandler Carruth 
11505f8f34e4SAdrian Prantl /// Test whether the given value is an Alloca-derived function argument.
11517adc3a2bSChandler Carruth bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
11527adc3a2bSChandler Carruth   return SROAArgValues.count(V);
11537adc3a2bSChandler Carruth }
11547adc3a2bSChandler Carruth 
115506408758SMircea Trofin void CallAnalyzer::disableSROAForArg(AllocaInst *SROAArg) {
115606408758SMircea Trofin   onDisableSROA(SROAArg);
11572e42cc7aSMircea Trofin   EnabledSROAAllocas.erase(SROAArg);
1158338a6016SMircea Trofin   disableLoadElimination();
1159338a6016SMircea Trofin }
1160c965fd94SKirill Naumov 
11617b639f50SJacob Hegna void InlineCostAnnotationWriter::emitInstructionAnnot(
11627b639f50SJacob Hegna     const Instruction *I, formatted_raw_ostream &OS) {
1163c965fd94SKirill Naumov   // The cost of inlining of the given instruction is printed always.
1164c965fd94SKirill Naumov   // The threshold delta is printed only when it is non-zero. It happens
1165c965fd94SKirill Naumov   // when we decided to give a bonus at a particular instruction.
11661022b5ebSKirill Naumov   Optional<InstructionCostDetail> Record = ICCA->getCostDetails(I);
11671022b5ebSKirill Naumov   if (!Record)
11681022b5ebSKirill Naumov     OS << "; No analysis for the instruction";
11691022b5ebSKirill Naumov   else {
11701022b5ebSKirill Naumov     OS << "; cost before = " << Record->CostBefore
11711022b5ebSKirill Naumov        << ", cost after = " << Record->CostAfter
11721022b5ebSKirill Naumov        << ", threshold before = " << Record->ThresholdBefore
11731022b5ebSKirill Naumov        << ", threshold after = " << Record->ThresholdAfter << ", ";
11741022b5ebSKirill Naumov     OS << "cost delta = " << Record->getCostDelta();
11751022b5ebSKirill Naumov     if (Record->hasThresholdChanged())
11761022b5ebSKirill Naumov       OS << ", threshold delta = " << Record->getThresholdDelta();
11770383253cSKirill Naumov   }
11787f094f7fSKirill Naumov   auto C = ICCA->getSimplifiedValue(const_cast<Instruction *>(I));
11797f094f7fSKirill Naumov   if (C) {
11807f094f7fSKirill Naumov     OS << ", simplified to ";
11817f094f7fSKirill Naumov     C.getValue()->print(OS, true);
11827f094f7fSKirill Naumov   }
1183c965fd94SKirill Naumov   OS << "\n";
1184c965fd94SKirill Naumov }
1185c965fd94SKirill Naumov 
11865f8f34e4SAdrian Prantl /// If 'V' maps to a SROA candidate, disable SROA for it.
11877adc3a2bSChandler Carruth void CallAnalyzer::disableSROA(Value *V) {
118806408758SMircea Trofin   if (auto *SROAArg = getSROAArgForValueOrNull(V)) {
118906408758SMircea Trofin     disableSROAForArg(SROAArg);
1190338a6016SMircea Trofin   }
11917adc3a2bSChandler Carruth }
11927adc3a2bSChandler Carruth 
1193a4461515SHaicheng Wu void CallAnalyzer::disableLoadElimination() {
1194a4461515SHaicheng Wu   if (EnableLoadElimination) {
119506408758SMircea Trofin     onDisableLoadElimination();
1196a4461515SHaicheng Wu     EnableLoadElimination = false;
1197a4461515SHaicheng Wu   }
1198a4461515SHaicheng Wu }
1199a4461515SHaicheng Wu 
12005f8f34e4SAdrian Prantl /// Accumulate a constant GEP offset into an APInt if possible.
12017adc3a2bSChandler Carruth ///
12027adc3a2bSChandler Carruth /// Returns false if unable to compute the offset for any reason. Respects any
12037adc3a2bSChandler Carruth /// simplified values known during the analysis of this callsite.
12047adc3a2bSChandler Carruth bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
1205945b7e5aSElena Demikhovsky   unsigned IntPtrWidth = DL.getIndexTypeSizeInBits(GEP.getType());
12067adc3a2bSChandler Carruth   assert(IntPtrWidth == Offset.getBitWidth());
12077adc3a2bSChandler Carruth 
12087adc3a2bSChandler Carruth   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
12097adc3a2bSChandler Carruth        GTI != GTE; ++GTI) {
12107adc3a2bSChandler Carruth     ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
12117adc3a2bSChandler Carruth     if (!OpC)
12127adc3a2bSChandler Carruth       if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
12137adc3a2bSChandler Carruth         OpC = dyn_cast<ConstantInt>(SimpleOp);
12147adc3a2bSChandler Carruth     if (!OpC)
12157adc3a2bSChandler Carruth       return false;
1216567556aaSChad Rosier     if (OpC->isZero())
1217567556aaSChad Rosier       continue;
12187adc3a2bSChandler Carruth 
12197adc3a2bSChandler Carruth     // Handle a struct index, which adds its field offset to the pointer.
1220ab85225bSPeter Collingbourne     if (StructType *STy = GTI.getStructTypeOrNull()) {
12217adc3a2bSChandler Carruth       unsigned ElementIdx = OpC->getZExtValue();
12227adc3a2bSChandler Carruth       const StructLayout *SL = DL.getStructLayout(STy);
12237adc3a2bSChandler Carruth       Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
12247adc3a2bSChandler Carruth       continue;
12257adc3a2bSChandler Carruth     }
12267adc3a2bSChandler Carruth 
12277adc3a2bSChandler Carruth     APInt TypeSize(IntPtrWidth, DL.getTypeAllocSize(GTI.getIndexedType()));
12287adc3a2bSChandler Carruth     Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
12297adc3a2bSChandler Carruth   }
12307adc3a2bSChandler Carruth   return true;
12317adc3a2bSChandler Carruth }
12327adc3a2bSChandler Carruth 
12335f8f34e4SAdrian Prantl /// Use TTI to check whether a GEP is free.
1234201b191bSHaicheng Wu ///
1235201b191bSHaicheng Wu /// Respects any simplified values known during the analysis of this callsite.
1236201b191bSHaicheng Wu bool CallAnalyzer::isGEPFree(GetElementPtrInst &GEP) {
123761c1bd5aSEvgeny Astigeevich   SmallVector<Value *, 4> Operands;
123861c1bd5aSEvgeny Astigeevich   Operands.push_back(GEP.getOperand(0));
123991aff1d8SNick Desaulniers   for (const Use &Op : GEP.indices())
124091aff1d8SNick Desaulniers     if (Constant *SimpleOp = SimplifiedValues.lookup(Op))
124161c1bd5aSEvgeny Astigeevich       Operands.push_back(SimpleOp);
1242201b191bSHaicheng Wu     else
124391aff1d8SNick Desaulniers       Operands.push_back(Op);
12443ccbd4f3SSander de Smalen   return TTI.getUserCost(&GEP, Operands,
12453ccbd4f3SSander de Smalen                          TargetTransformInfo::TCK_SizeAndLatency) ==
12463ccbd4f3SSander de Smalen          TargetTransformInfo::TCC_Free;
1247201b191bSHaicheng Wu }
1248201b191bSHaicheng Wu 
12497adc3a2bSChandler Carruth bool CallAnalyzer::visitAlloca(AllocaInst &I) {
1250a3a798d4SArthur Eubanks   disableSROA(I.getOperand(0));
1251a3a798d4SArthur Eubanks 
12527adc3a2bSChandler Carruth   // Check whether inlining will turn a dynamic alloca into a static
12530f153424SSanjay Patel   // alloca and handle that case.
12547adc3a2bSChandler Carruth   if (I.isArrayAllocation()) {
12550f153424SSanjay Patel     Constant *Size = SimplifiedValues.lookup(I.getArraySize());
12560f153424SSanjay Patel     if (auto *AllocSize = dyn_cast_or_null<ConstantInt>(Size)) {
1257090c108dSAmara Emerson       // Sometimes a dynamic alloca could be converted into a static alloca
1258090c108dSAmara Emerson       // after this constant prop, and become a huge static alloca on an
1259090c108dSAmara Emerson       // unconditional CFG path. Avoid inlining if this is going to happen above
1260090c108dSAmara Emerson       // a threshold.
1261090c108dSAmara Emerson       // FIXME: If the threshold is removed or lowered too much, we could end up
1262090c108dSAmara Emerson       // being too pessimistic and prevent inlining non-problematic code. This
1263090c108dSAmara Emerson       // could result in unintended perf regressions. A better overall strategy
1264090c108dSAmara Emerson       // is needed to track stack usage during inlining.
12657adc3a2bSChandler Carruth       Type *Ty = I.getAllocatedType();
126622eb80a1SEaswaran Raman       AllocatedSize = SaturatingMultiplyAdd(
12677b639f50SJacob Hegna           AllocSize->getLimitedValue(),
12687b639f50SJacob Hegna           DL.getTypeAllocSize(Ty).getKnownMinSize(), AllocatedSize);
1269a3a798d4SArthur Eubanks       if (AllocatedSize > InlineConstants::MaxSimplifiedDynamicAllocaToInline)
1270090c108dSAmara Emerson         HasDynamicAlloca = true;
1271090c108dSAmara Emerson       return false;
1272090c108dSAmara Emerson     }
12737adc3a2bSChandler Carruth   }
12747adc3a2bSChandler Carruth 
12757adc3a2bSChandler Carruth   // Accumulate the allocated size.
12767adc3a2bSChandler Carruth   if (I.isStaticAlloca()) {
12777adc3a2bSChandler Carruth     Type *Ty = I.getAllocatedType();
12785a956c85SMircea Trofin     AllocatedSize =
12792ccde3c9SCullen Rhodes         SaturatingAdd(DL.getTypeAllocSize(Ty).getKnownMinSize(), AllocatedSize);
12807adc3a2bSChandler Carruth   }
12817adc3a2bSChandler Carruth 
12827adc3a2bSChandler Carruth   // FIXME: This is overly conservative. Dynamic allocas are inefficient for
12837adc3a2bSChandler Carruth   // a variety of reasons, and so we would like to not inline them into
12847adc3a2bSChandler Carruth   // functions which don't currently have a dynamic alloca. This simply
12857adc3a2bSChandler Carruth   // disables inlining altogether in the presence of a dynamic alloca.
1286a3a798d4SArthur Eubanks   if (!I.isStaticAlloca())
12877adc3a2bSChandler Carruth     HasDynamicAlloca = true;
1288a3a798d4SArthur Eubanks 
12897adc3a2bSChandler Carruth   return false;
12907adc3a2bSChandler Carruth }
12917adc3a2bSChandler Carruth 
12927adc3a2bSChandler Carruth bool CallAnalyzer::visitPHI(PHINode &I) {
12937adc3a2bSChandler Carruth   // FIXME: We need to propagate SROA *disabling* through phi nodes, even
12947adc3a2bSChandler Carruth   // though we don't want to propagate it's bonuses. The idea is to disable
12957adc3a2bSChandler Carruth   // SROA if it *might* be used in an inappropriate manner.
12967adc3a2bSChandler Carruth 
12977adc3a2bSChandler Carruth   // Phi nodes are always zero-cost.
129877f32994SBjorn Pettersson   // FIXME: Pointer sizes may differ between different address spaces, so do we
129977f32994SBjorn Pettersson   // need to use correct address space in the call to getPointerSizeInBits here?
130077f32994SBjorn Pettersson   // Or could we skip the getPointerSizeInBits call completely? As far as I can
130177f32994SBjorn Pettersson   // see the ZeroOffset is used as a dummy value, so we can probably use any
130277f32994SBjorn Pettersson   // bit width for the ZeroOffset?
130377f32994SBjorn Pettersson   APInt ZeroOffset = APInt::getNullValue(DL.getPointerSizeInBits(0));
13043739e14aSHaicheng Wu   bool CheckSROA = I.getType()->isPointerTy();
13053739e14aSHaicheng Wu 
13063739e14aSHaicheng Wu   // Track the constant or pointer with constant offset we've seen so far.
13073739e14aSHaicheng Wu   Constant *FirstC = nullptr;
13083739e14aSHaicheng Wu   std::pair<Value *, APInt> FirstBaseAndOffset = {nullptr, ZeroOffset};
13093739e14aSHaicheng Wu   Value *FirstV = nullptr;
13103739e14aSHaicheng Wu 
13113739e14aSHaicheng Wu   for (unsigned i = 0, e = I.getNumIncomingValues(); i != e; ++i) {
13123739e14aSHaicheng Wu     BasicBlock *Pred = I.getIncomingBlock(i);
13133739e14aSHaicheng Wu     // If the incoming block is dead, skip the incoming block.
13143739e14aSHaicheng Wu     if (DeadBlocks.count(Pred))
13153739e14aSHaicheng Wu       continue;
13163739e14aSHaicheng Wu     // If the parent block of phi is not the known successor of the incoming
13173739e14aSHaicheng Wu     // block, skip the incoming block.
13183739e14aSHaicheng Wu     BasicBlock *KnownSuccessor = KnownSuccessors[Pred];
13193739e14aSHaicheng Wu     if (KnownSuccessor && KnownSuccessor != I.getParent())
13203739e14aSHaicheng Wu       continue;
13213739e14aSHaicheng Wu 
13223739e14aSHaicheng Wu     Value *V = I.getIncomingValue(i);
13233739e14aSHaicheng Wu     // If the incoming value is this phi itself, skip the incoming value.
13243739e14aSHaicheng Wu     if (&I == V)
13253739e14aSHaicheng Wu       continue;
13263739e14aSHaicheng Wu 
13273739e14aSHaicheng Wu     Constant *C = dyn_cast<Constant>(V);
13283739e14aSHaicheng Wu     if (!C)
13293739e14aSHaicheng Wu       C = SimplifiedValues.lookup(V);
13303739e14aSHaicheng Wu 
13313739e14aSHaicheng Wu     std::pair<Value *, APInt> BaseAndOffset = {nullptr, ZeroOffset};
13323739e14aSHaicheng Wu     if (!C && CheckSROA)
13333739e14aSHaicheng Wu       BaseAndOffset = ConstantOffsetPtrs.lookup(V);
13343739e14aSHaicheng Wu 
13353739e14aSHaicheng Wu     if (!C && !BaseAndOffset.first)
13363739e14aSHaicheng Wu       // The incoming value is neither a constant nor a pointer with constant
13373739e14aSHaicheng Wu       // offset, exit early.
13383739e14aSHaicheng Wu       return true;
13393739e14aSHaicheng Wu 
13403739e14aSHaicheng Wu     if (FirstC) {
13413739e14aSHaicheng Wu       if (FirstC == C)
13423739e14aSHaicheng Wu         // If we've seen a constant incoming value before and it is the same
13433739e14aSHaicheng Wu         // constant we see this time, continue checking the next incoming value.
13443739e14aSHaicheng Wu         continue;
13453739e14aSHaicheng Wu       // Otherwise early exit because we either see a different constant or saw
13463739e14aSHaicheng Wu       // a constant before but we have a pointer with constant offset this time.
13473739e14aSHaicheng Wu       return true;
13483739e14aSHaicheng Wu     }
13493739e14aSHaicheng Wu 
13503739e14aSHaicheng Wu     if (FirstV) {
13513739e14aSHaicheng Wu       // The same logic as above, but check pointer with constant offset here.
13523739e14aSHaicheng Wu       if (FirstBaseAndOffset == BaseAndOffset)
13533739e14aSHaicheng Wu         continue;
13543739e14aSHaicheng Wu       return true;
13553739e14aSHaicheng Wu     }
13563739e14aSHaicheng Wu 
13573739e14aSHaicheng Wu     if (C) {
13583739e14aSHaicheng Wu       // This is the 1st time we've seen a constant, record it.
13593739e14aSHaicheng Wu       FirstC = C;
13603739e14aSHaicheng Wu       continue;
13613739e14aSHaicheng Wu     }
13623739e14aSHaicheng Wu 
13633739e14aSHaicheng Wu     // The remaining case is that this is the 1st time we've seen a pointer with
13643739e14aSHaicheng Wu     // constant offset, record it.
13653739e14aSHaicheng Wu     FirstV = V;
13663739e14aSHaicheng Wu     FirstBaseAndOffset = BaseAndOffset;
13673739e14aSHaicheng Wu   }
13683739e14aSHaicheng Wu 
13693739e14aSHaicheng Wu   // Check if we can map phi to a constant.
13703739e14aSHaicheng Wu   if (FirstC) {
13713739e14aSHaicheng Wu     SimplifiedValues[&I] = FirstC;
13723739e14aSHaicheng Wu     return true;
13733739e14aSHaicheng Wu   }
13743739e14aSHaicheng Wu 
13753739e14aSHaicheng Wu   // Check if we can map phi to a pointer with constant offset.
13763739e14aSHaicheng Wu   if (FirstBaseAndOffset.first) {
13773739e14aSHaicheng Wu     ConstantOffsetPtrs[&I] = FirstBaseAndOffset;
13783739e14aSHaicheng Wu 
137906408758SMircea Trofin     if (auto *SROAArg = getSROAArgForValueOrNull(FirstV))
13803739e14aSHaicheng Wu       SROAArgValues[&I] = SROAArg;
13813739e14aSHaicheng Wu   }
13823739e14aSHaicheng Wu 
13837adc3a2bSChandler Carruth   return true;
13847adc3a2bSChandler Carruth }
13857adc3a2bSChandler Carruth 
13865f8f34e4SAdrian Prantl /// Check we can fold GEPs of constant-offset call site argument pointers.
1387d3558b5dSEvgeny Astigeevich /// This requires target data and inbounds GEPs.
1388d3558b5dSEvgeny Astigeevich ///
1389d3558b5dSEvgeny Astigeevich /// \return true if the specified GEP can be folded.
1390d3558b5dSEvgeny Astigeevich bool CallAnalyzer::canFoldInboundsGEP(GetElementPtrInst &I) {
1391d3558b5dSEvgeny Astigeevich   // Check if we have a base + offset for the pointer.
1392d3558b5dSEvgeny Astigeevich   std::pair<Value *, APInt> BaseAndOffset =
1393d3558b5dSEvgeny Astigeevich       ConstantOffsetPtrs.lookup(I.getPointerOperand());
1394d3558b5dSEvgeny Astigeevich   if (!BaseAndOffset.first)
1395d3558b5dSEvgeny Astigeevich     return false;
1396d3558b5dSEvgeny Astigeevich 
1397d3558b5dSEvgeny Astigeevich   // Check if the offset of this GEP is constant, and if so accumulate it
1398d3558b5dSEvgeny Astigeevich   // into Offset.
1399d3558b5dSEvgeny Astigeevich   if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second))
1400d3558b5dSEvgeny Astigeevich     return false;
1401d3558b5dSEvgeny Astigeevich 
1402d3558b5dSEvgeny Astigeevich   // Add the result as a new mapping to Base + Offset.
1403d3558b5dSEvgeny Astigeevich   ConstantOffsetPtrs[&I] = BaseAndOffset;
1404d3558b5dSEvgeny Astigeevich 
1405d3558b5dSEvgeny Astigeevich   return true;
1406d3558b5dSEvgeny Astigeevich }
1407d3558b5dSEvgeny Astigeevich 
14087adc3a2bSChandler Carruth bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
140906408758SMircea Trofin   auto *SROAArg = getSROAArgForValueOrNull(I.getPointerOperand());
14107adc3a2bSChandler Carruth 
1411a8b9cdc9SEaswaran Raman   // Lambda to check whether a GEP's indices are all constant.
1412a8b9cdc9SEaswaran Raman   auto IsGEPOffsetConstant = [&](GetElementPtrInst &GEP) {
141391aff1d8SNick Desaulniers     for (const Use &Op : GEP.indices())
141491aff1d8SNick Desaulniers       if (!isa<Constant>(Op) && !SimplifiedValues.lookup(Op))
1415a8b9cdc9SEaswaran Raman         return false;
1416a8b9cdc9SEaswaran Raman     return true;
1417a8b9cdc9SEaswaran Raman   };
1418a8b9cdc9SEaswaran Raman 
1419d48c7859SKirill Naumov   if (!DisableGEPConstOperand)
1420d48c7859SKirill Naumov     if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1421d48c7859SKirill Naumov           SmallVector<Constant *, 2> Indices;
1422d48c7859SKirill Naumov           for (unsigned int Index = 1; Index < COps.size(); ++Index)
1423d48c7859SKirill Naumov             Indices.push_back(COps[Index]);
14247b639f50SJacob Hegna           return ConstantExpr::getGetElementPtr(
14257b639f50SJacob Hegna               I.getSourceElementType(), COps[0], Indices, I.isInBounds());
1426d48c7859SKirill Naumov         }))
1427d48c7859SKirill Naumov       return true;
1428d48c7859SKirill Naumov 
1429d3558b5dSEvgeny Astigeevich   if ((I.isInBounds() && canFoldInboundsGEP(I)) || IsGEPOffsetConstant(I)) {
143006408758SMircea Trofin     if (SROAArg)
14317adc3a2bSChandler Carruth       SROAArgValues[&I] = SROAArg;
14327adc3a2bSChandler Carruth 
14337adc3a2bSChandler Carruth     // Constant GEPs are modeled as free.
14347adc3a2bSChandler Carruth     return true;
14357adc3a2bSChandler Carruth   }
14367adc3a2bSChandler Carruth 
14377adc3a2bSChandler Carruth   // Variable GEPs will require math and will disable SROA.
143806408758SMircea Trofin   if (SROAArg)
143906408758SMircea Trofin     disableSROAForArg(SROAArg);
1440201b191bSHaicheng Wu   return isGEPFree(I);
14417adc3a2bSChandler Carruth }
14427adc3a2bSChandler Carruth 
1443617f6364SEaswaran Raman /// Simplify \p I if its operands are constants and update SimplifiedValues.
1444617f6364SEaswaran Raman /// \p Evaluate is a callable specific to instruction type that evaluates the
1445617f6364SEaswaran Raman /// instruction when all the operands are constants.
1446617f6364SEaswaran Raman template <typename Callable>
1447617f6364SEaswaran Raman bool CallAnalyzer::simplifyInstruction(Instruction &I, Callable Evaluate) {
1448617f6364SEaswaran Raman   SmallVector<Constant *, 2> COps;
1449617f6364SEaswaran Raman   for (Value *Op : I.operands()) {
1450617f6364SEaswaran Raman     Constant *COp = dyn_cast<Constant>(Op);
14517adc3a2bSChandler Carruth     if (!COp)
1452617f6364SEaswaran Raman       COp = SimplifiedValues.lookup(Op);
1453617f6364SEaswaran Raman     if (!COp)
1454617f6364SEaswaran Raman       return false;
1455617f6364SEaswaran Raman     COps.push_back(COp);
1456617f6364SEaswaran Raman   }
1457617f6364SEaswaran Raman   auto *C = Evaluate(COps);
1458617f6364SEaswaran Raman   if (!C)
1459617f6364SEaswaran Raman     return false;
14607adc3a2bSChandler Carruth   SimplifiedValues[&I] = C;
14617adc3a2bSChandler Carruth   return true;
14627adc3a2bSChandler Carruth }
14637adc3a2bSChandler Carruth 
1464617f6364SEaswaran Raman bool CallAnalyzer::visitBitCast(BitCastInst &I) {
1465617f6364SEaswaran Raman   // Propagate constants through bitcasts.
1466617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1467617f6364SEaswaran Raman         return ConstantExpr::getBitCast(COps[0], I.getType());
1468617f6364SEaswaran Raman       }))
1469617f6364SEaswaran Raman     return true;
1470617f6364SEaswaran Raman 
14717adc3a2bSChandler Carruth   // Track base/offsets through casts
1472567556aaSChad Rosier   std::pair<Value *, APInt> BaseAndOffset =
1473567556aaSChad Rosier       ConstantOffsetPtrs.lookup(I.getOperand(0));
14747adc3a2bSChandler Carruth   // Casts don't change the offset, just wrap it up.
14757adc3a2bSChandler Carruth   if (BaseAndOffset.first)
14767adc3a2bSChandler Carruth     ConstantOffsetPtrs[&I] = BaseAndOffset;
14777adc3a2bSChandler Carruth 
14787adc3a2bSChandler Carruth   // Also look for SROA candidates here.
147906408758SMircea Trofin   if (auto *SROAArg = getSROAArgForValueOrNull(I.getOperand(0)))
14807adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
14817adc3a2bSChandler Carruth 
14827adc3a2bSChandler Carruth   // Bitcasts are always zero cost.
14837adc3a2bSChandler Carruth   return true;
14847adc3a2bSChandler Carruth }
14857adc3a2bSChandler Carruth 
14867adc3a2bSChandler Carruth bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
14877adc3a2bSChandler Carruth   // Propagate constants through ptrtoint.
1488617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1489617f6364SEaswaran Raman         return ConstantExpr::getPtrToInt(COps[0], I.getType());
1490617f6364SEaswaran Raman       }))
14917adc3a2bSChandler Carruth     return true;
14927adc3a2bSChandler Carruth 
14937adc3a2bSChandler Carruth   // Track base/offset pairs when converted to a plain integer provided the
14947adc3a2bSChandler Carruth   // integer is large enough to represent the pointer.
14957adc3a2bSChandler Carruth   unsigned IntegerSize = I.getType()->getScalarSizeInBits();
149677f32994SBjorn Pettersson   unsigned AS = I.getOperand(0)->getType()->getPointerAddressSpace();
1497faf848acSMikael Holmen   if (IntegerSize == DL.getPointerSizeInBits(AS)) {
1498567556aaSChad Rosier     std::pair<Value *, APInt> BaseAndOffset =
1499567556aaSChad Rosier         ConstantOffsetPtrs.lookup(I.getOperand(0));
15007adc3a2bSChandler Carruth     if (BaseAndOffset.first)
15017adc3a2bSChandler Carruth       ConstantOffsetPtrs[&I] = BaseAndOffset;
15027adc3a2bSChandler Carruth   }
15037adc3a2bSChandler Carruth 
15047adc3a2bSChandler Carruth   // This is really weird. Technically, ptrtoint will disable SROA. However,
15057adc3a2bSChandler Carruth   // unless that ptrtoint is *used* somewhere in the live basic blocks after
15067adc3a2bSChandler Carruth   // inlining, it will be nuked, and SROA should proceed. All of the uses which
15077adc3a2bSChandler Carruth   // would block SROA would also block SROA if applied directly to a pointer,
15087adc3a2bSChandler Carruth   // and so we can just add the integer in here. The only places where SROA is
15097adc3a2bSChandler Carruth   // preserved either cannot fire on an integer, or won't in-and-of themselves
15107adc3a2bSChandler Carruth   // disable SROA (ext) w/o some later use that we would see and disable.
151106408758SMircea Trofin   if (auto *SROAArg = getSROAArgForValueOrNull(I.getOperand(0)))
15127adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
15137adc3a2bSChandler Carruth 
15143ccbd4f3SSander de Smalen   return TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency) ==
15153ccbd4f3SSander de Smalen          TargetTransformInfo::TCC_Free;
15167adc3a2bSChandler Carruth }
15177adc3a2bSChandler Carruth 
15187adc3a2bSChandler Carruth bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
15197adc3a2bSChandler Carruth   // Propagate constants through ptrtoint.
1520617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1521617f6364SEaswaran Raman         return ConstantExpr::getIntToPtr(COps[0], I.getType());
1522617f6364SEaswaran Raman       }))
15237adc3a2bSChandler Carruth     return true;
15247adc3a2bSChandler Carruth 
15257adc3a2bSChandler Carruth   // Track base/offset pairs when round-tripped through a pointer without
15267adc3a2bSChandler Carruth   // modifications provided the integer is not too large.
15277adc3a2bSChandler Carruth   Value *Op = I.getOperand(0);
15287adc3a2bSChandler Carruth   unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
152977f32994SBjorn Pettersson   if (IntegerSize <= DL.getPointerTypeSizeInBits(I.getType())) {
15307adc3a2bSChandler Carruth     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
15317adc3a2bSChandler Carruth     if (BaseAndOffset.first)
15327adc3a2bSChandler Carruth       ConstantOffsetPtrs[&I] = BaseAndOffset;
15337adc3a2bSChandler Carruth   }
15347adc3a2bSChandler Carruth 
15357adc3a2bSChandler Carruth   // "Propagate" SROA here in the same manner as we do for ptrtoint above.
153606408758SMircea Trofin   if (auto *SROAArg = getSROAArgForValueOrNull(Op))
15377adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
15387adc3a2bSChandler Carruth 
15393ccbd4f3SSander de Smalen   return TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency) ==
15403ccbd4f3SSander de Smalen          TargetTransformInfo::TCC_Free;
15417adc3a2bSChandler Carruth }
15427adc3a2bSChandler Carruth 
15437adc3a2bSChandler Carruth bool CallAnalyzer::visitCastInst(CastInst &I) {
1544ab53c5e5SCraig Topper   // Propagate constants through casts.
1545617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1546617f6364SEaswaran Raman         return ConstantExpr::getCast(I.getOpcode(), COps[0], I.getType());
1547617f6364SEaswaran Raman       }))
15487adc3a2bSChandler Carruth     return true;
15497adc3a2bSChandler Carruth 
155010563e16SEric Christopher   // Disable SROA in the face of arbitrary casts we don't explicitly list
155110563e16SEric Christopher   // elsewhere.
15527adc3a2bSChandler Carruth   disableSROA(I.getOperand(0));
15537adc3a2bSChandler Carruth 
155439ed9a60SEli Friedman   // If this is a floating-point cast, and the target says this operation
155539ed9a60SEli Friedman   // is expensive, this may eventually become a library call. Treat the cost
155639ed9a60SEli Friedman   // as such.
155739ed9a60SEli Friedman   switch (I.getOpcode()) {
155839ed9a60SEli Friedman   case Instruction::FPTrunc:
155939ed9a60SEli Friedman   case Instruction::FPExt:
156039ed9a60SEli Friedman   case Instruction::UIToFP:
156139ed9a60SEli Friedman   case Instruction::SIToFP:
156239ed9a60SEli Friedman   case Instruction::FPToUI:
156339ed9a60SEli Friedman   case Instruction::FPToSI:
156439ed9a60SEli Friedman     if (TTI.getFPOpCost(I.getType()) == TargetTransformInfo::TCC_Expensive)
156506408758SMircea Trofin       onCallPenalty();
15664dc0b1acSReid Kleckner     break;
156739ed9a60SEli Friedman   default:
156839ed9a60SEli Friedman     break;
156939ed9a60SEli Friedman   }
157039ed9a60SEli Friedman 
15713ccbd4f3SSander de Smalen   return TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency) ==
15723ccbd4f3SSander de Smalen          TargetTransformInfo::TCC_Free;
15737adc3a2bSChandler Carruth }
15747adc3a2bSChandler Carruth 
15757adc3a2bSChandler Carruth bool CallAnalyzer::paramHasAttr(Argument *A, Attribute::AttrKind Attr) {
1576652168a9SFedor Sergeev   return CandidateCall.paramHasAttr(A->getArgNo(), Attr);
15777adc3a2bSChandler Carruth }
15787adc3a2bSChandler Carruth 
15797adc3a2bSChandler Carruth bool CallAnalyzer::isKnownNonNullInCallee(Value *V) {
15807adc3a2bSChandler Carruth   // Does the *call site* have the NonNull attribute set on an argument?  We
15817adc3a2bSChandler Carruth   // use the attribute on the call site to memoize any analysis done in the
15827adc3a2bSChandler Carruth   // caller. This will also trip if the callee function has a non-null
15837adc3a2bSChandler Carruth   // parameter attribute, but that's a less interesting case because hopefully
15847adc3a2bSChandler Carruth   // the callee would already have been simplified based on that.
15857adc3a2bSChandler Carruth   if (Argument *A = dyn_cast<Argument>(V))
15867adc3a2bSChandler Carruth     if (paramHasAttr(A, Attribute::NonNull))
15877adc3a2bSChandler Carruth       return true;
15887adc3a2bSChandler Carruth 
15897adc3a2bSChandler Carruth   // Is this an alloca in the caller?  This is distinct from the attribute case
15907adc3a2bSChandler Carruth   // above because attributes aren't updated within the inliner itself and we
15917adc3a2bSChandler Carruth   // always want to catch the alloca derived case.
15927adc3a2bSChandler Carruth   if (isAllocaDerivedArg(V))
15937adc3a2bSChandler Carruth     // We can actually predict the result of comparisons between an
15947adc3a2bSChandler Carruth     // alloca-derived value and null. Note that this fires regardless of
15957adc3a2bSChandler Carruth     // SROA firing.
15967adc3a2bSChandler Carruth     return true;
15977adc3a2bSChandler Carruth 
15987adc3a2bSChandler Carruth   return false;
15997adc3a2bSChandler Carruth }
16007adc3a2bSChandler Carruth 
1601652168a9SFedor Sergeev bool CallAnalyzer::allowSizeGrowth(CallBase &Call) {
16029a3fc17aSEaswaran Raman   // If the normal destination of the invoke or the parent block of the call
16039a3fc17aSEaswaran Raman   // site is unreachable-terminated, there is little point in inlining this
16049a3fc17aSEaswaran Raman   // unless there is literally zero cost.
16059a3fc17aSEaswaran Raman   // FIXME: Note that it is possible that an unreachable-terminated block has a
16069a3fc17aSEaswaran Raman   // hot entry. For example, in below scenario inlining hot_call_X() may be
16079a3fc17aSEaswaran Raman   // beneficial :
16089a3fc17aSEaswaran Raman   // main() {
16099a3fc17aSEaswaran Raman   //   hot_call_1();
16109a3fc17aSEaswaran Raman   //   ...
16119a3fc17aSEaswaran Raman   //   hot_call_N()
16129a3fc17aSEaswaran Raman   //   exit(0);
16139a3fc17aSEaswaran Raman   // }
16149a3fc17aSEaswaran Raman   // For now, we are not handling this corner case here as it is rare in real
16159a3fc17aSEaswaran Raman   // code. In future, we should elaborate this based on BPI and BFI in more
16169a3fc17aSEaswaran Raman   // general threshold adjusting heuristics in updateThreshold().
1617652168a9SFedor Sergeev   if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
16189a3fc17aSEaswaran Raman     if (isa<UnreachableInst>(II->getNormalDest()->getTerminator()))
16199a3fc17aSEaswaran Raman       return false;
1620652168a9SFedor Sergeev   } else if (isa<UnreachableInst>(Call.getParent()->getTerminator()))
16219a3fc17aSEaswaran Raman     return false;
16229a3fc17aSEaswaran Raman 
16239a3fc17aSEaswaran Raman   return true;
16249a3fc17aSEaswaran Raman }
16259a3fc17aSEaswaran Raman 
162606408758SMircea Trofin bool InlineCostCallAnalyzer::isColdCallSite(CallBase &Call,
1627652168a9SFedor Sergeev                                             BlockFrequencyInfo *CallerBFI) {
1628c5fa6358SEaswaran Raman   // If global profile summary is available, then callsite's coldness is
1629c5fa6358SEaswaran Raman   // determined based on that.
1630bba762a1SChandler Carruth   if (PSI && PSI->hasProfileSummary())
1631ec73ae11SMircea Trofin     return PSI->isColdCallSite(Call, CallerBFI);
1632bba762a1SChandler Carruth 
1633bba762a1SChandler Carruth   // Otherwise we need BFI to be available.
1634c5fa6358SEaswaran Raman   if (!CallerBFI)
1635c5fa6358SEaswaran Raman     return false;
1636c5fa6358SEaswaran Raman 
1637bba762a1SChandler Carruth   // Determine if the callsite is cold relative to caller's entry. We could
1638bba762a1SChandler Carruth   // potentially cache the computation of scaled entry frequency, but the added
1639bba762a1SChandler Carruth   // complexity is not worth it unless this scaling shows up high in the
1640bba762a1SChandler Carruth   // profiles.
1641c5fa6358SEaswaran Raman   const BranchProbability ColdProb(ColdCallSiteRelFreq, 100);
1642652168a9SFedor Sergeev   auto CallSiteBB = Call.getParent();
1643c5fa6358SEaswaran Raman   auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB);
1644c5fa6358SEaswaran Raman   auto CallerEntryFreq =
1645652168a9SFedor Sergeev       CallerBFI->getBlockFreq(&(Call.getCaller()->getEntryBlock()));
1646c5fa6358SEaswaran Raman   return CallSiteFreq < CallerEntryFreq * ColdProb;
1647c5fa6358SEaswaran Raman }
1648c5fa6358SEaswaran Raman 
1649974d4eeaSEaswaran Raman Optional<int>
165006408758SMircea Trofin InlineCostCallAnalyzer::getHotCallSiteThreshold(CallBase &Call,
1651974d4eeaSEaswaran Raman                                                 BlockFrequencyInfo *CallerBFI) {
1652bba762a1SChandler Carruth 
1653974d4eeaSEaswaran Raman   // If global profile summary is available, then callsite's hotness is
1654974d4eeaSEaswaran Raman   // determined based on that.
1655ec73ae11SMircea Trofin   if (PSI && PSI->hasProfileSummary() && PSI->isHotCallSite(Call, CallerBFI))
1656bba762a1SChandler Carruth     return Params.HotCallSiteThreshold;
1657974d4eeaSEaswaran Raman 
1658bba762a1SChandler Carruth   // Otherwise we need BFI to be available and to have a locally hot callsite
1659bba762a1SChandler Carruth   // threshold.
1660bba762a1SChandler Carruth   if (!CallerBFI || !Params.LocallyHotCallSiteThreshold)
1661974d4eeaSEaswaran Raman     return None;
1662974d4eeaSEaswaran Raman 
1663bba762a1SChandler Carruth   // Determine if the callsite is hot relative to caller's entry. We could
1664bba762a1SChandler Carruth   // potentially cache the computation of scaled entry frequency, but the added
1665bba762a1SChandler Carruth   // complexity is not worth it unless this scaling shows up high in the
1666bba762a1SChandler Carruth   // profiles.
1667652168a9SFedor Sergeev   auto CallSiteBB = Call.getParent();
1668974d4eeaSEaswaran Raman   auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB).getFrequency();
1669974d4eeaSEaswaran Raman   auto CallerEntryFreq = CallerBFI->getEntryFreq();
1670974d4eeaSEaswaran Raman   if (CallSiteFreq >= CallerEntryFreq * HotCallSiteRelFreq)
1671bba762a1SChandler Carruth     return Params.LocallyHotCallSiteThreshold;
1672bba762a1SChandler Carruth 
1673bba762a1SChandler Carruth   // Otherwise treat it normally.
1674974d4eeaSEaswaran Raman   return None;
1675974d4eeaSEaswaran Raman }
1676974d4eeaSEaswaran Raman 
167706408758SMircea Trofin void InlineCostCallAnalyzer::updateThreshold(CallBase &Call, Function &Callee) {
16789a3fc17aSEaswaran Raman   // If no size growth is allowed for this inlining, set Threshold to 0.
1679652168a9SFedor Sergeev   if (!allowSizeGrowth(Call)) {
16809a3fc17aSEaswaran Raman     Threshold = 0;
16819a3fc17aSEaswaran Raman     return;
16829a3fc17aSEaswaran Raman   }
16839a3fc17aSEaswaran Raman 
1684652168a9SFedor Sergeev   Function *Caller = Call.getCaller();
16851c57cc2bSEaswaran Raman 
16861c57cc2bSEaswaran Raman   // return min(A, B) if B is valid.
16871c57cc2bSEaswaran Raman   auto MinIfValid = [](int A, Optional<int> B) {
16881c57cc2bSEaswaran Raman     return B ? std::min(A, B.getValue()) : A;
16891c57cc2bSEaswaran Raman   };
16901c57cc2bSEaswaran Raman 
16910d58fcacSEaswaran Raman   // return max(A, B) if B is valid.
16920d58fcacSEaswaran Raman   auto MaxIfValid = [](int A, Optional<int> B) {
16930d58fcacSEaswaran Raman     return B ? std::max(A, B.getValue()) : A;
16940d58fcacSEaswaran Raman   };
16950d58fcacSEaswaran Raman 
169651b809bfSEaswaran Raman   // Various bonus percentages. These are multiplied by Threshold to get the
169751b809bfSEaswaran Raman   // bonus values.
169851b809bfSEaswaran Raman   // SingleBBBonus: This bonus is applied if the callee has a single reachable
169951b809bfSEaswaran Raman   // basic block at the given callsite context. This is speculatively applied
170051b809bfSEaswaran Raman   // and withdrawn if more than one basic block is seen.
170151b809bfSEaswaran Raman   //
170251b809bfSEaswaran Raman   // LstCallToStaticBonus: This large bonus is applied to ensure the inlining
170351b809bfSEaswaran Raman   // of the last call to a static function as inlining such functions is
170451b809bfSEaswaran Raman   // guaranteed to reduce code size.
170551b809bfSEaswaran Raman   //
170651b809bfSEaswaran Raman   // These bonus percentages may be set to 0 based on properties of the caller
170751b809bfSEaswaran Raman   // and the callsite.
170851b809bfSEaswaran Raman   int SingleBBBonusPercent = 50;
1709d912a9baSDaniil Fukalov   int VectorBonusPercent = TTI.getInlinerVectorBonusPercent();
171002647f73SJordan Rupprecht   int LastCallToStaticBonus = InlineConstants::LastCallToStaticBonus;
171151b809bfSEaswaran Raman 
171251b809bfSEaswaran Raman   // Lambda to set all the above bonus and bonus percentages to 0.
171351b809bfSEaswaran Raman   auto DisallowAllBonuses = [&]() {
171451b809bfSEaswaran Raman     SingleBBBonusPercent = 0;
171551b809bfSEaswaran Raman     VectorBonusPercent = 0;
171651b809bfSEaswaran Raman     LastCallToStaticBonus = 0;
171751b809bfSEaswaran Raman   };
171851b809bfSEaswaran Raman 
17191c57cc2bSEaswaran Raman   // Use the OptMinSizeThreshold or OptSizeThreshold knob if they are available
17201c57cc2bSEaswaran Raman   // and reduce the threshold if the caller has the necessary attribute.
172185bd3978SEvandro Menezes   if (Caller->hasMinSize()) {
17221c57cc2bSEaswaran Raman     Threshold = MinIfValid(Threshold, Params.OptMinSizeThreshold);
172351b809bfSEaswaran Raman     // For minsize, we want to disable the single BB bonus and the vector
172451b809bfSEaswaran Raman     // bonuses, but not the last-call-to-static bonus. Inlining the last call to
172551b809bfSEaswaran Raman     // a static function will, at the minimum, eliminate the parameter setup and
172651b809bfSEaswaran Raman     // call/return instructions.
172751b809bfSEaswaran Raman     SingleBBBonusPercent = 0;
172851b809bfSEaswaran Raman     VectorBonusPercent = 0;
172985bd3978SEvandro Menezes   } else if (Caller->hasOptSize())
17301c57cc2bSEaswaran Raman     Threshold = MinIfValid(Threshold, Params.OptSizeThreshold);
1731f4bb2f0dSEaswaran Raman 
1732e08b139dSEaswaran Raman   // Adjust the threshold based on inlinehint attribute and profile based
1733e08b139dSEaswaran Raman   // hotness information if the caller does not have MinSize attribute.
173485bd3978SEvandro Menezes   if (!Caller->hasMinSize()) {
1735e08b139dSEaswaran Raman     if (Callee.hasFnAttribute(Attribute::InlineHint))
17360d58fcacSEaswaran Raman       Threshold = MaxIfValid(Threshold, Params.HintThreshold);
1737bba762a1SChandler Carruth 
17383cd1479cSEaswaran Raman     // FIXME: After switching to the new passmanager, simplify the logic below
1739bba762a1SChandler Carruth     // by checking only the callsite hotness/coldness as we will reliably
1740bba762a1SChandler Carruth     // have local profile information.
17413cd1479cSEaswaran Raman     //
1742bba762a1SChandler Carruth     // Callsite hotness and coldness can be determined if sample profile is
1743bba762a1SChandler Carruth     // used (which adds hotness metadata to calls) or if caller's
1744bba762a1SChandler Carruth     // BlockFrequencyInfo is available.
174508e2386dSMircea Trofin     BlockFrequencyInfo *CallerBFI = GetBFI ? &(GetBFI(*Caller)) : nullptr;
1746652168a9SFedor Sergeev     auto HotCallSiteThreshold = getHotCallSiteThreshold(Call, CallerBFI);
174785bd3978SEvandro Menezes     if (!Caller->hasOptSize() && HotCallSiteThreshold) {
1748d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Hot callsite.\n");
1749974d4eeaSEaswaran Raman       // FIXME: This should update the threshold only if it exceeds the
1750974d4eeaSEaswaran Raman       // current threshold, but AutoFDO + ThinLTO currently relies on this
1751974d4eeaSEaswaran Raman       // behavior to prevent inlining of hot callsites during ThinLTO
1752974d4eeaSEaswaran Raman       // compile phase.
1753974d4eeaSEaswaran Raman       Threshold = HotCallSiteThreshold.getValue();
1754652168a9SFedor Sergeev     } else if (isColdCallSite(Call, CallerBFI)) {
1755d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Cold callsite.\n");
175651b809bfSEaswaran Raman       // Do not apply bonuses for a cold callsite including the
175751b809bfSEaswaran Raman       // LastCallToStatic bonus. While this bonus might result in code size
175851b809bfSEaswaran Raman       // reduction, it can cause the size of a non-cold caller to increase
175951b809bfSEaswaran Raman       // preventing it from being inlined.
176051b809bfSEaswaran Raman       DisallowAllBonuses();
17613cd1479cSEaswaran Raman       Threshold = MinIfValid(Threshold, Params.ColdCallSiteThreshold);
1762bba762a1SChandler Carruth     } else if (PSI) {
1763bba762a1SChandler Carruth       // Use callee's global profile information only if we have no way of
1764bba762a1SChandler Carruth       // determining this via callsite information.
17653cd1479cSEaswaran Raman       if (PSI->isFunctionEntryHot(&Callee)) {
1766d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Hot callee.\n");
1767e08b139dSEaswaran Raman         // If callsite hotness can not be determined, we may still know
1768e08b139dSEaswaran Raman         // that the callee is hot and treat it as a weaker hint for threshold
1769e08b139dSEaswaran Raman         // increase.
1770e08b139dSEaswaran Raman         Threshold = MaxIfValid(Threshold, Params.HintThreshold);
1771e08b139dSEaswaran Raman       } else if (PSI->isFunctionEntryCold(&Callee)) {
1772d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Cold callee.\n");
177351b809bfSEaswaran Raman         // Do not apply bonuses for a cold callee including the
177451b809bfSEaswaran Raman         // LastCallToStatic bonus. While this bonus might result in code size
177551b809bfSEaswaran Raman         // reduction, it can cause the size of a non-cold caller to increase
177651b809bfSEaswaran Raman         // preventing it from being inlined.
177751b809bfSEaswaran Raman         DisallowAllBonuses();
17781c57cc2bSEaswaran Raman         Threshold = MinIfValid(Threshold, Params.ColdThreshold);
1779e08b139dSEaswaran Raman       }
1780e08b139dSEaswaran Raman     }
1781e08b139dSEaswaran Raman   }
17828650a4daSJustin Lebar 
1783b7b99b07SStanislav Mekhanoshin   Threshold += TTI.adjustInliningThreshold(&Call);
1784b7b99b07SStanislav Mekhanoshin 
178502647f73SJordan Rupprecht   // Finally, take the target-specific inlining threshold multiplier into
178602647f73SJordan Rupprecht   // account.
17878650a4daSJustin Lebar   Threshold *= TTI.getInliningThresholdMultiplier();
178851b809bfSEaswaran Raman 
178951b809bfSEaswaran Raman   SingleBBBonus = Threshold * SingleBBBonusPercent / 100;
179051b809bfSEaswaran Raman   VectorBonus = Threshold * VectorBonusPercent / 100;
179151b809bfSEaswaran Raman 
179202647f73SJordan Rupprecht   bool OnlyOneCallAndLocalLinkage =
179302647f73SJordan Rupprecht       F.hasLocalLinkage() && F.hasOneUse() && &F == Call.getCalledFunction();
179402647f73SJordan Rupprecht   // If there is only one call of the function, and it has internal linkage,
179502647f73SJordan Rupprecht   // the cost of inlining it drops dramatically. It may seem odd to update
179602647f73SJordan Rupprecht   // Cost in updateThreshold, but the bonus depends on the logic in this method.
179702647f73SJordan Rupprecht   if (OnlyOneCallAndLocalLinkage)
179802647f73SJordan Rupprecht     Cost -= LastCallToStaticBonus;
1799f4bb2f0dSEaswaran Raman }
1800f4bb2f0dSEaswaran Raman 
18017adc3a2bSChandler Carruth bool CallAnalyzer::visitCmpInst(CmpInst &I) {
18027adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
18037adc3a2bSChandler Carruth   // First try to handle simplified comparisons.
1804617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1805617f6364SEaswaran Raman         return ConstantExpr::getCompare(I.getPredicate(), COps[0], COps[1]);
1806617f6364SEaswaran Raman       }))
18077adc3a2bSChandler Carruth     return true;
18087adc3a2bSChandler Carruth 
18097adc3a2bSChandler Carruth   if (I.getOpcode() == Instruction::FCmp)
18107adc3a2bSChandler Carruth     return false;
18117adc3a2bSChandler Carruth 
18127adc3a2bSChandler Carruth   // Otherwise look for a comparison between constant offset pointers with
18137adc3a2bSChandler Carruth   // a common base.
18147adc3a2bSChandler Carruth   Value *LHSBase, *RHSBase;
18157adc3a2bSChandler Carruth   APInt LHSOffset, RHSOffset;
18167adc3a2bSChandler Carruth   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
18177adc3a2bSChandler Carruth   if (LHSBase) {
18187adc3a2bSChandler Carruth     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
18197adc3a2bSChandler Carruth     if (RHSBase && LHSBase == RHSBase) {
18207adc3a2bSChandler Carruth       // We have common bases, fold the icmp to a constant based on the
18217adc3a2bSChandler Carruth       // offsets.
18227adc3a2bSChandler Carruth       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
18237adc3a2bSChandler Carruth       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
18247adc3a2bSChandler Carruth       if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
18257adc3a2bSChandler Carruth         SimplifiedValues[&I] = C;
18267adc3a2bSChandler Carruth         ++NumConstantPtrCmps;
18277adc3a2bSChandler Carruth         return true;
18287adc3a2bSChandler Carruth       }
18297adc3a2bSChandler Carruth     }
18307adc3a2bSChandler Carruth   }
18317adc3a2bSChandler Carruth 
18327adc3a2bSChandler Carruth   // If the comparison is an equality comparison with null, we can simplify it
18337adc3a2bSChandler Carruth   // if we know the value (argument) can't be null
18347adc3a2bSChandler Carruth   if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)) &&
18357adc3a2bSChandler Carruth       isKnownNonNullInCallee(I.getOperand(0))) {
18367adc3a2bSChandler Carruth     bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
18377adc3a2bSChandler Carruth     SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
18387adc3a2bSChandler Carruth                                       : ConstantInt::getFalse(I.getType());
18397adc3a2bSChandler Carruth     return true;
18407adc3a2bSChandler Carruth   }
184106408758SMircea Trofin   return handleSROA(I.getOperand(0), isa<ConstantPointerNull>(I.getOperand(1)));
18427adc3a2bSChandler Carruth }
18437adc3a2bSChandler Carruth 
18447adc3a2bSChandler Carruth bool CallAnalyzer::visitSub(BinaryOperator &I) {
18457adc3a2bSChandler Carruth   // Try to handle a special case: we can fold computing the difference of two
18467adc3a2bSChandler Carruth   // constant-related pointers.
18477adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
18487adc3a2bSChandler Carruth   Value *LHSBase, *RHSBase;
18497adc3a2bSChandler Carruth   APInt LHSOffset, RHSOffset;
18507adc3a2bSChandler Carruth   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
18517adc3a2bSChandler Carruth   if (LHSBase) {
18527adc3a2bSChandler Carruth     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
18537adc3a2bSChandler Carruth     if (RHSBase && LHSBase == RHSBase) {
18547adc3a2bSChandler Carruth       // We have common bases, fold the subtract to a constant based on the
18557adc3a2bSChandler Carruth       // offsets.
18567adc3a2bSChandler Carruth       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
18577adc3a2bSChandler Carruth       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
18587adc3a2bSChandler Carruth       if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
18597adc3a2bSChandler Carruth         SimplifiedValues[&I] = C;
18607adc3a2bSChandler Carruth         ++NumConstantPtrDiffs;
18617adc3a2bSChandler Carruth         return true;
18627adc3a2bSChandler Carruth       }
18637adc3a2bSChandler Carruth     }
18647adc3a2bSChandler Carruth   }
18657adc3a2bSChandler Carruth 
18667adc3a2bSChandler Carruth   // Otherwise, fall back to the generic logic for simplifying and handling
18677adc3a2bSChandler Carruth   // instructions.
18687adc3a2bSChandler Carruth   return Base::visitSub(I);
18697adc3a2bSChandler Carruth }
18707adc3a2bSChandler Carruth 
18717adc3a2bSChandler Carruth bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
18727adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
18736d14dfe8SHaicheng Wu   Constant *CLHS = dyn_cast<Constant>(LHS);
18746d14dfe8SHaicheng Wu   if (!CLHS)
18756d14dfe8SHaicheng Wu     CLHS = SimplifiedValues.lookup(LHS);
18766d14dfe8SHaicheng Wu   Constant *CRHS = dyn_cast<Constant>(RHS);
18776d14dfe8SHaicheng Wu   if (!CRHS)
18786d14dfe8SHaicheng Wu     CRHS = SimplifiedValues.lookup(RHS);
18796d14dfe8SHaicheng Wu 
18807adc3a2bSChandler Carruth   Value *SimpleV = nullptr;
18817adc3a2bSChandler Carruth   if (auto FI = dyn_cast<FPMathOperator>(&I))
18825a956c85SMircea Trofin     SimpleV = SimplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS,
18835a956c85SMircea Trofin                             FI->getFastMathFlags(), DL);
18847adc3a2bSChandler Carruth   else
18856d14dfe8SHaicheng Wu     SimpleV =
18866d14dfe8SHaicheng Wu         SimplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS, DL);
18877adc3a2bSChandler Carruth 
18886d14dfe8SHaicheng Wu   if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
18896d14dfe8SHaicheng Wu     SimplifiedValues[&I] = C;
18906d14dfe8SHaicheng Wu 
18916d14dfe8SHaicheng Wu   if (SimpleV)
18927adc3a2bSChandler Carruth     return true;
18937adc3a2bSChandler Carruth 
18947adc3a2bSChandler Carruth   // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
18957adc3a2bSChandler Carruth   disableSROA(LHS);
18967adc3a2bSChandler Carruth   disableSROA(RHS);
18977adc3a2bSChandler Carruth 
189839ed9a60SEli Friedman   // If the instruction is floating point, and the target says this operation
189939ed9a60SEli Friedman   // is expensive, this may eventually become a library call. Treat the cost
19007cebf0afSCraig Topper   // as such. Unless it's fneg which can be implemented with an xor.
19017cebf0afSCraig Topper   using namespace llvm::PatternMatch;
190239ed9a60SEli Friedman   if (I.getType()->isFloatingPointTy() &&
19037cebf0afSCraig Topper       TTI.getFPOpCost(I.getType()) == TargetTransformInfo::TCC_Expensive &&
19047cebf0afSCraig Topper       !match(&I, m_FNeg(m_Value())))
190506408758SMircea Trofin     onCallPenalty();
190639ed9a60SEli Friedman 
19077adc3a2bSChandler Carruth   return false;
19087adc3a2bSChandler Carruth }
19097adc3a2bSChandler Carruth 
19106cda33baSCraig Topper bool CallAnalyzer::visitFNeg(UnaryOperator &I) {
19116cda33baSCraig Topper   Value *Op = I.getOperand(0);
19126cda33baSCraig Topper   Constant *COp = dyn_cast<Constant>(Op);
19136cda33baSCraig Topper   if (!COp)
19146cda33baSCraig Topper     COp = SimplifiedValues.lookup(Op);
19156cda33baSCraig Topper 
19165a956c85SMircea Trofin   Value *SimpleV = SimplifyFNegInst(
19175a956c85SMircea Trofin       COp ? COp : Op, cast<FPMathOperator>(I).getFastMathFlags(), DL);
19186cda33baSCraig Topper 
19196cda33baSCraig Topper   if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
19206cda33baSCraig Topper     SimplifiedValues[&I] = C;
19216cda33baSCraig Topper 
19226cda33baSCraig Topper   if (SimpleV)
19236cda33baSCraig Topper     return true;
19246cda33baSCraig Topper 
19256cda33baSCraig Topper   // Disable any SROA on arguments to arbitrary, unsimplified fneg.
19266cda33baSCraig Topper   disableSROA(Op);
19276cda33baSCraig Topper 
19286cda33baSCraig Topper   return false;
19296cda33baSCraig Topper }
19306cda33baSCraig Topper 
19317adc3a2bSChandler Carruth bool CallAnalyzer::visitLoad(LoadInst &I) {
193206408758SMircea Trofin   if (handleSROA(I.getPointerOperand(), I.isSimple()))
19337adc3a2bSChandler Carruth     return true;
19347adc3a2bSChandler Carruth 
1935a4461515SHaicheng Wu   // If the data is already loaded from this address and hasn't been clobbered
1936a4461515SHaicheng Wu   // by any stores or calls, this load is likely to be redundant and can be
1937a4461515SHaicheng Wu   // eliminated.
1938a4461515SHaicheng Wu   if (EnableLoadElimination &&
1939b3689cabSHaicheng Wu       !LoadAddrSet.insert(I.getPointerOperand()).second && I.isUnordered()) {
194006408758SMircea Trofin     onLoadEliminationOpportunity();
1941a4461515SHaicheng Wu     return true;
1942a4461515SHaicheng Wu   }
1943a4461515SHaicheng Wu 
19447adc3a2bSChandler Carruth   return false;
19457adc3a2bSChandler Carruth }
19467adc3a2bSChandler Carruth 
19477adc3a2bSChandler Carruth bool CallAnalyzer::visitStore(StoreInst &I) {
194806408758SMircea Trofin   if (handleSROA(I.getPointerOperand(), I.isSimple()))
19497adc3a2bSChandler Carruth     return true;
19507adc3a2bSChandler Carruth 
1951a4461515SHaicheng Wu   // The store can potentially clobber loads and prevent repeated loads from
1952a4461515SHaicheng Wu   // being eliminated.
1953a4461515SHaicheng Wu   // FIXME:
1954a4461515SHaicheng Wu   // 1. We can probably keep an initial set of eliminatable loads substracted
1955a4461515SHaicheng Wu   // from the cost even when we finally see a store. We just need to disable
1956a4461515SHaicheng Wu   // *further* accumulation of elimination savings.
1957a4461515SHaicheng Wu   // 2. We should probably at some point thread MemorySSA for the callee into
1958a4461515SHaicheng Wu   // this and then use that to actually compute *really* precise savings.
1959a4461515SHaicheng Wu   disableLoadElimination();
19607adc3a2bSChandler Carruth   return false;
19617adc3a2bSChandler Carruth }
19627adc3a2bSChandler Carruth 
19637adc3a2bSChandler Carruth bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) {
19647adc3a2bSChandler Carruth   // Constant folding for extract value is trivial.
1965617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1966617f6364SEaswaran Raman         return ConstantExpr::getExtractValue(COps[0], I.getIndices());
1967617f6364SEaswaran Raman       }))
19687adc3a2bSChandler Carruth     return true;
19697adc3a2bSChandler Carruth 
1970ba5b015bSRoman Lebedev   // SROA can't look through these, but they may be free.
1971ba5b015bSRoman Lebedev   return Base::visitExtractValue(I);
19727adc3a2bSChandler Carruth }
19737adc3a2bSChandler Carruth 
19747adc3a2bSChandler Carruth bool CallAnalyzer::visitInsertValue(InsertValueInst &I) {
19757adc3a2bSChandler Carruth   // Constant folding for insert value is trivial.
1976617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1977617f6364SEaswaran Raman         return ConstantExpr::getInsertValue(/*AggregateOperand*/ COps[0],
1978617f6364SEaswaran Raman                                             /*InsertedValueOperand*/ COps[1],
1979617f6364SEaswaran Raman                                             I.getIndices());
1980617f6364SEaswaran Raman       }))
19817adc3a2bSChandler Carruth     return true;
19827adc3a2bSChandler Carruth 
1983ba5b015bSRoman Lebedev   // SROA can't look through these, but they may be free.
1984ba5b015bSRoman Lebedev   return Base::visitInsertValue(I);
19857adc3a2bSChandler Carruth }
19867adc3a2bSChandler Carruth 
19875f8f34e4SAdrian Prantl /// Try to simplify a call site.
19887adc3a2bSChandler Carruth ///
19897adc3a2bSChandler Carruth /// Takes a concrete function and callsite and tries to actually simplify it by
19907adc3a2bSChandler Carruth /// analyzing the arguments and call itself with instsimplify. Returns true if
19917adc3a2bSChandler Carruth /// it has simplified the callsite to some other entity (a constant), making it
19927adc3a2bSChandler Carruth /// free.
1993652168a9SFedor Sergeev bool CallAnalyzer::simplifyCallSite(Function *F, CallBase &Call) {
19947adc3a2bSChandler Carruth   // FIXME: Using the instsimplify logic directly for this is inefficient
19957adc3a2bSChandler Carruth   // because we have to continually rebuild the argument list even when no
19967adc3a2bSChandler Carruth   // simplifications can be performed. Until that is fixed with remapping
19977adc3a2bSChandler Carruth   // inside of instsimplify, directly constant fold calls here.
1998652168a9SFedor Sergeev   if (!canConstantFoldCallTo(&Call, F))
19997adc3a2bSChandler Carruth     return false;
20007adc3a2bSChandler Carruth 
20017adc3a2bSChandler Carruth   // Try to re-map the arguments to constants.
20027adc3a2bSChandler Carruth   SmallVector<Constant *, 4> ConstantArgs;
2003652168a9SFedor Sergeev   ConstantArgs.reserve(Call.arg_size());
2004652168a9SFedor Sergeev   for (Value *I : Call.args()) {
2005652168a9SFedor Sergeev     Constant *C = dyn_cast<Constant>(I);
20067adc3a2bSChandler Carruth     if (!C)
2007652168a9SFedor Sergeev       C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(I));
20087adc3a2bSChandler Carruth     if (!C)
20097adc3a2bSChandler Carruth       return false; // This argument doesn't map to a constant.
20107adc3a2bSChandler Carruth 
20117adc3a2bSChandler Carruth     ConstantArgs.push_back(C);
20127adc3a2bSChandler Carruth   }
2013652168a9SFedor Sergeev   if (Constant *C = ConstantFoldCall(&Call, F, ConstantArgs)) {
2014652168a9SFedor Sergeev     SimplifiedValues[&Call] = C;
20157adc3a2bSChandler Carruth     return true;
20167adc3a2bSChandler Carruth   }
20177adc3a2bSChandler Carruth 
20187adc3a2bSChandler Carruth   return false;
20197adc3a2bSChandler Carruth }
20207adc3a2bSChandler Carruth 
2021652168a9SFedor Sergeev bool CallAnalyzer::visitCallBase(CallBase &Call) {
2022652168a9SFedor Sergeev   if (Call.hasFnAttr(Attribute::ReturnsTwice) &&
20237adc3a2bSChandler Carruth       !F.hasFnAttribute(Attribute::ReturnsTwice)) {
20247adc3a2bSChandler Carruth     // This aborts the entire analysis.
20257adc3a2bSChandler Carruth     ExposesReturnsTwice = true;
20267adc3a2bSChandler Carruth     return false;
20277adc3a2bSChandler Carruth   }
2028652168a9SFedor Sergeev   if (isa<CallInst>(Call) && cast<CallInst>(Call).cannotDuplicate())
20297adc3a2bSChandler Carruth     ContainsNoDuplicateCall = true;
20307adc3a2bSChandler Carruth 
2031825debe8SEhud Katz   Value *Callee = Call.getCalledOperand();
2032825debe8SEhud Katz   Function *F = dyn_cast_or_null<Function>(Callee);
2033825debe8SEhud Katz   bool IsIndirectCall = !F;
2034825debe8SEhud Katz   if (IsIndirectCall) {
2035825debe8SEhud Katz     // Check if this happens to be an indirect function call to a known function
2036825debe8SEhud Katz     // in this inline context. If not, we've done all we can.
2037825debe8SEhud Katz     F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
2038825debe8SEhud Katz     if (!F) {
203906408758SMircea Trofin       onCallArgumentSetup(Call);
2040825debe8SEhud Katz 
2041825debe8SEhud Katz       if (!Call.onlyReadsMemory())
2042825debe8SEhud Katz         disableLoadElimination();
2043825debe8SEhud Katz       return Base::visitCallBase(Call);
2044825debe8SEhud Katz     }
2045825debe8SEhud Katz   }
2046825debe8SEhud Katz 
2047825debe8SEhud Katz   assert(F && "Expected a call to a known function");
2048825debe8SEhud Katz 
20497adc3a2bSChandler Carruth   // When we have a concrete function, first try to simplify it directly.
2050652168a9SFedor Sergeev   if (simplifyCallSite(F, Call))
20517adc3a2bSChandler Carruth     return true;
20527adc3a2bSChandler Carruth 
20537adc3a2bSChandler Carruth   // Next check if it is an intrinsic we know about.
20547adc3a2bSChandler Carruth   // FIXME: Lift this into part of the InstVisitor.
2055652168a9SFedor Sergeev   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&Call)) {
20567adc3a2bSChandler Carruth     switch (II->getIntrinsicID()) {
20577adc3a2bSChandler Carruth     default:
2058652168a9SFedor Sergeev       if (!Call.onlyReadsMemory() && !isAssumeLikeIntrinsic(II))
2059a4461515SHaicheng Wu         disableLoadElimination();
2060652168a9SFedor Sergeev       return Base::visitCallBase(Call);
20617adc3a2bSChandler Carruth 
20627dd8dbf4SPeter Collingbourne     case Intrinsic::load_relative:
206306408758SMircea Trofin       onLoadRelativeIntrinsic();
20647dd8dbf4SPeter Collingbourne       return false;
20657dd8dbf4SPeter Collingbourne 
20667adc3a2bSChandler Carruth     case Intrinsic::memset:
20677adc3a2bSChandler Carruth     case Intrinsic::memcpy:
20687adc3a2bSChandler Carruth     case Intrinsic::memmove:
2069a4461515SHaicheng Wu       disableLoadElimination();
20707adc3a2bSChandler Carruth       // SROA can usually chew through these intrinsics, but they aren't free.
20717adc3a2bSChandler Carruth       return false;
20724296ea72SVitaly Buka     case Intrinsic::icall_branch_funnel:
20737adc3a2bSChandler Carruth     case Intrinsic::localescape:
20744296ea72SVitaly Buka       HasUninlineableIntrinsic = true;
20757adc3a2bSChandler Carruth       return false;
207680788d80SFlorian Hahn     case Intrinsic::vastart:
207777beee41SSameer AbuAsal       InitsVargArgs = true;
207880788d80SFlorian Hahn       return false;
2079269b335bSArthur Eubanks     case Intrinsic::launder_invariant_group:
2080269b335bSArthur Eubanks     case Intrinsic::strip_invariant_group:
2081269b335bSArthur Eubanks       if (auto *SROAArg = getSROAArgForValueOrNull(II->getOperand(0)))
2082269b335bSArthur Eubanks         SROAArgValues[II] = SROAArg;
2083269b335bSArthur Eubanks       return true;
20847adc3a2bSChandler Carruth     }
20857adc3a2bSChandler Carruth   }
20867adc3a2bSChandler Carruth 
2087652168a9SFedor Sergeev   if (F == Call.getFunction()) {
20887adc3a2bSChandler Carruth     // This flag will fully abort the analysis, so don't bother with anything
20897adc3a2bSChandler Carruth     // else.
20907adc3a2bSChandler Carruth     IsRecursiveCall = true;
20917adc3a2bSChandler Carruth     return false;
20927adc3a2bSChandler Carruth   }
20937adc3a2bSChandler Carruth 
20947adc3a2bSChandler Carruth   if (TTI.isLoweredToCall(F)) {
209506408758SMircea Trofin     onLoweredCall(F, Call, IsIndirectCall);
2096825debe8SEhud Katz   }
20977adc3a2bSChandler Carruth 
2098825debe8SEhud Katz   if (!(Call.onlyReadsMemory() || (IsIndirectCall && F->onlyReadsMemory())))
2099a4461515SHaicheng Wu     disableLoadElimination();
2100652168a9SFedor Sergeev   return Base::visitCallBase(Call);
21017adc3a2bSChandler Carruth }
21027adc3a2bSChandler Carruth 
21037adc3a2bSChandler Carruth bool CallAnalyzer::visitReturnInst(ReturnInst &RI) {
21047adc3a2bSChandler Carruth   // At least one return instruction will be free after inlining.
21057adc3a2bSChandler Carruth   bool Free = !HasReturn;
21067adc3a2bSChandler Carruth   HasReturn = true;
21077adc3a2bSChandler Carruth   return Free;
21087adc3a2bSChandler Carruth }
21097adc3a2bSChandler Carruth 
21107adc3a2bSChandler Carruth bool CallAnalyzer::visitBranchInst(BranchInst &BI) {
21117adc3a2bSChandler Carruth   // We model unconditional branches as essentially free -- they really
21127adc3a2bSChandler Carruth   // shouldn't exist at all, but handling them makes the behavior of the
21137adc3a2bSChandler Carruth   // inliner more regular and predictable. Interestingly, conditional branches
21147adc3a2bSChandler Carruth   // which will fold away are also free.
21157adc3a2bSChandler Carruth   return BI.isUnconditional() || isa<ConstantInt>(BI.getCondition()) ||
21167adc3a2bSChandler Carruth          dyn_cast_or_null<ConstantInt>(
21177adc3a2bSChandler Carruth              SimplifiedValues.lookup(BI.getCondition()));
21187adc3a2bSChandler Carruth }
21197adc3a2bSChandler Carruth 
21203ec848bcSHaicheng Wu bool CallAnalyzer::visitSelectInst(SelectInst &SI) {
21213ec848bcSHaicheng Wu   bool CheckSROA = SI.getType()->isPointerTy();
21223ec848bcSHaicheng Wu   Value *TrueVal = SI.getTrueValue();
21233ec848bcSHaicheng Wu   Value *FalseVal = SI.getFalseValue();
21243ec848bcSHaicheng Wu 
21253ec848bcSHaicheng Wu   Constant *TrueC = dyn_cast<Constant>(TrueVal);
21263ec848bcSHaicheng Wu   if (!TrueC)
21273ec848bcSHaicheng Wu     TrueC = SimplifiedValues.lookup(TrueVal);
21283ec848bcSHaicheng Wu   Constant *FalseC = dyn_cast<Constant>(FalseVal);
21293ec848bcSHaicheng Wu   if (!FalseC)
21303ec848bcSHaicheng Wu     FalseC = SimplifiedValues.lookup(FalseVal);
21313ec848bcSHaicheng Wu   Constant *CondC =
21323ec848bcSHaicheng Wu       dyn_cast_or_null<Constant>(SimplifiedValues.lookup(SI.getCondition()));
21333ec848bcSHaicheng Wu 
21343ec848bcSHaicheng Wu   if (!CondC) {
21353ec848bcSHaicheng Wu     // Select C, X, X => X
21363ec848bcSHaicheng Wu     if (TrueC == FalseC && TrueC) {
21373ec848bcSHaicheng Wu       SimplifiedValues[&SI] = TrueC;
21383ec848bcSHaicheng Wu       return true;
21393ec848bcSHaicheng Wu     }
21403ec848bcSHaicheng Wu 
21413ec848bcSHaicheng Wu     if (!CheckSROA)
21423ec848bcSHaicheng Wu       return Base::visitSelectInst(SI);
21433ec848bcSHaicheng Wu 
21443ec848bcSHaicheng Wu     std::pair<Value *, APInt> TrueBaseAndOffset =
21453ec848bcSHaicheng Wu         ConstantOffsetPtrs.lookup(TrueVal);
21463ec848bcSHaicheng Wu     std::pair<Value *, APInt> FalseBaseAndOffset =
21473ec848bcSHaicheng Wu         ConstantOffsetPtrs.lookup(FalseVal);
21483ec848bcSHaicheng Wu     if (TrueBaseAndOffset == FalseBaseAndOffset && TrueBaseAndOffset.first) {
21493ec848bcSHaicheng Wu       ConstantOffsetPtrs[&SI] = TrueBaseAndOffset;
21503ec848bcSHaicheng Wu 
215106408758SMircea Trofin       if (auto *SROAArg = getSROAArgForValueOrNull(TrueVal))
21523ec848bcSHaicheng Wu         SROAArgValues[&SI] = SROAArg;
21533ec848bcSHaicheng Wu       return true;
21543ec848bcSHaicheng Wu     }
21553ec848bcSHaicheng Wu 
21563ec848bcSHaicheng Wu     return Base::visitSelectInst(SI);
21573ec848bcSHaicheng Wu   }
21583ec848bcSHaicheng Wu 
21593ec848bcSHaicheng Wu   // Select condition is a constant.
21607b639f50SJacob Hegna   Value *SelectedV = CondC->isAllOnesValue()  ? TrueVal
21617b639f50SJacob Hegna                      : (CondC->isNullValue()) ? FalseVal
21627b639f50SJacob Hegna                                               : nullptr;
21633ec848bcSHaicheng Wu   if (!SelectedV) {
21643ec848bcSHaicheng Wu     // Condition is a vector constant that is not all 1s or all 0s.  If all
21653ec848bcSHaicheng Wu     // operands are constants, ConstantExpr::getSelect() can handle the cases
21663ec848bcSHaicheng Wu     // such as select vectors.
21673ec848bcSHaicheng Wu     if (TrueC && FalseC) {
21683ec848bcSHaicheng Wu       if (auto *C = ConstantExpr::getSelect(CondC, TrueC, FalseC)) {
21693ec848bcSHaicheng Wu         SimplifiedValues[&SI] = C;
21703ec848bcSHaicheng Wu         return true;
21713ec848bcSHaicheng Wu       }
21723ec848bcSHaicheng Wu     }
21733ec848bcSHaicheng Wu     return Base::visitSelectInst(SI);
21743ec848bcSHaicheng Wu   }
21753ec848bcSHaicheng Wu 
21763ec848bcSHaicheng Wu   // Condition is either all 1s or all 0s. SI can be simplified.
21773ec848bcSHaicheng Wu   if (Constant *SelectedC = dyn_cast<Constant>(SelectedV)) {
21783ec848bcSHaicheng Wu     SimplifiedValues[&SI] = SelectedC;
21793ec848bcSHaicheng Wu     return true;
21803ec848bcSHaicheng Wu   }
21813ec848bcSHaicheng Wu 
21823ec848bcSHaicheng Wu   if (!CheckSROA)
21833ec848bcSHaicheng Wu     return true;
21843ec848bcSHaicheng Wu 
21853ec848bcSHaicheng Wu   std::pair<Value *, APInt> BaseAndOffset =
21863ec848bcSHaicheng Wu       ConstantOffsetPtrs.lookup(SelectedV);
21873ec848bcSHaicheng Wu   if (BaseAndOffset.first) {
21883ec848bcSHaicheng Wu     ConstantOffsetPtrs[&SI] = BaseAndOffset;
21893ec848bcSHaicheng Wu 
219006408758SMircea Trofin     if (auto *SROAArg = getSROAArgForValueOrNull(SelectedV))
21913ec848bcSHaicheng Wu       SROAArgValues[&SI] = SROAArg;
21923ec848bcSHaicheng Wu   }
21933ec848bcSHaicheng Wu 
21943ec848bcSHaicheng Wu   return true;
21953ec848bcSHaicheng Wu }
21963ec848bcSHaicheng Wu 
21977adc3a2bSChandler Carruth bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) {
21987adc3a2bSChandler Carruth   // We model unconditional switches as free, see the comments on handling
21997adc3a2bSChandler Carruth   // branches.
22007adc3a2bSChandler Carruth   if (isa<ConstantInt>(SI.getCondition()))
22017adc3a2bSChandler Carruth     return true;
22027adc3a2bSChandler Carruth   if (Value *V = SimplifiedValues.lookup(SI.getCondition()))
22037adc3a2bSChandler Carruth     if (isa<ConstantInt>(V))
22047adc3a2bSChandler Carruth       return true;
22057adc3a2bSChandler Carruth 
22067ad02eeeSEric Christopher   // Assume the most general case where the switch is lowered into
2207919f9e8dSJun Bum Lim   // either a jump table, bit test, or a balanced binary tree consisting of
2208919f9e8dSJun Bum Lim   // case clusters without merging adjacent clusters with the same
2209919f9e8dSJun Bum Lim   // destination. We do not consider the switches that are lowered with a mix
2210919f9e8dSJun Bum Lim   // of jump table/bit test/binary search tree. The cost of the switch is
2211919f9e8dSJun Bum Lim   // proportional to the size of the tree or the size of jump table range.
22122960d41eSJun Bum Lim   //
22132960d41eSJun Bum Lim   // NB: We convert large switches which are just used to initialize large phi
2214*472462c4SBjorn Pettersson   // nodes to lookup tables instead in simplifycfg, so this shouldn't prevent
22152960d41eSJun Bum Lim   // inlining those. It will prevent inlining in cases where the optimization
22162960d41eSJun Bum Lim   // does not (yet) fire.
2217919f9e8dSJun Bum Lim 
2218919f9e8dSJun Bum Lim   unsigned JumpTableSize = 0;
221908e2386dSMircea Trofin   BlockFrequencyInfo *BFI = GetBFI ? &(GetBFI(F)) : nullptr;
2220919f9e8dSJun Bum Lim   unsigned NumCaseCluster =
22210d987e41SHiroshi Yamauchi       TTI.getEstimatedNumberOfCaseClusters(SI, JumpTableSize, PSI, BFI);
2222919f9e8dSJun Bum Lim 
222306408758SMircea Trofin   onFinalizeSwitch(JumpTableSize, NumCaseCluster);
2224919f9e8dSJun Bum Lim   return false;
2225919f9e8dSJun Bum Lim }
2226919f9e8dSJun Bum Lim 
22277adc3a2bSChandler Carruth bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) {
22287adc3a2bSChandler Carruth   // We never want to inline functions that contain an indirectbr.  This is
22297adc3a2bSChandler Carruth   // incorrect because all the blockaddress's (in static global initializers
22307adc3a2bSChandler Carruth   // for example) would be referring to the original function, and this
22317adc3a2bSChandler Carruth   // indirect jump would jump from the inlined copy of the function into the
22327adc3a2bSChandler Carruth   // original function which is extremely undefined behavior.
22337adc3a2bSChandler Carruth   // FIXME: This logic isn't really right; we can safely inline functions with
22347adc3a2bSChandler Carruth   // indirectbr's as long as no other function or global references the
22357adc3a2bSChandler Carruth   // blockaddress of a block within the current function.
22367adc3a2bSChandler Carruth   HasIndirectBr = true;
22377adc3a2bSChandler Carruth   return false;
22387adc3a2bSChandler Carruth }
22397adc3a2bSChandler Carruth 
22407adc3a2bSChandler Carruth bool CallAnalyzer::visitResumeInst(ResumeInst &RI) {
22417adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
22427adc3a2bSChandler Carruth   // the inline cost of a resume instruction.
22437adc3a2bSChandler Carruth   return false;
22447adc3a2bSChandler Carruth }
22457adc3a2bSChandler Carruth 
22467adc3a2bSChandler Carruth bool CallAnalyzer::visitCleanupReturnInst(CleanupReturnInst &CRI) {
22477adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
22487adc3a2bSChandler Carruth   // the inline cost of a cleanupret instruction.
22497adc3a2bSChandler Carruth   return false;
22507adc3a2bSChandler Carruth }
22517adc3a2bSChandler Carruth 
22527adc3a2bSChandler Carruth bool CallAnalyzer::visitCatchReturnInst(CatchReturnInst &CRI) {
22537adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
22548220bcc5SJoseph Tremoulet   // the inline cost of a catchret instruction.
22557adc3a2bSChandler Carruth   return false;
22567adc3a2bSChandler Carruth }
22577adc3a2bSChandler Carruth 
22587adc3a2bSChandler Carruth bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) {
22597adc3a2bSChandler Carruth   // FIXME: It might be reasonably to discount the cost of instructions leading
22607adc3a2bSChandler Carruth   // to unreachable as they have the lowest possible impact on both runtime and
22617adc3a2bSChandler Carruth   // code size.
22627adc3a2bSChandler Carruth   return true; // No actual code is needed for unreachable.
22637adc3a2bSChandler Carruth }
22647adc3a2bSChandler Carruth 
22657adc3a2bSChandler Carruth bool CallAnalyzer::visitInstruction(Instruction &I) {
22667adc3a2bSChandler Carruth   // Some instructions are free. All of the free intrinsics can also be
22677adc3a2bSChandler Carruth   // handled by SROA, etc.
22683ccbd4f3SSander de Smalen   if (TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency) ==
22693ccbd4f3SSander de Smalen       TargetTransformInfo::TCC_Free)
22707adc3a2bSChandler Carruth     return true;
22717adc3a2bSChandler Carruth 
22727adc3a2bSChandler Carruth   // We found something we don't understand or can't handle. Mark any SROA-able
22737adc3a2bSChandler Carruth   // values in the operand list as no longer viable.
227491aff1d8SNick Desaulniers   for (const Use &Op : I.operands())
227591aff1d8SNick Desaulniers     disableSROA(Op);
22767adc3a2bSChandler Carruth 
22777adc3a2bSChandler Carruth   return false;
22787adc3a2bSChandler Carruth }
22797adc3a2bSChandler Carruth 
22805f8f34e4SAdrian Prantl /// Analyze a basic block for its contribution to the inline cost.
22817adc3a2bSChandler Carruth ///
22827adc3a2bSChandler Carruth /// This method walks the analyzer over every instruction in the given basic
22837adc3a2bSChandler Carruth /// block and accounts for their cost during inlining at this callsite. It
22847adc3a2bSChandler Carruth /// aborts early if the threshold has been exceeded or an impossible to inline
22857adc3a2bSChandler Carruth /// construct has been detected. It returns false if inlining is no longer
22867adc3a2bSChandler Carruth /// viable, and true if inlining remains viable.
2287c0aa4b75SDavid Bolvansky InlineResult
2288c0aa4b75SDavid Bolvansky CallAnalyzer::analyzeBlock(BasicBlock *BB,
22897adc3a2bSChandler Carruth                            SmallPtrSetImpl<const Value *> &EphValues) {
229091aff1d8SNick Desaulniers   for (Instruction &I : *BB) {
22917adc3a2bSChandler Carruth     // FIXME: Currently, the number of instructions in a function regardless of
22927adc3a2bSChandler Carruth     // our ability to simplify them during inline to constants or dead code,
22937adc3a2bSChandler Carruth     // are actually used by the vector bonus heuristic. As long as that's true,
22947adc3a2bSChandler Carruth     // we have to special case debug intrinsics here to prevent differences in
22957adc3a2bSChandler Carruth     // inlining due to debug symbols. Eventually, the number of unsimplified
22967adc3a2bSChandler Carruth     // instructions shouldn't factor into the cost computation, but until then,
22977adc3a2bSChandler Carruth     // hack around it here.
22987adc3a2bSChandler Carruth     if (isa<DbgInfoIntrinsic>(I))
22997adc3a2bSChandler Carruth       continue;
23007adc3a2bSChandler Carruth 
2301f3c44569SHongtao Yu     // Skip pseudo-probes.
2302f3c44569SHongtao Yu     if (isa<PseudoProbeInst>(I))
2303f3c44569SHongtao Yu       continue;
2304f3c44569SHongtao Yu 
23057adc3a2bSChandler Carruth     // Skip ephemeral values.
230691aff1d8SNick Desaulniers     if (EphValues.count(&I))
23077adc3a2bSChandler Carruth       continue;
23087adc3a2bSChandler Carruth 
23097adc3a2bSChandler Carruth     ++NumInstructions;
231091aff1d8SNick Desaulniers     if (isa<ExtractElementInst>(I) || I.getType()->isVectorTy())
23117adc3a2bSChandler Carruth       ++NumVectorInstructions;
23127adc3a2bSChandler Carruth 
23137adc3a2bSChandler Carruth     // If the instruction simplified to a constant, there is no cost to this
23147adc3a2bSChandler Carruth     // instruction. Visit the instructions using our InstVisitor to account for
23157adc3a2bSChandler Carruth     // all of the per-instruction logic. The visit tree returns true if we
23167adc3a2bSChandler Carruth     // consumed the instruction in any way, and false if the instruction's base
23177adc3a2bSChandler Carruth     // cost should count against inlining.
231891aff1d8SNick Desaulniers     onInstructionAnalysisStart(&I);
2319c965fd94SKirill Naumov 
232091aff1d8SNick Desaulniers     if (Base::visit(&I))
23217adc3a2bSChandler Carruth       ++NumInstructionsSimplified;
23227adc3a2bSChandler Carruth     else
232314a16faeSMircea Trofin       onMissedSimplification();
23247adc3a2bSChandler Carruth 
232591aff1d8SNick Desaulniers     onInstructionAnalysisFinish(&I);
23260812c5beSHaicheng Wu     using namespace ore;
23277adc3a2bSChandler Carruth     // If the visit this instruction detected an uninlinable pattern, abort.
23285466597fSMircea Trofin     InlineResult IR = InlineResult::success();
2329c0aa4b75SDavid Bolvansky     if (IsRecursiveCall)
23305466597fSMircea Trofin       IR = InlineResult::failure("recursive");
2331c0aa4b75SDavid Bolvansky     else if (ExposesReturnsTwice)
23325466597fSMircea Trofin       IR = InlineResult::failure("exposes returns twice");
2333c0aa4b75SDavid Bolvansky     else if (HasDynamicAlloca)
23345466597fSMircea Trofin       IR = InlineResult::failure("dynamic alloca");
2335c0aa4b75SDavid Bolvansky     else if (HasIndirectBr)
23365466597fSMircea Trofin       IR = InlineResult::failure("indirect branch");
2337c0aa4b75SDavid Bolvansky     else if (HasUninlineableIntrinsic)
23385466597fSMircea Trofin       IR = InlineResult::failure("uninlinable intrinsic");
233977beee41SSameer AbuAsal     else if (InitsVargArgs)
23405466597fSMircea Trofin       IR = InlineResult::failure("varargs");
23415466597fSMircea Trofin     if (!IR.isSuccess()) {
23420812c5beSHaicheng Wu       if (ORE)
23439590658fSVivek Pandya         ORE->emit([&]() {
23449590658fSVivek Pandya           return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline",
2345652168a9SFedor Sergeev                                           &CandidateCall)
2346c0aa4b75SDavid Bolvansky                  << NV("Callee", &F) << " has uninlinable pattern ("
23475466597fSMircea Trofin                  << NV("InlineResult", IR.getFailureReason())
2348c0aa4b75SDavid Bolvansky                  << ") and cost is not fully computed";
23499590658fSVivek Pandya         });
2350c0aa4b75SDavid Bolvansky       return IR;
23510812c5beSHaicheng Wu     }
23527adc3a2bSChandler Carruth 
23537adc3a2bSChandler Carruth     // If the caller is a recursive function then we don't want to inline
23547adc3a2bSChandler Carruth     // functions which allocate a lot of stack space because it would increase
23557adc3a2bSChandler Carruth     // the caller stack usage dramatically.
23567adc3a2bSChandler Carruth     if (IsCallerRecursive &&
23570812c5beSHaicheng Wu         AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller) {
23585466597fSMircea Trofin       auto IR =
23595466597fSMircea Trofin           InlineResult::failure("recursive and allocates too much stack space");
23600812c5beSHaicheng Wu       if (ORE)
23619590658fSVivek Pandya         ORE->emit([&]() {
23629590658fSVivek Pandya           return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline",
2363652168a9SFedor Sergeev                                           &CandidateCall)
23645466597fSMircea Trofin                  << NV("Callee", &F) << " is "
23655466597fSMircea Trofin                  << NV("InlineResult", IR.getFailureReason())
2366c0aa4b75SDavid Bolvansky                  << ". Cost is not fully computed";
23679590658fSVivek Pandya         });
2368c0aa4b75SDavid Bolvansky       return IR;
23690812c5beSHaicheng Wu     }
23707adc3a2bSChandler Carruth 
237106408758SMircea Trofin     if (shouldStop())
23725466597fSMircea Trofin       return InlineResult::failure(
23735466597fSMircea Trofin           "Call site analysis is not favorable to inlining.");
23747adc3a2bSChandler Carruth   }
23757adc3a2bSChandler Carruth 
23765466597fSMircea Trofin   return InlineResult::success();
23777adc3a2bSChandler Carruth }
23787adc3a2bSChandler Carruth 
23795f8f34e4SAdrian Prantl /// Compute the base pointer and cumulative constant offsets for V.
23807adc3a2bSChandler Carruth ///
23817adc3a2bSChandler Carruth /// This strips all constant offsets off of V, leaving it the base pointer, and
23827adc3a2bSChandler Carruth /// accumulates the total constant offset applied in the returned constant. It
23837adc3a2bSChandler Carruth /// returns 0 if V is not a pointer, and returns the constant '0' if there are
23847adc3a2bSChandler Carruth /// no constant offsets applied.
23857adc3a2bSChandler Carruth ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
23867adc3a2bSChandler Carruth   if (!V->getType()->isPointerTy())
23877adc3a2bSChandler Carruth     return nullptr;
23887adc3a2bSChandler Carruth 
238977f32994SBjorn Pettersson   unsigned AS = V->getType()->getPointerAddressSpace();
2390945b7e5aSElena Demikhovsky   unsigned IntPtrWidth = DL.getIndexSizeInBits(AS);
23917adc3a2bSChandler Carruth   APInt Offset = APInt::getNullValue(IntPtrWidth);
23927adc3a2bSChandler Carruth 
23937adc3a2bSChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
23947adc3a2bSChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
23957adc3a2bSChandler Carruth   SmallPtrSet<Value *, 4> Visited;
23967adc3a2bSChandler Carruth   Visited.insert(V);
23977adc3a2bSChandler Carruth   do {
23987adc3a2bSChandler Carruth     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
23997adc3a2bSChandler Carruth       if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
24007adc3a2bSChandler Carruth         return nullptr;
24017adc3a2bSChandler Carruth       V = GEP->getPointerOperand();
24027adc3a2bSChandler Carruth     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
24037adc3a2bSChandler Carruth       V = cast<Operator>(V)->getOperand(0);
24047adc3a2bSChandler Carruth     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
24055ce32728SSanjoy Das       if (GA->isInterposable())
24067adc3a2bSChandler Carruth         break;
24077adc3a2bSChandler Carruth       V = GA->getAliasee();
24087adc3a2bSChandler Carruth     } else {
24097adc3a2bSChandler Carruth       break;
24107adc3a2bSChandler Carruth     }
24117adc3a2bSChandler Carruth     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
24127adc3a2bSChandler Carruth   } while (Visited.insert(V).second);
24137adc3a2bSChandler Carruth 
241497572775SNicola Zaghen   Type *IdxPtrTy = DL.getIndexType(V->getType());
241597572775SNicola Zaghen   return cast<ConstantInt>(ConstantInt::get(IdxPtrTy, Offset));
24167adc3a2bSChandler Carruth }
24177adc3a2bSChandler Carruth 
24185f8f34e4SAdrian Prantl /// Find dead blocks due to deleted CFG edges during inlining.
24193739e14aSHaicheng Wu ///
24203739e14aSHaicheng Wu /// If we know the successor of the current block, \p CurrBB, has to be \p
24213739e14aSHaicheng Wu /// NextBB, the other successors of \p CurrBB are dead if these successors have
24223739e14aSHaicheng Wu /// no live incoming CFG edges.  If one block is found to be dead, we can
24233739e14aSHaicheng Wu /// continue growing the dead block list by checking the successors of the dead
24243739e14aSHaicheng Wu /// blocks to see if all their incoming edges are dead or not.
24253739e14aSHaicheng Wu void CallAnalyzer::findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB) {
24263739e14aSHaicheng Wu   auto IsEdgeDead = [&](BasicBlock *Pred, BasicBlock *Succ) {
242702a2bb2fSHiroshi Inoue     // A CFG edge is dead if the predecessor is dead or the predecessor has a
24283739e14aSHaicheng Wu     // known successor which is not the one under exam.
24293739e14aSHaicheng Wu     return (DeadBlocks.count(Pred) ||
24303739e14aSHaicheng Wu             (KnownSuccessors[Pred] && KnownSuccessors[Pred] != Succ));
24313739e14aSHaicheng Wu   };
24323739e14aSHaicheng Wu 
24333739e14aSHaicheng Wu   auto IsNewlyDead = [&](BasicBlock *BB) {
24343739e14aSHaicheng Wu     // If all the edges to a block are dead, the block is also dead.
24353739e14aSHaicheng Wu     return (!DeadBlocks.count(BB) &&
24363739e14aSHaicheng Wu             llvm::all_of(predecessors(BB),
24373739e14aSHaicheng Wu                          [&](BasicBlock *P) { return IsEdgeDead(P, BB); }));
24383739e14aSHaicheng Wu   };
24393739e14aSHaicheng Wu 
24403739e14aSHaicheng Wu   for (BasicBlock *Succ : successors(CurrBB)) {
24413739e14aSHaicheng Wu     if (Succ == NextBB || !IsNewlyDead(Succ))
24423739e14aSHaicheng Wu       continue;
24433739e14aSHaicheng Wu     SmallVector<BasicBlock *, 4> NewDead;
24443739e14aSHaicheng Wu     NewDead.push_back(Succ);
24453739e14aSHaicheng Wu     while (!NewDead.empty()) {
24463739e14aSHaicheng Wu       BasicBlock *Dead = NewDead.pop_back_val();
24473739e14aSHaicheng Wu       if (DeadBlocks.insert(Dead))
24483739e14aSHaicheng Wu         // Continue growing the dead block lists.
24493739e14aSHaicheng Wu         for (BasicBlock *S : successors(Dead))
24503739e14aSHaicheng Wu           if (IsNewlyDead(S))
24513739e14aSHaicheng Wu             NewDead.push_back(S);
24523739e14aSHaicheng Wu     }
24533739e14aSHaicheng Wu   }
24543739e14aSHaicheng Wu }
24553739e14aSHaicheng Wu 
24565f8f34e4SAdrian Prantl /// Analyze a call site for potential inlining.
24577adc3a2bSChandler Carruth ///
24587adc3a2bSChandler Carruth /// Returns true if inlining this call is viable, and false if it is not
24597adc3a2bSChandler Carruth /// viable. It computes the cost and adjusts the threshold based on numerous
24607adc3a2bSChandler Carruth /// factors and heuristics. If this method returns false but the computed cost
24617adc3a2bSChandler Carruth /// is below the computed threshold, then inlining was forcibly disabled by
24627adc3a2bSChandler Carruth /// some artifact of the routine.
246393ac81ccSMircea Trofin InlineResult CallAnalyzer::analyze() {
24647adc3a2bSChandler Carruth   ++NumCallsAnalyzed;
24657adc3a2bSChandler Carruth 
246606408758SMircea Trofin   auto Result = onAnalysisStart();
24675466597fSMircea Trofin   if (!Result.isSuccess())
246806408758SMircea Trofin     return Result;
24697adc3a2bSChandler Carruth 
24707adc3a2bSChandler Carruth   if (F.empty())
24715466597fSMircea Trofin     return InlineResult::success();
24727adc3a2bSChandler Carruth 
247393ac81ccSMircea Trofin   Function *Caller = CandidateCall.getFunction();
24747adc3a2bSChandler Carruth   // Check if the caller function is recursive itself.
24757adc3a2bSChandler Carruth   for (User *U : Caller->users()) {
2476652168a9SFedor Sergeev     CallBase *Call = dyn_cast<CallBase>(U);
2477652168a9SFedor Sergeev     if (Call && Call->getFunction() == Caller) {
24787adc3a2bSChandler Carruth       IsCallerRecursive = true;
24797adc3a2bSChandler Carruth       break;
24807adc3a2bSChandler Carruth     }
24817adc3a2bSChandler Carruth   }
24827adc3a2bSChandler Carruth 
24837adc3a2bSChandler Carruth   // Populate our simplified values by mapping from function arguments to call
24847adc3a2bSChandler Carruth   // arguments with known important simplifications.
248593ac81ccSMircea Trofin   auto CAI = CandidateCall.arg_begin();
248691aff1d8SNick Desaulniers   for (Argument &FAI : F.args()) {
248793ac81ccSMircea Trofin     assert(CAI != CandidateCall.arg_end());
24887adc3a2bSChandler Carruth     if (Constant *C = dyn_cast<Constant>(CAI))
248991aff1d8SNick Desaulniers       SimplifiedValues[&FAI] = C;
24907adc3a2bSChandler Carruth 
24917adc3a2bSChandler Carruth     Value *PtrArg = *CAI;
24927adc3a2bSChandler Carruth     if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
249391aff1d8SNick Desaulniers       ConstantOffsetPtrs[&FAI] = std::make_pair(PtrArg, C->getValue());
24947adc3a2bSChandler Carruth 
24957adc3a2bSChandler Carruth       // We can SROA any pointer arguments derived from alloca instructions.
249606408758SMircea Trofin       if (auto *SROAArg = dyn_cast<AllocaInst>(PtrArg)) {
249791aff1d8SNick Desaulniers         SROAArgValues[&FAI] = SROAArg;
249806408758SMircea Trofin         onInitializeSROAArg(SROAArg);
24992e42cc7aSMircea Trofin         EnabledSROAAllocas.insert(SROAArg);
25007adc3a2bSChandler Carruth       }
25017adc3a2bSChandler Carruth     }
250291aff1d8SNick Desaulniers     ++CAI;
25037adc3a2bSChandler Carruth   }
25047adc3a2bSChandler Carruth   NumConstantArgs = SimplifiedValues.size();
25057adc3a2bSChandler Carruth   NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
25067adc3a2bSChandler Carruth   NumAllocaArgs = SROAArgValues.size();
25077adc3a2bSChandler Carruth 
25087adc3a2bSChandler Carruth   // FIXME: If a caller has multiple calls to a callee, we end up recomputing
25097adc3a2bSChandler Carruth   // the ephemeral values multiple times (and they're completely determined by
25107adc3a2bSChandler Carruth   // the callee, so this is purely duplicate work).
25117adc3a2bSChandler Carruth   SmallPtrSet<const Value *, 32> EphValues;
2512aec2fa35SDaniel Jasper   CodeMetrics::collectEphemeralValues(&F, &GetAssumptionCache(F), EphValues);
25137adc3a2bSChandler Carruth 
25147adc3a2bSChandler Carruth   // The worklist of live basic blocks in the callee *after* inlining. We avoid
25157adc3a2bSChandler Carruth   // adding basic blocks of the callee which can be proven to be dead for this
25167adc3a2bSChandler Carruth   // particular call site in order to get more accurate cost estimates. This
25177adc3a2bSChandler Carruth   // requires a somewhat heavyweight iteration pattern: we need to walk the
25187adc3a2bSChandler Carruth   // basic blocks in a breadth-first order as we insert live successors. To
25197adc3a2bSChandler Carruth   // accomplish this, prioritizing for small iterations because we exit after
25207adc3a2bSChandler Carruth   // crossing our threshold, we use a small-size optimized SetVector.
25217adc3a2bSChandler Carruth   typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
2522567556aaSChad Rosier                     SmallPtrSet<BasicBlock *, 16>>
2523567556aaSChad Rosier       BBSetVector;
25247adc3a2bSChandler Carruth   BBSetVector BBWorklist;
25257adc3a2bSChandler Carruth   BBWorklist.insert(&F.getEntryBlock());
252606408758SMircea Trofin 
25277adc3a2bSChandler Carruth   // Note that we *must not* cache the size, this loop grows the worklist.
25287adc3a2bSChandler Carruth   for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
252906408758SMircea Trofin     if (shouldStop())
25307adc3a2bSChandler Carruth       break;
25317adc3a2bSChandler Carruth 
25327adc3a2bSChandler Carruth     BasicBlock *BB = BBWorklist[Idx];
25337adc3a2bSChandler Carruth     if (BB->empty())
25347adc3a2bSChandler Carruth       continue;
25357adc3a2bSChandler Carruth 
25369895c701SKazu Hirata     onBlockStart(BB);
25379895c701SKazu Hirata 
2538639b29b1SNick Desaulniers     // Disallow inlining a blockaddress with uses other than strictly callbr.
2539639b29b1SNick Desaulniers     // A blockaddress only has defined behavior for an indirect branch in the
2540639b29b1SNick Desaulniers     // same function, and we do not currently support inlining indirect
2541639b29b1SNick Desaulniers     // branches.  But, the inliner may not see an indirect branch that ends up
2542639b29b1SNick Desaulniers     // being dead code at a particular call site. If the blockaddress escapes
2543639b29b1SNick Desaulniers     // the function, e.g., via a global variable, inlining may lead to an
2544639b29b1SNick Desaulniers     // invalid cross-function reference.
2545639b29b1SNick Desaulniers     // FIXME: pr/39560: continue relaxing this overt restriction.
25466a84cd3bSNick Desaulniers     if (BB->hasAddressTaken())
2547639b29b1SNick Desaulniers       for (User *U : BlockAddress::get(&*BB)->users())
2548639b29b1SNick Desaulniers         if (!isa<CallBrInst>(*U))
25495466597fSMircea Trofin           return InlineResult::failure("blockaddress used outside of callbr");
25507adc3a2bSChandler Carruth 
25517adc3a2bSChandler Carruth     // Analyze the cost of this block. If we blow through the threshold, this
25527adc3a2bSChandler Carruth     // returns false, and we can bail on out.
2553c0aa4b75SDavid Bolvansky     InlineResult IR = analyzeBlock(BB, EphValues);
25545466597fSMircea Trofin     if (!IR.isSuccess())
2555c0aa4b75SDavid Bolvansky       return IR;
25567adc3a2bSChandler Carruth 
2557edb12a83SChandler Carruth     Instruction *TI = BB->getTerminator();
25587adc3a2bSChandler Carruth 
25597adc3a2bSChandler Carruth     // Add in the live successors by first checking whether we have terminator
25607adc3a2bSChandler Carruth     // that may be simplified based on the values simplified by this call.
25617adc3a2bSChandler Carruth     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
25627adc3a2bSChandler Carruth       if (BI->isConditional()) {
25637adc3a2bSChandler Carruth         Value *Cond = BI->getCondition();
2564567556aaSChad Rosier         if (ConstantInt *SimpleCond =
2565567556aaSChad Rosier                 dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
25663739e14aSHaicheng Wu           BasicBlock *NextBB = BI->getSuccessor(SimpleCond->isZero() ? 1 : 0);
25673739e14aSHaicheng Wu           BBWorklist.insert(NextBB);
25683739e14aSHaicheng Wu           KnownSuccessors[BB] = NextBB;
25693739e14aSHaicheng Wu           findDeadBlocks(BB, NextBB);
25707adc3a2bSChandler Carruth           continue;
25717adc3a2bSChandler Carruth         }
25727adc3a2bSChandler Carruth       }
25737adc3a2bSChandler Carruth     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
25747adc3a2bSChandler Carruth       Value *Cond = SI->getCondition();
2575567556aaSChad Rosier       if (ConstantInt *SimpleCond =
2576567556aaSChad Rosier               dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
25773739e14aSHaicheng Wu         BasicBlock *NextBB = SI->findCaseValue(SimpleCond)->getCaseSuccessor();
25783739e14aSHaicheng Wu         BBWorklist.insert(NextBB);
25793739e14aSHaicheng Wu         KnownSuccessors[BB] = NextBB;
25803739e14aSHaicheng Wu         findDeadBlocks(BB, NextBB);
25817adc3a2bSChandler Carruth         continue;
25827adc3a2bSChandler Carruth       }
25837adc3a2bSChandler Carruth     }
25847adc3a2bSChandler Carruth 
25857adc3a2bSChandler Carruth     // If we're unable to select a particular successor, just count all of
25867adc3a2bSChandler Carruth     // them.
25877adc3a2bSChandler Carruth     for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
25887adc3a2bSChandler Carruth          ++TIdx)
25897adc3a2bSChandler Carruth       BBWorklist.insert(TI->getSuccessor(TIdx));
25907adc3a2bSChandler Carruth 
259106408758SMircea Trofin     onBlockAnalyzed(BB);
25927adc3a2bSChandler Carruth   }
25937adc3a2bSChandler Carruth 
259493ac81ccSMircea Trofin   bool OnlyOneCallAndLocalLinkage = F.hasLocalLinkage() && F.hasOneUse() &&
259593ac81ccSMircea Trofin                                     &F == CandidateCall.getCalledFunction();
25967adc3a2bSChandler Carruth   // If this is a noduplicate call, we can still inline as long as
25977adc3a2bSChandler Carruth   // inlining this would cause the removal of the caller (so the instruction
25987adc3a2bSChandler Carruth   // is not actually duplicated, just moved).
25997adc3a2bSChandler Carruth   if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall)
26005466597fSMircea Trofin     return InlineResult::failure("noduplicate");
26017adc3a2bSChandler Carruth 
260206408758SMircea Trofin   return finalizeAnalysis();
26037adc3a2bSChandler Carruth }
26047adc3a2bSChandler Carruth 
2605ca899bf9SKirill Naumov void InlineCostCallAnalyzer::print() {
26067adc3a2bSChandler Carruth #define DEBUG_PRINT_STAT(x) dbgs() << "      " #x ": " << x << "\n"
26071022b5ebSKirill Naumov   if (PrintInstructionComments)
2608c965fd94SKirill Naumov     F.print(dbgs(), &Writer);
26097adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantArgs);
26107adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
26117adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumAllocaArgs);
26127adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantPtrCmps);
26137adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantPtrDiffs);
26147adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumInstructionsSimplified);
26157adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumInstructions);
26167adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(SROACostSavings);
26177adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(SROACostSavingsLost);
2618a4461515SHaicheng Wu   DEBUG_PRINT_STAT(LoadEliminationCost);
26197adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
26207adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(Cost);
26217adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(Threshold);
26227adc3a2bSChandler Carruth #undef DEBUG_PRINT_STAT
26237adc3a2bSChandler Carruth }
2624ca899bf9SKirill Naumov 
2625ca899bf9SKirill Naumov #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2626ca899bf9SKirill Naumov /// Dump stats about this call's analysis.
26277b639f50SJacob Hegna LLVM_DUMP_METHOD void InlineCostCallAnalyzer::dump() { print(); }
26287adc3a2bSChandler Carruth #endif
26297adc3a2bSChandler Carruth 
26305f8f34e4SAdrian Prantl /// Test that there are no attribute conflicts between Caller and Callee
26317adc3a2bSChandler Carruth ///        that prevent inlining.
2632f9ca75f1STeresa Johnson static bool functionsHaveCompatibleAttributes(
2633f9ca75f1STeresa Johnson     Function *Caller, Function *Callee, TargetTransformInfo &TTI,
2634f9ca75f1STeresa Johnson     function_ref<const TargetLibraryInfo &(Function &)> &GetTLI) {
2635f9ca75f1STeresa Johnson   // Note that CalleeTLI must be a copy not a reference. The legacy pass manager
2636f9ca75f1STeresa Johnson   // caches the most recently created TLI in the TargetLibraryInfoWrapperPass
2637f9ca75f1STeresa Johnson   // object, and always returns the same object (which is overwritten on each
2638f9ca75f1STeresa Johnson   // GetTLI call). Therefore we copy the first result.
2639f9ca75f1STeresa Johnson   auto CalleeTLI = GetTLI(*Callee);
26407adc3a2bSChandler Carruth   return TTI.areInlineCompatible(Caller, Callee) &&
2641f9ca75f1STeresa Johnson          GetTLI(*Caller).areInlineCompatible(CalleeTLI,
2642ed03d948SMehdi Amini                                              InlineCallerSupersetNoBuiltin) &&
26431cb242ebSAkira Hatanaka          AttributeFuncs::areInlineCompatible(*Caller, *Callee);
26447adc3a2bSChandler Carruth }
26457adc3a2bSChandler Carruth 
2646652168a9SFedor Sergeev int llvm::getCallsiteCost(CallBase &Call, const DataLayout &DL) {
2647351d9b01SXinliang David Li   int Cost = 0;
2648652168a9SFedor Sergeev   for (unsigned I = 0, E = Call.arg_size(); I != E; ++I) {
2649652168a9SFedor Sergeev     if (Call.isByValArgument(I)) {
2650351d9b01SXinliang David Li       // We approximate the number of loads and stores needed by dividing the
2651351d9b01SXinliang David Li       // size of the byval type by the target's pointer size.
2652652168a9SFedor Sergeev       PointerType *PTy = cast<PointerType>(Call.getArgOperand(I)->getType());
265307a9df59SArthur Eubanks       unsigned TypeSize = DL.getTypeSizeInBits(Call.getParamByValType(I));
265477f32994SBjorn Pettersson       unsigned AS = PTy->getAddressSpace();
265577f32994SBjorn Pettersson       unsigned PointerSize = DL.getPointerSizeInBits(AS);
2656351d9b01SXinliang David Li       // Ceiling division.
2657351d9b01SXinliang David Li       unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
2658351d9b01SXinliang David Li 
2659351d9b01SXinliang David Li       // If it generates more than 8 stores it is likely to be expanded as an
2660351d9b01SXinliang David Li       // inline memcpy so we take that as an upper bound. Otherwise we assume
2661351d9b01SXinliang David Li       // one load and one store per word copied.
2662351d9b01SXinliang David Li       // FIXME: The maxStoresPerMemcpy setting from the target should be used
2663351d9b01SXinliang David Li       // here instead of a magic number of 8, but it's not available via
2664351d9b01SXinliang David Li       // DataLayout.
2665351d9b01SXinliang David Li       NumStores = std::min(NumStores, 8U);
2666351d9b01SXinliang David Li 
2667351d9b01SXinliang David Li       Cost += 2 * NumStores * InlineConstants::InstrCost;
2668351d9b01SXinliang David Li     } else {
2669351d9b01SXinliang David Li       // For non-byval arguments subtract off one instruction per call
2670351d9b01SXinliang David Li       // argument.
2671351d9b01SXinliang David Li       Cost += InlineConstants::InstrCost;
2672351d9b01SXinliang David Li     }
2673351d9b01SXinliang David Li   }
2674351d9b01SXinliang David Li   // The call instruction also disappears after inlining.
2675351d9b01SXinliang David Li   Cost += InlineConstants::InstrCost + InlineConstants::CallPenalty;
2676351d9b01SXinliang David Li   return Cost;
2677351d9b01SXinliang David Li }
2678351d9b01SXinliang David Li 
2679ab6a6837SSean Silva InlineCost llvm::getInlineCost(
2680652168a9SFedor Sergeev     CallBase &Call, const InlineParams &Params, TargetTransformInfo &CalleeTTI,
268108e2386dSMircea Trofin     function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
2682f9ca75f1STeresa Johnson     function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
268308e2386dSMircea Trofin     function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
26840812c5beSHaicheng Wu     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
2685652168a9SFedor Sergeev   return getInlineCost(Call, Call.getCalledFunction(), Params, CalleeTTI,
268608e2386dSMircea Trofin                        GetAssumptionCache, GetTLI, GetBFI, PSI, ORE);
2687b9f7120eSEaswaran Raman }
2688b9f7120eSEaswaran Raman 
2689011a07c0SMircea Trofin Optional<int> llvm::getInliningCostEstimate(
26908a4013edSMircea Trofin     CallBase &Call, TargetTransformInfo &CalleeTTI,
269108e2386dSMircea Trofin     function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
269208e2386dSMircea Trofin     function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
26938a4013edSMircea Trofin     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
26948a4013edSMircea Trofin   const InlineParams Params = {/* DefaultThreshold*/ 0,
26958a4013edSMircea Trofin                                /*HintThreshold*/ {},
26968a4013edSMircea Trofin                                /*ColdThreshold*/ {},
26978a4013edSMircea Trofin                                /*OptSizeThreshold*/ {},
26988a4013edSMircea Trofin                                /*OptMinSizeThreshold*/ {},
26998a4013edSMircea Trofin                                /*HotCallSiteThreshold*/ {},
27008a4013edSMircea Trofin                                /*LocallyHotCallSiteThreshold*/ {},
27018a4013edSMircea Trofin                                /*ColdCallSiteThreshold*/ {},
2702347a599eSKazu Hirata                                /*ComputeFullInlineCost*/ true,
2703347a599eSKazu Hirata                                /*EnableDeferral*/ true};
27048a4013edSMircea Trofin 
270508e2386dSMircea Trofin   InlineCostCallAnalyzer CA(*Call.getCalledFunction(), Call, Params, CalleeTTI,
270608e2386dSMircea Trofin                             GetAssumptionCache, GetBFI, PSI, ORE, true,
27078a4013edSMircea Trofin                             /*IgnoreThreshold*/ true);
27088a4013edSMircea Trofin   auto R = CA.analyze();
27098a4013edSMircea Trofin   if (!R.isSuccess())
27108a4013edSMircea Trofin     return None;
27118a4013edSMircea Trofin   return CA.getCost();
27128a4013edSMircea Trofin }
27138a4013edSMircea Trofin 
271499f00635SJacob Hegna Optional<InlineCostFeatures> llvm::getInliningCostFeatures(
271599f00635SJacob Hegna     CallBase &Call, TargetTransformInfo &CalleeTTI,
271699f00635SJacob Hegna     function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
271799f00635SJacob Hegna     function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
271899f00635SJacob Hegna     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
271999f00635SJacob Hegna   InlineCostFeaturesAnalyzer CFA(CalleeTTI, GetAssumptionCache, GetBFI, PSI,
272099f00635SJacob Hegna                                  ORE, *Call.getCalledFunction(), Call);
272199f00635SJacob Hegna   auto R = CFA.analyze();
272299f00635SJacob Hegna   if (!R.isSuccess())
272399f00635SJacob Hegna     return None;
272499f00635SJacob Hegna   return CFA.features();
272599f00635SJacob Hegna }
272699f00635SJacob Hegna 
2727201498c6SMircea Trofin Optional<InlineResult> llvm::getAttributeBasedInliningDecision(
2728201498c6SMircea Trofin     CallBase &Call, Function *Callee, TargetTransformInfo &CalleeTTI,
2729201498c6SMircea Trofin     function_ref<const TargetLibraryInfo &(Function &)> GetTLI) {
2730f4bb2f0dSEaswaran Raman 
27317adc3a2bSChandler Carruth   // Cannot inline indirect calls.
27327adc3a2bSChandler Carruth   if (!Callee)
2733201498c6SMircea Trofin     return InlineResult::failure("indirect call");
27347adc3a2bSChandler Carruth 
273531e60b91SXun Li   // When callee coroutine function is inlined into caller coroutine function
273631e60b91SXun Li   // before coro-split pass,
273731e60b91SXun Li   // coro-early pass can not handle this quiet well.
273831e60b91SXun Li   // So we won't inline the coroutine function if it have not been unsplited
273931e60b91SXun Li   if (Callee->isPresplitCoroutine())
274031e60b91SXun Li     return InlineResult::failure("unsplited coroutine call");
274131e60b91SXun Li 
27423851496eSBjorn Pettersson   // Never inline calls with byval arguments that does not have the alloca
27433851496eSBjorn Pettersson   // address space. Since byval arguments can be replaced with a copy to an
27443851496eSBjorn Pettersson   // alloca, the inlined code would need to be adjusted to handle that the
27453851496eSBjorn Pettersson   // argument is in the alloca address space (so it is a little bit complicated
27463851496eSBjorn Pettersson   // to solve).
27473851496eSBjorn Pettersson   unsigned AllocaAS = Callee->getParent()->getDataLayout().getAllocaAddrSpace();
2748652168a9SFedor Sergeev   for (unsigned I = 0, E = Call.arg_size(); I != E; ++I)
2749652168a9SFedor Sergeev     if (Call.isByValArgument(I)) {
2750652168a9SFedor Sergeev       PointerType *PTy = cast<PointerType>(Call.getArgOperand(I)->getType());
27513851496eSBjorn Pettersson       if (PTy->getAddressSpace() != AllocaAS)
2752201498c6SMircea Trofin         return InlineResult::failure("byval arguments without alloca"
2753c0aa4b75SDavid Bolvansky                                      " address space");
27543851496eSBjorn Pettersson     }
27553851496eSBjorn Pettersson 
27567adc3a2bSChandler Carruth   // Calls to functions with always-inline attributes should be inlined
27577adc3a2bSChandler Carruth   // whenever possible.
2758652168a9SFedor Sergeev   if (Call.hasFnAttr(Attribute::AlwaysInline)) {
275915b17d0aSYevgeny Rouban     auto IsViable = isInlineViable(*Callee);
27605466597fSMircea Trofin     if (IsViable.isSuccess())
2761201498c6SMircea Trofin       return InlineResult::success();
2762201498c6SMircea Trofin     return InlineResult::failure(IsViable.getFailureReason());
27637adc3a2bSChandler Carruth   }
27647adc3a2bSChandler Carruth 
27657adc3a2bSChandler Carruth   // Never inline functions with conflicting attributes (unless callee has
27667adc3a2bSChandler Carruth   // always-inline attribute).
2767652168a9SFedor Sergeev   Function *Caller = Call.getCaller();
2768f9ca75f1STeresa Johnson   if (!functionsHaveCompatibleAttributes(Caller, Callee, CalleeTTI, GetTLI))
2769201498c6SMircea Trofin     return InlineResult::failure("conflicting attributes");
27707adc3a2bSChandler Carruth 
27717adc3a2bSChandler Carruth   // Don't inline this call if the caller has the optnone attribute.
277285bd3978SEvandro Menezes   if (Caller->hasOptNone())
2773201498c6SMircea Trofin     return InlineResult::failure("optnone attribute");
27747adc3a2bSChandler Carruth 
277577eeac3dSManoj Gupta   // Don't inline a function that treats null pointer as valid into a caller
277677eeac3dSManoj Gupta   // that does not have this attribute.
277777eeac3dSManoj Gupta   if (!Caller->nullPointerIsDefined() && Callee->nullPointerIsDefined())
2778201498c6SMircea Trofin     return InlineResult::failure("nullptr definitions incompatible");
277977eeac3dSManoj Gupta 
2780c0aa4b75SDavid Bolvansky   // Don't inline functions which can be interposed at link-time.
2781c0aa4b75SDavid Bolvansky   if (Callee->isInterposable())
2782201498c6SMircea Trofin     return InlineResult::failure("interposable");
2783c0aa4b75SDavid Bolvansky 
2784c0aa4b75SDavid Bolvansky   // Don't inline functions marked noinline.
2785c0aa4b75SDavid Bolvansky   if (Callee->hasFnAttribute(Attribute::NoInline))
2786201498c6SMircea Trofin     return InlineResult::failure("noinline function attribute");
2787c0aa4b75SDavid Bolvansky 
2788c0aa4b75SDavid Bolvansky   // Don't inline call sites marked noinline.
2789652168a9SFedor Sergeev   if (Call.isNoInline())
2790201498c6SMircea Trofin     return InlineResult::failure("noinline call site attribute");
2791201498c6SMircea Trofin 
2792bc044a88SNick Desaulniers   // Don't inline functions if one does not have any stack protector attribute
2793bc044a88SNick Desaulniers   // but the other does.
2794bc044a88SNick Desaulniers   if (Caller->hasStackProtectorFnAttr() && !Callee->hasStackProtectorFnAttr())
2795bc044a88SNick Desaulniers     return InlineResult::failure(
2796bc044a88SNick Desaulniers         "stack protected caller but callee requested no stack protector");
2797bc044a88SNick Desaulniers   if (Callee->hasStackProtectorFnAttr() && !Caller->hasStackProtectorFnAttr())
2798bc044a88SNick Desaulniers     return InlineResult::failure(
2799bc044a88SNick Desaulniers         "stack protected callee but caller requested no stack protector");
2800bc044a88SNick Desaulniers 
2801201498c6SMircea Trofin   return None;
2802201498c6SMircea Trofin }
2803201498c6SMircea Trofin 
2804201498c6SMircea Trofin InlineCost llvm::getInlineCost(
2805201498c6SMircea Trofin     CallBase &Call, Function *Callee, const InlineParams &Params,
2806201498c6SMircea Trofin     TargetTransformInfo &CalleeTTI,
280708e2386dSMircea Trofin     function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
2808201498c6SMircea Trofin     function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
280908e2386dSMircea Trofin     function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
2810201498c6SMircea Trofin     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
2811201498c6SMircea Trofin 
2812201498c6SMircea Trofin   auto UserDecision =
2813201498c6SMircea Trofin       llvm::getAttributeBasedInliningDecision(Call, Callee, CalleeTTI, GetTLI);
2814201498c6SMircea Trofin 
2815201498c6SMircea Trofin   if (UserDecision.hasValue()) {
2816201498c6SMircea Trofin     if (UserDecision->isSuccess())
2817201498c6SMircea Trofin       return llvm::InlineCost::getAlways("always inline attribute");
2818201498c6SMircea Trofin     return llvm::InlineCost::getNever(UserDecision->getFailureReason());
2819201498c6SMircea Trofin   }
28207adc3a2bSChandler Carruth 
2821d34e60caSNicola Zaghen   LLVM_DEBUG(llvm::dbgs() << "      Analyzing call of " << Callee->getName()
2822201498c6SMircea Trofin                           << "... (caller:" << Call.getCaller()->getName()
2823201498c6SMircea Trofin                           << ")\n");
28247adc3a2bSChandler Carruth 
282508e2386dSMircea Trofin   InlineCostCallAnalyzer CA(*Callee, Call, Params, CalleeTTI,
282608e2386dSMircea Trofin                             GetAssumptionCache, GetBFI, PSI, ORE);
282793ac81ccSMircea Trofin   InlineResult ShouldInline = CA.analyze();
28287adc3a2bSChandler Carruth 
2829d34e60caSNicola Zaghen   LLVM_DEBUG(CA.dump());
28307adc3a2bSChandler Carruth 
28316869e6c1SWenlei He   // Always make cost benefit based decision explicit.
28326869e6c1SWenlei He   // We use always/never here since threshold is not meaningful,
28336869e6c1SWenlei He   // as it's not what drives cost-benefit analysis.
28346869e6c1SWenlei He   if (CA.wasDecidedByCostBenefit()) {
28356869e6c1SWenlei He     if (ShouldInline.isSuccess())
28366869e6c1SWenlei He       return InlineCost::getAlways("benefit over cost");
28376869e6c1SWenlei He     else
28386869e6c1SWenlei He       return InlineCost::getNever("cost over benefit");
28396869e6c1SWenlei He   }
28406869e6c1SWenlei He 
28417adc3a2bSChandler Carruth   // Check if there was a reason to force inlining or no inlining.
28425466597fSMircea Trofin   if (!ShouldInline.isSuccess() && CA.getCost() < CA.getThreshold())
28435466597fSMircea Trofin     return InlineCost::getNever(ShouldInline.getFailureReason());
28445466597fSMircea Trofin   if (ShouldInline.isSuccess() && CA.getCost() >= CA.getThreshold())
2845c0aa4b75SDavid Bolvansky     return InlineCost::getAlways("empty function");
28467adc3a2bSChandler Carruth 
28477adc3a2bSChandler Carruth   return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());
28487adc3a2bSChandler Carruth }
28497adc3a2bSChandler Carruth 
285015b17d0aSYevgeny Rouban InlineResult llvm::isInlineViable(Function &F) {
28517adc3a2bSChandler Carruth   bool ReturnsTwice = F.hasFnAttribute(Attribute::ReturnsTwice);
285291aff1d8SNick Desaulniers   for (BasicBlock &BB : F) {
2853639b29b1SNick Desaulniers     // Disallow inlining of functions which contain indirect branches.
285491aff1d8SNick Desaulniers     if (isa<IndirectBrInst>(BB.getTerminator()))
28555466597fSMircea Trofin       return InlineResult::failure("contains indirect branches");
285615b17d0aSYevgeny Rouban 
2857639b29b1SNick Desaulniers     // Disallow inlining of blockaddresses which are used by non-callbr
2858639b29b1SNick Desaulniers     // instructions.
285991aff1d8SNick Desaulniers     if (BB.hasAddressTaken())
286091aff1d8SNick Desaulniers       for (User *U : BlockAddress::get(&BB)->users())
2861639b29b1SNick Desaulniers         if (!isa<CallBrInst>(*U))
28625466597fSMircea Trofin           return InlineResult::failure("blockaddress used outside of callbr");
28637adc3a2bSChandler Carruth 
286491aff1d8SNick Desaulniers     for (auto &II : BB) {
2865652168a9SFedor Sergeev       CallBase *Call = dyn_cast<CallBase>(&II);
2866652168a9SFedor Sergeev       if (!Call)
28677adc3a2bSChandler Carruth         continue;
28687adc3a2bSChandler Carruth 
28697adc3a2bSChandler Carruth       // Disallow recursive calls.
2870bc044a88SNick Desaulniers       Function *Callee = Call->getCalledFunction();
2871bc044a88SNick Desaulniers       if (&F == Callee)
28725466597fSMircea Trofin         return InlineResult::failure("recursive call");
28737adc3a2bSChandler Carruth 
28747adc3a2bSChandler Carruth       // Disallow calls which expose returns-twice to a function not previously
28757adc3a2bSChandler Carruth       // attributed as such.
2876652168a9SFedor Sergeev       if (!ReturnsTwice && isa<CallInst>(Call) &&
2877652168a9SFedor Sergeev           cast<CallInst>(Call)->canReturnTwice())
28785466597fSMircea Trofin         return InlineResult::failure("exposes returns-twice attribute");
28797adc3a2bSChandler Carruth 
2880bc044a88SNick Desaulniers       if (Callee)
2881bc044a88SNick Desaulniers         switch (Callee->getIntrinsicID()) {
28821636651eSFlorian Hahn         default:
28831636651eSFlorian Hahn           break;
288406408758SMircea Trofin         case llvm::Intrinsic::icall_branch_funnel:
28854296ea72SVitaly Buka           // Disallow inlining of @llvm.icall.branch.funnel because current
28864296ea72SVitaly Buka           // backend can't separate call targets from call arguments.
28875466597fSMircea Trofin           return InlineResult::failure(
28885466597fSMircea Trofin               "disallowed inlining of @llvm.icall.branch.funnel");
288906408758SMircea Trofin         case llvm::Intrinsic::localescape:
28907adc3a2bSChandler Carruth           // Disallow inlining functions that call @llvm.localescape. Doing this
28917adc3a2bSChandler Carruth           // correctly would require major changes to the inliner.
28925466597fSMircea Trofin           return InlineResult::failure(
28935466597fSMircea Trofin               "disallowed inlining of @llvm.localescape");
28941636651eSFlorian Hahn         case llvm::Intrinsic::vastart:
289506408758SMircea Trofin           // Disallow inlining of functions that initialize VarArgs with
289606408758SMircea Trofin           // va_start.
28975466597fSMircea Trofin           return InlineResult::failure(
28985466597fSMircea Trofin               "contains VarArgs initialized with va_start");
28997adc3a2bSChandler Carruth         }
29007adc3a2bSChandler Carruth     }
29011636651eSFlorian Hahn   }
29027adc3a2bSChandler Carruth 
29035466597fSMircea Trofin   return InlineResult::success();
29047adc3a2bSChandler Carruth }
29051c57cc2bSEaswaran Raman 
29061c57cc2bSEaswaran Raman // APIs to create InlineParams based on command line flags and/or other
29071c57cc2bSEaswaran Raman // parameters.
29081c57cc2bSEaswaran Raman 
29091c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams(int Threshold) {
29101c57cc2bSEaswaran Raman   InlineParams Params;
29111c57cc2bSEaswaran Raman 
29121c57cc2bSEaswaran Raman   // This field is the threshold to use for a callee by default. This is
29131c57cc2bSEaswaran Raman   // derived from one or more of:
29141c57cc2bSEaswaran Raman   //  * optimization or size-optimization levels,
29151c57cc2bSEaswaran Raman   //  * a value passed to createFunctionInliningPass function, or
29161c57cc2bSEaswaran Raman   //  * the -inline-threshold flag.
29171c57cc2bSEaswaran Raman   //  If the -inline-threshold flag is explicitly specified, that is used
29181c57cc2bSEaswaran Raman   //  irrespective of anything else.
29191c57cc2bSEaswaran Raman   if (InlineThreshold.getNumOccurrences() > 0)
29201c57cc2bSEaswaran Raman     Params.DefaultThreshold = InlineThreshold;
29211c57cc2bSEaswaran Raman   else
29221c57cc2bSEaswaran Raman     Params.DefaultThreshold = Threshold;
29231c57cc2bSEaswaran Raman 
29241c57cc2bSEaswaran Raman   // Set the HintThreshold knob from the -inlinehint-threshold.
29251c57cc2bSEaswaran Raman   Params.HintThreshold = HintThreshold;
29261c57cc2bSEaswaran Raman 
29271c57cc2bSEaswaran Raman   // Set the HotCallSiteThreshold knob from the -hot-callsite-threshold.
29281c57cc2bSEaswaran Raman   Params.HotCallSiteThreshold = HotCallSiteThreshold;
29291c57cc2bSEaswaran Raman 
2930974d4eeaSEaswaran Raman   // If the -locally-hot-callsite-threshold is explicitly specified, use it to
2931974d4eeaSEaswaran Raman   // populate LocallyHotCallSiteThreshold. Later, we populate
2932974d4eeaSEaswaran Raman   // Params.LocallyHotCallSiteThreshold from -locally-hot-callsite-threshold if
2933974d4eeaSEaswaran Raman   // we know that optimization level is O3 (in the getInlineParams variant that
2934974d4eeaSEaswaran Raman   // takes the opt and size levels).
2935974d4eeaSEaswaran Raman   // FIXME: Remove this check (and make the assignment unconditional) after
2936974d4eeaSEaswaran Raman   // addressing size regression issues at O2.
2937974d4eeaSEaswaran Raman   if (LocallyHotCallSiteThreshold.getNumOccurrences() > 0)
2938974d4eeaSEaswaran Raman     Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold;
2939974d4eeaSEaswaran Raman 
29405a956c85SMircea Trofin   // Set the ColdCallSiteThreshold knob from the
29415a956c85SMircea Trofin   // -inline-cold-callsite-threshold.
294212585b01SEaswaran Raman   Params.ColdCallSiteThreshold = ColdCallSiteThreshold;
294312585b01SEaswaran Raman 
29441c57cc2bSEaswaran Raman   // Set the OptMinSizeThreshold and OptSizeThreshold params only if the
29451c57cc2bSEaswaran Raman   // -inlinehint-threshold commandline option is not explicitly given. If that
29461c57cc2bSEaswaran Raman   // option is present, then its value applies even for callees with size and
29471c57cc2bSEaswaran Raman   // minsize attributes.
29481c57cc2bSEaswaran Raman   // If the -inline-threshold is not specified, set the ColdThreshold from the
29491c57cc2bSEaswaran Raman   // -inlinecold-threshold even if it is not explicitly passed. If
29501c57cc2bSEaswaran Raman   // -inline-threshold is specified, then -inlinecold-threshold needs to be
29511c57cc2bSEaswaran Raman   // explicitly specified to set the ColdThreshold knob
29521c57cc2bSEaswaran Raman   if (InlineThreshold.getNumOccurrences() == 0) {
29531c57cc2bSEaswaran Raman     Params.OptMinSizeThreshold = InlineConstants::OptMinSizeThreshold;
29541c57cc2bSEaswaran Raman     Params.OptSizeThreshold = InlineConstants::OptSizeThreshold;
29551c57cc2bSEaswaran Raman     Params.ColdThreshold = ColdThreshold;
29561c57cc2bSEaswaran Raman   } else if (ColdThreshold.getNumOccurrences() > 0) {
29571c57cc2bSEaswaran Raman     Params.ColdThreshold = ColdThreshold;
29581c57cc2bSEaswaran Raman   }
29591c57cc2bSEaswaran Raman   return Params;
29601c57cc2bSEaswaran Raman }
29611c57cc2bSEaswaran Raman 
29621c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams() {
29637f37a802STeresa Johnson   return getInlineParams(DefaultThreshold);
29641c57cc2bSEaswaran Raman }
29651c57cc2bSEaswaran Raman 
29661c57cc2bSEaswaran Raman // Compute the default threshold for inlining based on the opt level and the
29671c57cc2bSEaswaran Raman // size opt level.
29681c57cc2bSEaswaran Raman static int computeThresholdFromOptLevels(unsigned OptLevel,
29691c57cc2bSEaswaran Raman                                          unsigned SizeOptLevel) {
29701c57cc2bSEaswaran Raman   if (OptLevel > 2)
29711c57cc2bSEaswaran Raman     return InlineConstants::OptAggressiveThreshold;
29721c57cc2bSEaswaran Raman   if (SizeOptLevel == 1) // -Os
29731c57cc2bSEaswaran Raman     return InlineConstants::OptSizeThreshold;
29741c57cc2bSEaswaran Raman   if (SizeOptLevel == 2) // -Oz
29751c57cc2bSEaswaran Raman     return InlineConstants::OptMinSizeThreshold;
29767f37a802STeresa Johnson   return DefaultThreshold;
29771c57cc2bSEaswaran Raman }
29781c57cc2bSEaswaran Raman 
29791c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams(unsigned OptLevel, unsigned SizeOptLevel) {
2980974d4eeaSEaswaran Raman   auto Params =
2981974d4eeaSEaswaran Raman       getInlineParams(computeThresholdFromOptLevels(OptLevel, SizeOptLevel));
2982974d4eeaSEaswaran Raman   // At O3, use the value of -locally-hot-callsite-threshold option to populate
2983974d4eeaSEaswaran Raman   // Params.LocallyHotCallSiteThreshold. Below O3, this flag has effect only
2984974d4eeaSEaswaran Raman   // when it is specified explicitly.
2985974d4eeaSEaswaran Raman   if (OptLevel > 2)
2986974d4eeaSEaswaran Raman     Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold;
2987974d4eeaSEaswaran Raman   return Params;
29881c57cc2bSEaswaran Raman }
29896a5d7d49SKirill Naumov 
29906a5d7d49SKirill Naumov PreservedAnalyses
29916a5d7d49SKirill Naumov InlineCostAnnotationPrinterPass::run(Function &F,
29926a5d7d49SKirill Naumov                                      FunctionAnalysisManager &FAM) {
29936a5d7d49SKirill Naumov   PrintInstructionComments = true;
29947b639f50SJacob Hegna   std::function<AssumptionCache &(Function &)> GetAssumptionCache =
29957b639f50SJacob Hegna       [&](Function &F) -> AssumptionCache & {
29966a5d7d49SKirill Naumov     return FAM.getResult<AssumptionAnalysis>(F);
29976a5d7d49SKirill Naumov   };
29986a5d7d49SKirill Naumov   Module *M = F.getParent();
29996a5d7d49SKirill Naumov   ProfileSummaryInfo PSI(*M);
30006a5d7d49SKirill Naumov   DataLayout DL(M);
30016a5d7d49SKirill Naumov   TargetTransformInfo TTI(DL);
30026a5d7d49SKirill Naumov   // FIXME: Redesign the usage of InlineParams to expand the scope of this pass.
30036a5d7d49SKirill Naumov   // In the current implementation, the type of InlineParams doesn't matter as
30046a5d7d49SKirill Naumov   // the pass serves only for verification of inliner's decisions.
30056a5d7d49SKirill Naumov   // We can add a flag which determines InlineParams for this run. Right now,
30066a5d7d49SKirill Naumov   // the default InlineParams are used.
30076a5d7d49SKirill Naumov   const InlineParams Params = llvm::getInlineParams();
30086a5d7d49SKirill Naumov   for (BasicBlock &BB : F) {
30096a5d7d49SKirill Naumov     for (Instruction &I : BB) {
30106a5d7d49SKirill Naumov       if (CallInst *CI = dyn_cast<CallInst>(&I)) {
30116a5d7d49SKirill Naumov         Function *CalledFunction = CI->getCalledFunction();
30126a5d7d49SKirill Naumov         if (!CalledFunction || CalledFunction->isDeclaration())
30136a5d7d49SKirill Naumov           continue;
30146a5d7d49SKirill Naumov         OptimizationRemarkEmitter ORE(CalledFunction);
30156a5d7d49SKirill Naumov         InlineCostCallAnalyzer ICCA(*CalledFunction, *CI, Params, TTI,
30166a5d7d49SKirill Naumov                                     GetAssumptionCache, nullptr, &PSI, &ORE);
30176a5d7d49SKirill Naumov         ICCA.analyze();
30186a5d7d49SKirill Naumov         OS << "      Analyzing call of " << CalledFunction->getName()
30196a5d7d49SKirill Naumov            << "... (caller:" << CI->getCaller()->getName() << ")\n";
30206a5d7d49SKirill Naumov         ICCA.print();
30216a5d7d49SKirill Naumov       }
30226a5d7d49SKirill Naumov     }
30236a5d7d49SKirill Naumov   }
30246a5d7d49SKirill Naumov   return PreservedAnalyses::all();
30256a5d7d49SKirill Naumov }
3026