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 visitUnaryInstruction(UnaryInstruction &I);
3947adc3a2bSChandler Carruth   bool visitCmpInst(CmpInst &I);
3957adc3a2bSChandler Carruth   bool visitSub(BinaryOperator &I);
3967adc3a2bSChandler Carruth   bool visitBinaryOperator(BinaryOperator &I);
3976cda33baSCraig Topper   bool visitFNeg(UnaryOperator &I);
3987adc3a2bSChandler Carruth   bool visitLoad(LoadInst &I);
3997adc3a2bSChandler Carruth   bool visitStore(StoreInst &I);
4007adc3a2bSChandler Carruth   bool visitExtractValue(ExtractValueInst &I);
4017adc3a2bSChandler Carruth   bool visitInsertValue(InsertValueInst &I);
402652168a9SFedor Sergeev   bool visitCallBase(CallBase &Call);
4037adc3a2bSChandler Carruth   bool visitReturnInst(ReturnInst &RI);
4047adc3a2bSChandler Carruth   bool visitBranchInst(BranchInst &BI);
4053ec848bcSHaicheng Wu   bool visitSelectInst(SelectInst &SI);
4067adc3a2bSChandler Carruth   bool visitSwitchInst(SwitchInst &SI);
4077adc3a2bSChandler Carruth   bool visitIndirectBrInst(IndirectBrInst &IBI);
4087adc3a2bSChandler Carruth   bool visitResumeInst(ResumeInst &RI);
4097adc3a2bSChandler Carruth   bool visitCleanupReturnInst(CleanupReturnInst &RI);
4107adc3a2bSChandler Carruth   bool visitCatchReturnInst(CatchReturnInst &RI);
4117adc3a2bSChandler Carruth   bool visitUnreachableInst(UnreachableInst &I);
4127adc3a2bSChandler Carruth 
4137adc3a2bSChandler Carruth public:
41408e2386dSMircea Trofin   CallAnalyzer(
41508e2386dSMircea Trofin       Function &Callee, CallBase &Call, const TargetTransformInfo &TTI,
41608e2386dSMircea Trofin       function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
41708e2386dSMircea Trofin       function_ref<BlockFrequencyInfo &(Function &)> GetBFI = nullptr,
41808e2386dSMircea Trofin       ProfileSummaryInfo *PSI = nullptr,
41908e2386dSMircea Trofin       OptimizationRemarkEmitter *ORE = nullptr)
42012585b01SEaswaran Raman       : TTI(TTI), GetAssumptionCache(GetAssumptionCache), GetBFI(GetBFI),
4210812c5beSHaicheng Wu         PSI(PSI), F(Callee), DL(F.getParent()->getDataLayout()), ORE(ORE),
42206408758SMircea Trofin         CandidateCall(Call), EnableLoadElimination(true) {}
4237adc3a2bSChandler Carruth 
42493ac81ccSMircea Trofin   InlineResult analyze();
4257adc3a2bSChandler Carruth 
4267f094f7fSKirill Naumov   Optional<Constant*> getSimplifiedValue(Instruction *I) {
4277f094f7fSKirill Naumov     if (SimplifiedValues.find(I) != SimplifiedValues.end())
4287f094f7fSKirill Naumov       return SimplifiedValues[I];
4297f094f7fSKirill Naumov     return None;
4307f094f7fSKirill Naumov   }
4317f094f7fSKirill Naumov 
4327adc3a2bSChandler Carruth   // Keep a bunch of stats about the cost savings found so we can print them
4337adc3a2bSChandler Carruth   // out when debugging.
434eeae45dcSFedor Sergeev   unsigned NumConstantArgs = 0;
435eeae45dcSFedor Sergeev   unsigned NumConstantOffsetPtrArgs = 0;
436eeae45dcSFedor Sergeev   unsigned NumAllocaArgs = 0;
437eeae45dcSFedor Sergeev   unsigned NumConstantPtrCmps = 0;
438eeae45dcSFedor Sergeev   unsigned NumConstantPtrDiffs = 0;
439eeae45dcSFedor Sergeev   unsigned NumInstructionsSimplified = 0;
44076aab66dSMircea Trofin 
44176aab66dSMircea Trofin   void dump();
44276aab66dSMircea Trofin };
443338a6016SMircea Trofin 
44406408758SMircea Trofin /// FIXME: if it is necessary to derive from InlineCostCallAnalyzer, note
44506408758SMircea Trofin /// the FIXME in onLoweredCall, when instantiating an InlineCostCallAnalyzer
44606408758SMircea Trofin class InlineCostCallAnalyzer final : public CallAnalyzer {
44706408758SMircea Trofin   const int CostUpperBound = INT_MAX - InlineConstants::InstrCost - 1;
44806408758SMircea Trofin   const bool ComputeFullInlineCost;
44906408758SMircea Trofin   int LoadEliminationCost = 0;
45006408758SMircea Trofin   /// Bonus to be applied when percentage of vector instructions in callee is
45106408758SMircea Trofin   /// high (see more details in updateThreshold).
45206408758SMircea Trofin   int VectorBonus = 0;
45306408758SMircea Trofin   /// Bonus to be applied when the callee has only one reachable basic block.
45406408758SMircea Trofin   int SingleBBBonus = 0;
45506408758SMircea Trofin 
45606408758SMircea Trofin   /// Tunable parameters that control the analysis.
45706408758SMircea Trofin   const InlineParams &Params;
45806408758SMircea Trofin 
4591022b5ebSKirill Naumov   // This DenseMap stores the delta change in cost and threshold after
4601022b5ebSKirill Naumov   // accounting for the given instruction. The map is filled only with the
4611022b5ebSKirill Naumov   // flag PrintInstructionComments on.
4621022b5ebSKirill Naumov   DenseMap<const Instruction *, InstructionCostDetail> InstructionCostDetailMap;
4631022b5ebSKirill Naumov 
46406408758SMircea Trofin   /// Upper bound for the inlining cost. Bonuses are being applied to account
46506408758SMircea Trofin   /// for speculative "expected profit" of the inlining decision.
46606408758SMircea Trofin   int Threshold = 0;
46706408758SMircea Trofin 
46806408758SMircea Trofin   /// Attempt to evaluate indirect calls to boost its inline cost.
46906408758SMircea Trofin   const bool BoostIndirectCalls;
47006408758SMircea Trofin 
4718a4013edSMircea Trofin   /// Ignore the threshold when finalizing analysis.
4728a4013edSMircea Trofin   const bool IgnoreThreshold;
4738a4013edSMircea Trofin 
4749895c701SKazu Hirata   // True if the cost-benefit-analysis-based inliner is enabled.
4759895c701SKazu Hirata   const bool CostBenefitAnalysisEnabled;
4769895c701SKazu Hirata 
47706408758SMircea Trofin   /// Inlining cost measured in abstract units, accounts for all the
47806408758SMircea Trofin   /// instructions expected to be executed for a given function invocation.
47906408758SMircea Trofin   /// Instructions that are statically proven to be dead based on call-site
48006408758SMircea Trofin   /// arguments are not counted here.
48106408758SMircea Trofin   int Cost = 0;
48206408758SMircea Trofin 
4839895c701SKazu Hirata   // The cumulative cost at the beginning of the basic block being analyzed.  At
4849895c701SKazu Hirata   // the end of analyzing each basic block, "Cost - CostAtBBStart" represents
4859895c701SKazu Hirata   // the size of that basic block.
4869895c701SKazu Hirata   int CostAtBBStart = 0;
4879895c701SKazu Hirata 
4889895c701SKazu Hirata   // The static size of live but cold basic blocks.  This is "static" in the
4899895c701SKazu Hirata   // sense that it's not weighted by profile counts at all.
4909895c701SKazu Hirata   int ColdSize = 0;
4919895c701SKazu Hirata 
49206408758SMircea Trofin   bool SingleBB = true;
49306408758SMircea Trofin 
49406408758SMircea Trofin   unsigned SROACostSavings = 0;
49506408758SMircea Trofin   unsigned SROACostSavingsLost = 0;
49606408758SMircea Trofin 
49706408758SMircea Trofin   /// The mapping of caller Alloca values to their accumulated cost savings. If
49806408758SMircea Trofin   /// we have to disable SROA for one of the allocas, this tells us how much
49906408758SMircea Trofin   /// cost must be added.
50006408758SMircea Trofin   DenseMap<AllocaInst *, int> SROAArgCosts;
50106408758SMircea Trofin 
50206408758SMircea Trofin   /// Return true if \p Call is a cold callsite.
50306408758SMircea Trofin   bool isColdCallSite(CallBase &Call, BlockFrequencyInfo *CallerBFI);
50406408758SMircea Trofin 
50506408758SMircea Trofin   /// Update Threshold based on callsite properties such as callee
50606408758SMircea Trofin   /// attributes and callee hotness for PGO builds. The Callee is explicitly
50706408758SMircea Trofin   /// passed to support analyzing indirect calls whose target is inferred by
50806408758SMircea Trofin   /// analysis.
50906408758SMircea Trofin   void updateThreshold(CallBase &Call, Function &Callee);
51006408758SMircea Trofin   /// Return a higher threshold if \p Call is a hot callsite.
51106408758SMircea Trofin   Optional<int> getHotCallSiteThreshold(CallBase &Call,
51206408758SMircea Trofin                                         BlockFrequencyInfo *CallerBFI);
51306408758SMircea Trofin 
51406408758SMircea Trofin   /// Handle a capped 'int' increment for Cost.
51506408758SMircea Trofin   void addCost(int64_t Inc, int64_t UpperBound = INT_MAX) {
51606408758SMircea Trofin     assert(UpperBound > 0 && UpperBound <= INT_MAX && "invalid upper bound");
51706408758SMircea Trofin     Cost = (int)std::min(UpperBound, Cost + Inc);
51806408758SMircea Trofin   }
51906408758SMircea Trofin 
52006408758SMircea Trofin   void onDisableSROA(AllocaInst *Arg) override {
52106408758SMircea Trofin     auto CostIt = SROAArgCosts.find(Arg);
52206408758SMircea Trofin     if (CostIt == SROAArgCosts.end())
52306408758SMircea Trofin       return;
52406408758SMircea Trofin     addCost(CostIt->second);
52506408758SMircea Trofin     SROACostSavings -= CostIt->second;
52606408758SMircea Trofin     SROACostSavingsLost += CostIt->second;
52706408758SMircea Trofin     SROAArgCosts.erase(CostIt);
52806408758SMircea Trofin   }
52906408758SMircea Trofin 
53006408758SMircea Trofin   void onDisableLoadElimination() override {
53106408758SMircea Trofin     addCost(LoadEliminationCost);
53206408758SMircea Trofin     LoadEliminationCost = 0;
53306408758SMircea Trofin   }
53406408758SMircea Trofin   void onCallPenalty() override { addCost(InlineConstants::CallPenalty); }
53506408758SMircea Trofin   void onCallArgumentSetup(const CallBase &Call) override {
53606408758SMircea Trofin     // Pay the price of the argument setup. We account for the average 1
53706408758SMircea Trofin     // instruction per call argument setup here.
53806408758SMircea Trofin     addCost(Call.arg_size() * InlineConstants::InstrCost);
53906408758SMircea Trofin   }
54006408758SMircea Trofin   void onLoadRelativeIntrinsic() override {
54106408758SMircea Trofin     // This is normally lowered to 4 LLVM instructions.
54206408758SMircea Trofin     addCost(3 * InlineConstants::InstrCost);
54306408758SMircea Trofin   }
54406408758SMircea Trofin   void onLoweredCall(Function *F, CallBase &Call,
54506408758SMircea Trofin                      bool IsIndirectCall) override {
54606408758SMircea Trofin     // We account for the average 1 instruction per call argument setup here.
54706408758SMircea Trofin     addCost(Call.arg_size() * InlineConstants::InstrCost);
54806408758SMircea Trofin 
54906408758SMircea Trofin     // If we have a constant that we are calling as a function, we can peer
55006408758SMircea Trofin     // through it and see the function target. This happens not infrequently
55106408758SMircea Trofin     // during devirtualization and so we want to give it a hefty bonus for
55206408758SMircea Trofin     // inlining, but cap that bonus in the event that inlining wouldn't pan out.
55306408758SMircea Trofin     // Pretend to inline the function, with a custom threshold.
55406408758SMircea Trofin     if (IsIndirectCall && BoostIndirectCalls) {
55506408758SMircea Trofin       auto IndirectCallParams = Params;
55606408758SMircea Trofin       IndirectCallParams.DefaultThreshold =
55706408758SMircea Trofin           InlineConstants::IndirectCallThreshold;
55806408758SMircea Trofin       /// FIXME: if InlineCostCallAnalyzer is derived from, this may need
55906408758SMircea Trofin       /// to instantiate the derived class.
56008e2386dSMircea Trofin       InlineCostCallAnalyzer CA(*F, Call, IndirectCallParams, TTI,
56108e2386dSMircea Trofin                                 GetAssumptionCache, GetBFI, PSI, ORE, false);
5625466597fSMircea Trofin       if (CA.analyze().isSuccess()) {
56306408758SMircea Trofin         // We were able to inline the indirect call! Subtract the cost from the
56406408758SMircea Trofin         // threshold to get the bonus we want to apply, but don't go below zero.
56506408758SMircea Trofin         Cost -= std::max(0, CA.getThreshold() - CA.getCost());
56606408758SMircea Trofin       }
56706408758SMircea Trofin     } else
56806408758SMircea Trofin       // Otherwise simply add the cost for merely making the call.
56906408758SMircea Trofin       addCost(InlineConstants::CallPenalty);
57006408758SMircea Trofin   }
57106408758SMircea Trofin 
57206408758SMircea Trofin   void onFinalizeSwitch(unsigned JumpTableSize,
57306408758SMircea Trofin                         unsigned NumCaseCluster) override {
57406408758SMircea Trofin     // If suitable for a jump table, consider the cost for the table size and
57506408758SMircea Trofin     // branch to destination.
57606408758SMircea Trofin     // Maximum valid cost increased in this function.
57706408758SMircea Trofin     if (JumpTableSize) {
57806408758SMircea Trofin       int64_t JTCost = (int64_t)JumpTableSize * InlineConstants::InstrCost +
57906408758SMircea Trofin                        4 * InlineConstants::InstrCost;
58006408758SMircea Trofin 
58106408758SMircea Trofin       addCost(JTCost, (int64_t)CostUpperBound);
58206408758SMircea Trofin       return;
58306408758SMircea Trofin     }
58406408758SMircea Trofin     // Considering forming a binary search, we should find the number of nodes
58506408758SMircea Trofin     // which is same as the number of comparisons when lowered. For a given
58606408758SMircea Trofin     // number of clusters, n, we can define a recursive function, f(n), to find
58706408758SMircea Trofin     // the number of nodes in the tree. The recursion is :
58806408758SMircea Trofin     // f(n) = 1 + f(n/2) + f (n - n/2), when n > 3,
58906408758SMircea Trofin     // and f(n) = n, when n <= 3.
59006408758SMircea Trofin     // This will lead a binary tree where the leaf should be either f(2) or f(3)
59106408758SMircea Trofin     // when n > 3.  So, the number of comparisons from leaves should be n, while
59206408758SMircea Trofin     // the number of non-leaf should be :
59306408758SMircea Trofin     //   2^(log2(n) - 1) - 1
59406408758SMircea Trofin     //   = 2^log2(n) * 2^-1 - 1
59506408758SMircea Trofin     //   = n / 2 - 1.
59606408758SMircea Trofin     // Considering comparisons from leaf and non-leaf nodes, we can estimate the
59706408758SMircea Trofin     // number of comparisons in a simple closed form :
59806408758SMircea Trofin     //   n + n / 2 - 1 = n * 3 / 2 - 1
59906408758SMircea Trofin     if (NumCaseCluster <= 3) {
60006408758SMircea Trofin       // Suppose a comparison includes one compare and one conditional branch.
60106408758SMircea Trofin       addCost(NumCaseCluster * 2 * InlineConstants::InstrCost);
60206408758SMircea Trofin       return;
60306408758SMircea Trofin     }
60406408758SMircea Trofin 
60506408758SMircea Trofin     int64_t ExpectedNumberOfCompare = 3 * (int64_t)NumCaseCluster / 2 - 1;
60606408758SMircea Trofin     int64_t SwitchCost =
60706408758SMircea Trofin         ExpectedNumberOfCompare * 2 * InlineConstants::InstrCost;
60806408758SMircea Trofin 
60906408758SMircea Trofin     addCost(SwitchCost, (int64_t)CostUpperBound);
61006408758SMircea Trofin   }
61114a16faeSMircea Trofin   void onMissedSimplification() override {
61206408758SMircea Trofin     addCost(InlineConstants::InstrCost);
61306408758SMircea Trofin   }
61406408758SMircea Trofin 
61506408758SMircea Trofin   void onInitializeSROAArg(AllocaInst *Arg) override {
61606408758SMircea Trofin     assert(Arg != nullptr &&
61706408758SMircea Trofin            "Should not initialize SROA costs for null value.");
61806408758SMircea Trofin     SROAArgCosts[Arg] = 0;
61906408758SMircea Trofin   }
62006408758SMircea Trofin 
62106408758SMircea Trofin   void onAggregateSROAUse(AllocaInst *SROAArg) override {
62206408758SMircea Trofin     auto CostIt = SROAArgCosts.find(SROAArg);
62306408758SMircea Trofin     assert(CostIt != SROAArgCosts.end() &&
62406408758SMircea Trofin            "expected this argument to have a cost");
62506408758SMircea Trofin     CostIt->second += InlineConstants::InstrCost;
62606408758SMircea Trofin     SROACostSavings += InlineConstants::InstrCost;
62706408758SMircea Trofin   }
62806408758SMircea Trofin 
6299895c701SKazu Hirata   void onBlockStart(const BasicBlock *BB) override { CostAtBBStart = Cost; }
6309895c701SKazu Hirata 
63106408758SMircea Trofin   void onBlockAnalyzed(const BasicBlock *BB) override {
6329895c701SKazu Hirata     if (CostBenefitAnalysisEnabled) {
6339895c701SKazu Hirata       // Keep track of the static size of live but cold basic blocks.  For now,
6349895c701SKazu Hirata       // we define a cold basic block to be one that's never executed.
6359895c701SKazu Hirata       assert(GetBFI && "GetBFI must be available");
6369895c701SKazu Hirata       BlockFrequencyInfo *BFI = &(GetBFI(F));
6379895c701SKazu Hirata       assert(BFI && "BFI must be available");
6389895c701SKazu Hirata       auto ProfileCount = BFI->getBlockProfileCount(BB);
6399895c701SKazu Hirata       assert(ProfileCount.hasValue());
6409895c701SKazu Hirata       if (ProfileCount.getValue() == 0)
6419895c701SKazu Hirata         ColdSize += Cost - CostAtBBStart;
6429895c701SKazu Hirata     }
6439895c701SKazu Hirata 
64406408758SMircea Trofin     auto *TI = BB->getTerminator();
64506408758SMircea Trofin     // If we had any successors at this point, than post-inlining is likely to
64606408758SMircea Trofin     // have them as well. Note that we assume any basic blocks which existed
64706408758SMircea Trofin     // due to branches or switches which folded above will also fold after
64806408758SMircea Trofin     // inlining.
64906408758SMircea Trofin     if (SingleBB && TI->getNumSuccessors() > 1) {
65006408758SMircea Trofin       // Take off the bonus we applied to the threshold.
65106408758SMircea Trofin       Threshold -= SingleBBBonus;
65206408758SMircea Trofin       SingleBB = false;
65306408758SMircea Trofin     }
65406408758SMircea Trofin   }
6555466597fSMircea Trofin 
656c965fd94SKirill Naumov   void onInstructionAnalysisStart(const Instruction *I) override {
657c965fd94SKirill Naumov     // This function is called to store the initial cost of inlining before
658c965fd94SKirill Naumov     // the given instruction was assessed.
6591022b5ebSKirill Naumov     if (!PrintInstructionComments)
660c965fd94SKirill Naumov       return;
6611022b5ebSKirill Naumov     InstructionCostDetailMap[I].CostBefore = Cost;
6621022b5ebSKirill Naumov     InstructionCostDetailMap[I].ThresholdBefore = Threshold;
663c965fd94SKirill Naumov   }
664c965fd94SKirill Naumov 
665c965fd94SKirill Naumov   void onInstructionAnalysisFinish(const Instruction *I) override {
666c965fd94SKirill Naumov     // This function is called to find new values of cost and threshold after
667c965fd94SKirill Naumov     // the instruction has been assessed.
6681022b5ebSKirill Naumov     if (!PrintInstructionComments)
669c965fd94SKirill Naumov       return;
6701022b5ebSKirill Naumov     InstructionCostDetailMap[I].CostAfter = Cost;
6711022b5ebSKirill Naumov     InstructionCostDetailMap[I].ThresholdAfter = Threshold;
672c965fd94SKirill Naumov   }
673c965fd94SKirill Naumov 
6749895c701SKazu Hirata   bool isCostBenefitAnalysisEnabled() {
6759895c701SKazu Hirata     if (!PSI || !PSI->hasProfileSummary())
6769895c701SKazu Hirata       return false;
6779895c701SKazu Hirata 
6789895c701SKazu Hirata     if (!GetBFI)
6799895c701SKazu Hirata       return false;
6809895c701SKazu Hirata 
681*ef69aa96SKazu Hirata     if (InlineEnableCostBenefitAnalysis.getNumOccurrences()) {
682*ef69aa96SKazu Hirata       // Honor the explicit request from the user.
683*ef69aa96SKazu Hirata       if (!InlineEnableCostBenefitAnalysis)
684*ef69aa96SKazu Hirata         return false;
685*ef69aa96SKazu Hirata     } else {
686*ef69aa96SKazu Hirata       // Otherwise, require instrumentation profile.
687*ef69aa96SKazu Hirata       if (!PSI->hasInstrumentationProfile())
688*ef69aa96SKazu Hirata         return false;
689*ef69aa96SKazu Hirata     }
690*ef69aa96SKazu Hirata 
6919895c701SKazu Hirata     auto *Caller = CandidateCall.getParent()->getParent();
6929895c701SKazu Hirata     if (!Caller->getEntryCount())
6939895c701SKazu Hirata       return false;
6949895c701SKazu Hirata 
6959895c701SKazu Hirata     BlockFrequencyInfo *CallerBFI = &(GetBFI(*Caller));
6969895c701SKazu Hirata     if (!CallerBFI)
6979895c701SKazu Hirata       return false;
6989895c701SKazu Hirata 
6999895c701SKazu Hirata     // For now, limit to hot call site.
7009895c701SKazu Hirata     if (!PSI->isHotCallSite(CandidateCall, CallerBFI))
7019895c701SKazu Hirata       return false;
7029895c701SKazu Hirata 
7039895c701SKazu Hirata     if (!F.getEntryCount())
7049895c701SKazu Hirata       return false;
7059895c701SKazu Hirata 
7069895c701SKazu Hirata     BlockFrequencyInfo *CalleeBFI = &(GetBFI(F));
7079895c701SKazu Hirata     if (!CalleeBFI)
7089895c701SKazu Hirata       return false;
7099895c701SKazu Hirata 
7109895c701SKazu Hirata     return true;
7119895c701SKazu Hirata   }
7129895c701SKazu Hirata 
7139895c701SKazu Hirata   // Determine whether we should inline the given call site, taking into account
7149895c701SKazu Hirata   // both the size cost and the cycle savings.  Return None if we don't have
7159895c701SKazu Hirata   // suficient profiling information to determine.
7169895c701SKazu Hirata   Optional<bool> costBenefitAnalysis() {
7179895c701SKazu Hirata     if (!CostBenefitAnalysisEnabled)
7189895c701SKazu Hirata       return None;
7199895c701SKazu Hirata 
7209895c701SKazu Hirata     // buildInlinerPipeline in the pass builder sets HotCallSiteThreshold to 0
7219895c701SKazu Hirata     // for the prelink phase of the AutoFDO + ThinLTO build.  Honor the logic by
7229895c701SKazu Hirata     // falling back to the cost-based metric.
7239895c701SKazu Hirata     // TODO: Improve this hacky condition.
7249895c701SKazu Hirata     if (Threshold == 0)
7259895c701SKazu Hirata       return None;
7269895c701SKazu Hirata 
7279895c701SKazu Hirata     assert(GetBFI);
7289895c701SKazu Hirata     BlockFrequencyInfo *CalleeBFI = &(GetBFI(F));
7299895c701SKazu Hirata     assert(CalleeBFI);
7309895c701SKazu Hirata 
7319895c701SKazu Hirata     // The cycle savings expressed as the sum of InlineConstants::InstrCost
7329895c701SKazu Hirata     // multiplied by the estimated dynamic count of each instruction we can
7339895c701SKazu Hirata     // avoid.  Savings come from the call site cost, such as argument setup and
7349895c701SKazu Hirata     // the call instruction, as well as the instructions that are folded.
7359895c701SKazu Hirata     //
7369895c701SKazu Hirata     // We use 128-bit APInt here to avoid potential overflow.  This variable
7379895c701SKazu Hirata     // should stay well below 10^^24 (or 2^^80) in practice.  This "worst" case
7389895c701SKazu Hirata     // assumes that we can avoid or fold a billion instructions, each with a
7399895c701SKazu Hirata     // profile count of 10^^15 -- roughly the number of cycles for a 24-hour
7409895c701SKazu Hirata     // period on a 4GHz machine.
7419895c701SKazu Hirata     APInt CycleSavings(128, 0);
7429895c701SKazu Hirata 
7439895c701SKazu Hirata     for (auto &BB : F) {
7449895c701SKazu Hirata       APInt CurrentSavings(128, 0);
7459895c701SKazu Hirata       for (auto &I : BB) {
7469895c701SKazu Hirata         if (BranchInst *BI = dyn_cast<BranchInst>(&I)) {
7479895c701SKazu Hirata           // Count a conditional branch as savings if it becomes unconditional.
7489895c701SKazu Hirata           if (BI->isConditional() &&
7499895c701SKazu Hirata               dyn_cast_or_null<ConstantInt>(
7509895c701SKazu Hirata                   SimplifiedValues.lookup(BI->getCondition()))) {
7519895c701SKazu Hirata             CurrentSavings += InlineConstants::InstrCost;
7529895c701SKazu Hirata           }
7539895c701SKazu Hirata         } else if (Value *V = dyn_cast<Value>(&I)) {
7549895c701SKazu Hirata           // Count an instruction as savings if we can fold it.
7559895c701SKazu Hirata           if (SimplifiedValues.count(V)) {
7569895c701SKazu Hirata             CurrentSavings += InlineConstants::InstrCost;
7579895c701SKazu Hirata           }
7589895c701SKazu Hirata         }
7599895c701SKazu Hirata         // TODO: Consider other forms of savings like switch statements,
7609895c701SKazu Hirata         // indirect calls becoming direct, SROACostSavings, LoadEliminationCost,
7619895c701SKazu Hirata         // etc.
7629895c701SKazu Hirata       }
7639895c701SKazu Hirata 
7649895c701SKazu Hirata       auto ProfileCount = CalleeBFI->getBlockProfileCount(&BB);
7659895c701SKazu Hirata       assert(ProfileCount.hasValue());
7669895c701SKazu Hirata       CurrentSavings *= ProfileCount.getValue();
7679895c701SKazu Hirata       CycleSavings += CurrentSavings;
7689895c701SKazu Hirata     }
7699895c701SKazu Hirata 
7709895c701SKazu Hirata     // Compute the cycle savings per call.
7719895c701SKazu Hirata     auto EntryProfileCount = F.getEntryCount();
7729895c701SKazu Hirata     assert(EntryProfileCount.hasValue());
7739895c701SKazu Hirata     auto EntryCount = EntryProfileCount.getCount();
7749895c701SKazu Hirata     CycleSavings += EntryCount / 2;
7759895c701SKazu Hirata     CycleSavings = CycleSavings.udiv(EntryCount);
7769895c701SKazu Hirata 
7779895c701SKazu Hirata     // Compute the total savings for the call site.
7789895c701SKazu Hirata     auto *CallerBB = CandidateCall.getParent();
7799895c701SKazu Hirata     BlockFrequencyInfo *CallerBFI = &(GetBFI(*(CallerBB->getParent())));
7809895c701SKazu Hirata     CycleSavings += getCallsiteCost(this->CandidateCall, DL);
7819895c701SKazu Hirata     CycleSavings *= CallerBFI->getBlockProfileCount(CallerBB).getValue();
7829895c701SKazu Hirata 
7839895c701SKazu Hirata     // Remove the cost of the cold basic blocks.
7849895c701SKazu Hirata     int Size = Cost - ColdSize;
7859895c701SKazu Hirata 
7869895c701SKazu Hirata     // Allow tiny callees to be inlined regardless of whether they meet the
7879895c701SKazu Hirata     // savings threshold.
7889895c701SKazu Hirata     Size = Size > InlineSizeAllowance ? Size - InlineSizeAllowance : 1;
7899895c701SKazu Hirata 
7909895c701SKazu Hirata     // Return true if the savings justify the cost of inlining.  Specifically,
7919895c701SKazu Hirata     // we evaluate the following inequality:
7929895c701SKazu Hirata     //
7939895c701SKazu Hirata     //  CycleSavings      PSI->getOrCompHotCountThreshold()
7949895c701SKazu Hirata     // -------------- >= -----------------------------------
7959895c701SKazu Hirata     //       Size              InlineSavingsMultiplier
7969895c701SKazu Hirata     //
7979895c701SKazu Hirata     // Note that the left hand side is specific to a call site.  The right hand
7989895c701SKazu Hirata     // side is a constant for the entire executable.
7999895c701SKazu Hirata     APInt LHS = CycleSavings;
8009895c701SKazu Hirata     LHS *= InlineSavingsMultiplier;
8019895c701SKazu Hirata     APInt RHS(128, PSI->getOrCompHotCountThreshold());
8029895c701SKazu Hirata     RHS *= Size;
8039895c701SKazu Hirata     return LHS.uge(RHS);
8049895c701SKazu Hirata   }
8059895c701SKazu Hirata 
80606408758SMircea Trofin   InlineResult finalizeAnalysis() override {
80706408758SMircea Trofin     // Loops generally act a lot like calls in that they act like barriers to
80806408758SMircea Trofin     // movement, require a certain amount of setup, etc. So when optimising for
80906408758SMircea Trofin     // size, we penalise any call sites that perform loops. We do this after all
81006408758SMircea Trofin     // other costs here, so will likely only be dealing with relatively small
81106408758SMircea Trofin     // functions (and hence DT and LI will hopefully be cheap).
81206408758SMircea Trofin     auto *Caller = CandidateCall.getFunction();
81306408758SMircea Trofin     if (Caller->hasMinSize()) {
81406408758SMircea Trofin       DominatorTree DT(F);
81506408758SMircea Trofin       LoopInfo LI(DT);
81606408758SMircea Trofin       int NumLoops = 0;
81706408758SMircea Trofin       for (Loop *L : LI) {
81806408758SMircea Trofin         // Ignore loops that will not be executed
81906408758SMircea Trofin         if (DeadBlocks.count(L->getHeader()))
82006408758SMircea Trofin           continue;
82106408758SMircea Trofin         NumLoops++;
82206408758SMircea Trofin       }
82306408758SMircea Trofin       addCost(NumLoops * InlineConstants::CallPenalty);
82406408758SMircea Trofin     }
82506408758SMircea Trofin 
82606408758SMircea Trofin     // We applied the maximum possible vector bonus at the beginning. Now,
82706408758SMircea Trofin     // subtract the excess bonus, if any, from the Threshold before
82806408758SMircea Trofin     // comparing against Cost.
82906408758SMircea Trofin     if (NumVectorInstructions <= NumInstructions / 10)
83006408758SMircea Trofin       Threshold -= VectorBonus;
83106408758SMircea Trofin     else if (NumVectorInstructions <= NumInstructions / 2)
83206408758SMircea Trofin       Threshold -= VectorBonus / 2;
83306408758SMircea Trofin 
8349895c701SKazu Hirata     if (auto Result = costBenefitAnalysis()) {
8359895c701SKazu Hirata       if (Result.getValue())
8369895c701SKazu Hirata         return InlineResult::success();
8379895c701SKazu Hirata       else
8389895c701SKazu Hirata         return InlineResult::failure("Cost over threshold.");
8399895c701SKazu Hirata     }
8409895c701SKazu Hirata 
8418a4013edSMircea Trofin     if (IgnoreThreshold || Cost < std::max(1, Threshold))
8425466597fSMircea Trofin       return InlineResult::success();
8435466597fSMircea Trofin     return InlineResult::failure("Cost over threshold.");
84406408758SMircea Trofin   }
84506408758SMircea Trofin   bool shouldStop() override {
84606408758SMircea Trofin     // Bail out the moment we cross the threshold. This means we'll under-count
84706408758SMircea Trofin     // the cost, but only when undercounting doesn't matter.
8488a4013edSMircea Trofin     return !IgnoreThreshold && Cost >= Threshold && !ComputeFullInlineCost;
84906408758SMircea Trofin   }
85006408758SMircea Trofin 
85106408758SMircea Trofin   void onLoadEliminationOpportunity() override {
85206408758SMircea Trofin     LoadEliminationCost += InlineConstants::InstrCost;
85306408758SMircea Trofin   }
85406408758SMircea Trofin 
85506408758SMircea Trofin   InlineResult onAnalysisStart() override {
85606408758SMircea Trofin     // Perform some tweaks to the cost and threshold based on the direct
85706408758SMircea Trofin     // callsite information.
85806408758SMircea Trofin 
85906408758SMircea Trofin     // We want to more aggressively inline vector-dense kernels, so up the
86006408758SMircea Trofin     // threshold, and we'll lower it if the % of vector instructions gets too
86106408758SMircea Trofin     // low. Note that these bonuses are some what arbitrary and evolved over
86206408758SMircea Trofin     // time by accident as much as because they are principled bonuses.
86306408758SMircea Trofin     //
86406408758SMircea Trofin     // FIXME: It would be nice to remove all such bonuses. At least it would be
86506408758SMircea Trofin     // nice to base the bonus values on something more scientific.
86606408758SMircea Trofin     assert(NumInstructions == 0);
86706408758SMircea Trofin     assert(NumVectorInstructions == 0);
86806408758SMircea Trofin 
86906408758SMircea Trofin     // Update the threshold based on callsite properties
87006408758SMircea Trofin     updateThreshold(CandidateCall, F);
87106408758SMircea Trofin 
87206408758SMircea Trofin     // While Threshold depends on commandline options that can take negative
87306408758SMircea Trofin     // values, we want to enforce the invariant that the computed threshold and
87406408758SMircea Trofin     // bonuses are non-negative.
87506408758SMircea Trofin     assert(Threshold >= 0);
87606408758SMircea Trofin     assert(SingleBBBonus >= 0);
87706408758SMircea Trofin     assert(VectorBonus >= 0);
87806408758SMircea Trofin 
87906408758SMircea Trofin     // Speculatively apply all possible bonuses to Threshold. If cost exceeds
88006408758SMircea Trofin     // this Threshold any time, and cost cannot decrease, we can stop processing
88106408758SMircea Trofin     // the rest of the function body.
88206408758SMircea Trofin     Threshold += (SingleBBBonus + VectorBonus);
88306408758SMircea Trofin 
88406408758SMircea Trofin     // Give out bonuses for the callsite, as the instructions setting them up
88506408758SMircea Trofin     // will be gone after inlining.
88606408758SMircea Trofin     addCost(-getCallsiteCost(this->CandidateCall, DL));
88706408758SMircea Trofin 
88806408758SMircea Trofin     // If this function uses the coldcc calling convention, prefer not to inline
88906408758SMircea Trofin     // it.
89006408758SMircea Trofin     if (F.getCallingConv() == CallingConv::Cold)
89106408758SMircea Trofin       Cost += InlineConstants::ColdccPenalty;
89206408758SMircea Trofin 
89306408758SMircea Trofin     // Check if we're done. This can happen due to bonuses and penalties.
89406408758SMircea Trofin     if (Cost >= Threshold && !ComputeFullInlineCost)
8955466597fSMircea Trofin       return InlineResult::failure("high cost");
89606408758SMircea Trofin 
8975466597fSMircea Trofin     return InlineResult::success();
89806408758SMircea Trofin   }
89906408758SMircea Trofin 
90006408758SMircea Trofin public:
90106408758SMircea Trofin   InlineCostCallAnalyzer(
90208e2386dSMircea Trofin       Function &Callee, CallBase &Call, const InlineParams &Params,
90306408758SMircea Trofin       const TargetTransformInfo &TTI,
90408e2386dSMircea Trofin       function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
90508e2386dSMircea Trofin       function_ref<BlockFrequencyInfo &(Function &)> GetBFI = nullptr,
90608e2386dSMircea Trofin       ProfileSummaryInfo *PSI = nullptr,
90708e2386dSMircea Trofin       OptimizationRemarkEmitter *ORE = nullptr, bool BoostIndirect = true,
9088a4013edSMircea Trofin       bool IgnoreThreshold = false)
90908e2386dSMircea Trofin       : CallAnalyzer(Callee, Call, TTI, GetAssumptionCache, GetBFI, PSI, ORE),
91006408758SMircea Trofin         ComputeFullInlineCost(OptComputeFullInlineCost ||
91165cd3cbbSKazu Hirata                               Params.ComputeFullInlineCost || ORE ||
91265cd3cbbSKazu Hirata                               isCostBenefitAnalysisEnabled()),
91306408758SMircea Trofin         Params(Params), Threshold(Params.DefaultThreshold),
9141022b5ebSKirill Naumov         BoostIndirectCalls(BoostIndirect), IgnoreThreshold(IgnoreThreshold),
9159895c701SKazu Hirata         CostBenefitAnalysisEnabled(isCostBenefitAnalysisEnabled()),
9161022b5ebSKirill Naumov         Writer(this) {}
917c965fd94SKirill Naumov 
9181022b5ebSKirill Naumov   /// Annotation Writer for instruction details
9191022b5ebSKirill Naumov   InlineCostAnnotationWriter Writer;
920c965fd94SKirill Naumov 
92106408758SMircea Trofin   void dump();
92206408758SMircea Trofin 
923ca899bf9SKirill Naumov   // Prints the same analysis as dump(), but its definition is not dependent
924ca899bf9SKirill Naumov   // on the build.
925ca899bf9SKirill Naumov   void print();
926ca899bf9SKirill Naumov 
9271022b5ebSKirill Naumov   Optional<InstructionCostDetail> getCostDetails(const Instruction *I) {
9281022b5ebSKirill Naumov     if (InstructionCostDetailMap.find(I) != InstructionCostDetailMap.end())
9291022b5ebSKirill Naumov       return InstructionCostDetailMap[I];
9301022b5ebSKirill Naumov     return None;
9311022b5ebSKirill Naumov   }
9321022b5ebSKirill Naumov 
93306408758SMircea Trofin   virtual ~InlineCostCallAnalyzer() {}
93406408758SMircea Trofin   int getThreshold() { return Threshold; }
93506408758SMircea Trofin   int getCost() { return Cost; }
93606408758SMircea Trofin };
9377adc3a2bSChandler Carruth } // namespace
9387adc3a2bSChandler Carruth 
9395f8f34e4SAdrian Prantl /// Test whether the given value is an Alloca-derived function argument.
9407adc3a2bSChandler Carruth bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
9417adc3a2bSChandler Carruth   return SROAArgValues.count(V);
9427adc3a2bSChandler Carruth }
9437adc3a2bSChandler Carruth 
94406408758SMircea Trofin void CallAnalyzer::disableSROAForArg(AllocaInst *SROAArg) {
94506408758SMircea Trofin   onDisableSROA(SROAArg);
9462e42cc7aSMircea Trofin   EnabledSROAAllocas.erase(SROAArg);
947338a6016SMircea Trofin   disableLoadElimination();
948338a6016SMircea Trofin }
949c965fd94SKirill Naumov 
9501022b5ebSKirill Naumov void InlineCostAnnotationWriter::emitInstructionAnnot(const Instruction *I,
9510383253cSKirill Naumov                                                 formatted_raw_ostream &OS) {
952c965fd94SKirill Naumov   // The cost of inlining of the given instruction is printed always.
953c965fd94SKirill Naumov   // The threshold delta is printed only when it is non-zero. It happens
954c965fd94SKirill Naumov   // when we decided to give a bonus at a particular instruction.
9551022b5ebSKirill Naumov   Optional<InstructionCostDetail> Record = ICCA->getCostDetails(I);
9561022b5ebSKirill Naumov   if (!Record)
9571022b5ebSKirill Naumov     OS << "; No analysis for the instruction";
9581022b5ebSKirill Naumov   else {
9591022b5ebSKirill Naumov     OS << "; cost before = " << Record->CostBefore
9601022b5ebSKirill Naumov        << ", cost after = " << Record->CostAfter
9611022b5ebSKirill Naumov        << ", threshold before = " << Record->ThresholdBefore
9621022b5ebSKirill Naumov        << ", threshold after = " << Record->ThresholdAfter << ", ";
9631022b5ebSKirill Naumov     OS << "cost delta = " << Record->getCostDelta();
9641022b5ebSKirill Naumov     if (Record->hasThresholdChanged())
9651022b5ebSKirill Naumov       OS << ", threshold delta = " << Record->getThresholdDelta();
9660383253cSKirill Naumov   }
9677f094f7fSKirill Naumov   auto C = ICCA->getSimplifiedValue(const_cast<Instruction *>(I));
9687f094f7fSKirill Naumov   if (C) {
9697f094f7fSKirill Naumov     OS << ", simplified to ";
9707f094f7fSKirill Naumov     C.getValue()->print(OS, true);
9717f094f7fSKirill Naumov   }
972c965fd94SKirill Naumov   OS << "\n";
973c965fd94SKirill Naumov }
974c965fd94SKirill Naumov 
9755f8f34e4SAdrian Prantl /// If 'V' maps to a SROA candidate, disable SROA for it.
9767adc3a2bSChandler Carruth void CallAnalyzer::disableSROA(Value *V) {
97706408758SMircea Trofin   if (auto *SROAArg = getSROAArgForValueOrNull(V)) {
97806408758SMircea Trofin     disableSROAForArg(SROAArg);
979338a6016SMircea Trofin   }
9807adc3a2bSChandler Carruth }
9817adc3a2bSChandler Carruth 
982a4461515SHaicheng Wu void CallAnalyzer::disableLoadElimination() {
983a4461515SHaicheng Wu   if (EnableLoadElimination) {
98406408758SMircea Trofin     onDisableLoadElimination();
985a4461515SHaicheng Wu     EnableLoadElimination = false;
986a4461515SHaicheng Wu   }
987a4461515SHaicheng Wu }
988a4461515SHaicheng Wu 
9895f8f34e4SAdrian Prantl /// Accumulate a constant GEP offset into an APInt if possible.
9907adc3a2bSChandler Carruth ///
9917adc3a2bSChandler Carruth /// Returns false if unable to compute the offset for any reason. Respects any
9927adc3a2bSChandler Carruth /// simplified values known during the analysis of this callsite.
9937adc3a2bSChandler Carruth bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
994945b7e5aSElena Demikhovsky   unsigned IntPtrWidth = DL.getIndexTypeSizeInBits(GEP.getType());
9957adc3a2bSChandler Carruth   assert(IntPtrWidth == Offset.getBitWidth());
9967adc3a2bSChandler Carruth 
9977adc3a2bSChandler Carruth   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
9987adc3a2bSChandler Carruth        GTI != GTE; ++GTI) {
9997adc3a2bSChandler Carruth     ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
10007adc3a2bSChandler Carruth     if (!OpC)
10017adc3a2bSChandler Carruth       if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
10027adc3a2bSChandler Carruth         OpC = dyn_cast<ConstantInt>(SimpleOp);
10037adc3a2bSChandler Carruth     if (!OpC)
10047adc3a2bSChandler Carruth       return false;
1005567556aaSChad Rosier     if (OpC->isZero())
1006567556aaSChad Rosier       continue;
10077adc3a2bSChandler Carruth 
10087adc3a2bSChandler Carruth     // Handle a struct index, which adds its field offset to the pointer.
1009ab85225bSPeter Collingbourne     if (StructType *STy = GTI.getStructTypeOrNull()) {
10107adc3a2bSChandler Carruth       unsigned ElementIdx = OpC->getZExtValue();
10117adc3a2bSChandler Carruth       const StructLayout *SL = DL.getStructLayout(STy);
10127adc3a2bSChandler Carruth       Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
10137adc3a2bSChandler Carruth       continue;
10147adc3a2bSChandler Carruth     }
10157adc3a2bSChandler Carruth 
10167adc3a2bSChandler Carruth     APInt TypeSize(IntPtrWidth, DL.getTypeAllocSize(GTI.getIndexedType()));
10177adc3a2bSChandler Carruth     Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
10187adc3a2bSChandler Carruth   }
10197adc3a2bSChandler Carruth   return true;
10207adc3a2bSChandler Carruth }
10217adc3a2bSChandler Carruth 
10225f8f34e4SAdrian Prantl /// Use TTI to check whether a GEP is free.
1023201b191bSHaicheng Wu ///
1024201b191bSHaicheng Wu /// Respects any simplified values known during the analysis of this callsite.
1025201b191bSHaicheng Wu bool CallAnalyzer::isGEPFree(GetElementPtrInst &GEP) {
102661c1bd5aSEvgeny Astigeevich   SmallVector<Value *, 4> Operands;
102761c1bd5aSEvgeny Astigeevich   Operands.push_back(GEP.getOperand(0));
102891aff1d8SNick Desaulniers   for (const Use &Op : GEP.indices())
102991aff1d8SNick Desaulniers     if (Constant *SimpleOp = SimplifiedValues.lookup(Op))
103061c1bd5aSEvgeny Astigeevich       Operands.push_back(SimpleOp);
1031201b191bSHaicheng Wu     else
103291aff1d8SNick Desaulniers       Operands.push_back(Op);
1033e9c9329aSSam Parker   return TargetTransformInfo::TCC_Free ==
10340383253cSKirill Naumov          TTI.getUserCost(&GEP, Operands,
10350383253cSKirill Naumov                          TargetTransformInfo::TCK_SizeAndLatency);
1036201b191bSHaicheng Wu }
1037201b191bSHaicheng Wu 
10387adc3a2bSChandler Carruth bool CallAnalyzer::visitAlloca(AllocaInst &I) {
10397adc3a2bSChandler Carruth   // Check whether inlining will turn a dynamic alloca into a static
10400f153424SSanjay Patel   // alloca and handle that case.
10417adc3a2bSChandler Carruth   if (I.isArrayAllocation()) {
10420f153424SSanjay Patel     Constant *Size = SimplifiedValues.lookup(I.getArraySize());
10430f153424SSanjay Patel     if (auto *AllocSize = dyn_cast_or_null<ConstantInt>(Size)) {
1044090c108dSAmara Emerson       // Sometimes a dynamic alloca could be converted into a static alloca
1045090c108dSAmara Emerson       // after this constant prop, and become a huge static alloca on an
1046090c108dSAmara Emerson       // unconditional CFG path. Avoid inlining if this is going to happen above
1047090c108dSAmara Emerson       // a threshold.
1048090c108dSAmara Emerson       // FIXME: If the threshold is removed or lowered too much, we could end up
1049090c108dSAmara Emerson       // being too pessimistic and prevent inlining non-problematic code. This
1050090c108dSAmara Emerson       // could result in unintended perf regressions. A better overall strategy
1051090c108dSAmara Emerson       // is needed to track stack usage during inlining.
10527adc3a2bSChandler Carruth       Type *Ty = I.getAllocatedType();
105322eb80a1SEaswaran Raman       AllocatedSize = SaturatingMultiplyAdd(
10542ccde3c9SCullen Rhodes           AllocSize->getLimitedValue(), DL.getTypeAllocSize(Ty).getKnownMinSize(),
1055b302561bSGraham Hunter           AllocatedSize);
1056090c108dSAmara Emerson       if (AllocatedSize > InlineConstants::MaxSimplifiedDynamicAllocaToInline) {
1057090c108dSAmara Emerson         HasDynamicAlloca = true;
1058090c108dSAmara Emerson         return false;
1059090c108dSAmara Emerson       }
10607adc3a2bSChandler Carruth       return Base::visitAlloca(I);
10617adc3a2bSChandler Carruth     }
10627adc3a2bSChandler Carruth   }
10637adc3a2bSChandler Carruth 
10647adc3a2bSChandler Carruth   // Accumulate the allocated size.
10657adc3a2bSChandler Carruth   if (I.isStaticAlloca()) {
10667adc3a2bSChandler Carruth     Type *Ty = I.getAllocatedType();
10675a956c85SMircea Trofin     AllocatedSize =
10682ccde3c9SCullen Rhodes         SaturatingAdd(DL.getTypeAllocSize(Ty).getKnownMinSize(), AllocatedSize);
10697adc3a2bSChandler Carruth   }
10707adc3a2bSChandler Carruth 
10717adc3a2bSChandler Carruth   // We will happily inline static alloca instructions.
10727adc3a2bSChandler Carruth   if (I.isStaticAlloca())
10737adc3a2bSChandler Carruth     return Base::visitAlloca(I);
10747adc3a2bSChandler Carruth 
10757adc3a2bSChandler Carruth   // FIXME: This is overly conservative. Dynamic allocas are inefficient for
10767adc3a2bSChandler Carruth   // a variety of reasons, and so we would like to not inline them into
10777adc3a2bSChandler Carruth   // functions which don't currently have a dynamic alloca. This simply
10787adc3a2bSChandler Carruth   // disables inlining altogether in the presence of a dynamic alloca.
10797adc3a2bSChandler Carruth   HasDynamicAlloca = true;
10807adc3a2bSChandler Carruth   return false;
10817adc3a2bSChandler Carruth }
10827adc3a2bSChandler Carruth 
10837adc3a2bSChandler Carruth bool CallAnalyzer::visitPHI(PHINode &I) {
10847adc3a2bSChandler Carruth   // FIXME: We need to propagate SROA *disabling* through phi nodes, even
10857adc3a2bSChandler Carruth   // though we don't want to propagate it's bonuses. The idea is to disable
10867adc3a2bSChandler Carruth   // SROA if it *might* be used in an inappropriate manner.
10877adc3a2bSChandler Carruth 
10887adc3a2bSChandler Carruth   // Phi nodes are always zero-cost.
108977f32994SBjorn Pettersson   // FIXME: Pointer sizes may differ between different address spaces, so do we
109077f32994SBjorn Pettersson   // need to use correct address space in the call to getPointerSizeInBits here?
109177f32994SBjorn Pettersson   // Or could we skip the getPointerSizeInBits call completely? As far as I can
109277f32994SBjorn Pettersson   // see the ZeroOffset is used as a dummy value, so we can probably use any
109377f32994SBjorn Pettersson   // bit width for the ZeroOffset?
109477f32994SBjorn Pettersson   APInt ZeroOffset = APInt::getNullValue(DL.getPointerSizeInBits(0));
10953739e14aSHaicheng Wu   bool CheckSROA = I.getType()->isPointerTy();
10963739e14aSHaicheng Wu 
10973739e14aSHaicheng Wu   // Track the constant or pointer with constant offset we've seen so far.
10983739e14aSHaicheng Wu   Constant *FirstC = nullptr;
10993739e14aSHaicheng Wu   std::pair<Value *, APInt> FirstBaseAndOffset = {nullptr, ZeroOffset};
11003739e14aSHaicheng Wu   Value *FirstV = nullptr;
11013739e14aSHaicheng Wu 
11023739e14aSHaicheng Wu   for (unsigned i = 0, e = I.getNumIncomingValues(); i != e; ++i) {
11033739e14aSHaicheng Wu     BasicBlock *Pred = I.getIncomingBlock(i);
11043739e14aSHaicheng Wu     // If the incoming block is dead, skip the incoming block.
11053739e14aSHaicheng Wu     if (DeadBlocks.count(Pred))
11063739e14aSHaicheng Wu       continue;
11073739e14aSHaicheng Wu     // If the parent block of phi is not the known successor of the incoming
11083739e14aSHaicheng Wu     // block, skip the incoming block.
11093739e14aSHaicheng Wu     BasicBlock *KnownSuccessor = KnownSuccessors[Pred];
11103739e14aSHaicheng Wu     if (KnownSuccessor && KnownSuccessor != I.getParent())
11113739e14aSHaicheng Wu       continue;
11123739e14aSHaicheng Wu 
11133739e14aSHaicheng Wu     Value *V = I.getIncomingValue(i);
11143739e14aSHaicheng Wu     // If the incoming value is this phi itself, skip the incoming value.
11153739e14aSHaicheng Wu     if (&I == V)
11163739e14aSHaicheng Wu       continue;
11173739e14aSHaicheng Wu 
11183739e14aSHaicheng Wu     Constant *C = dyn_cast<Constant>(V);
11193739e14aSHaicheng Wu     if (!C)
11203739e14aSHaicheng Wu       C = SimplifiedValues.lookup(V);
11213739e14aSHaicheng Wu 
11223739e14aSHaicheng Wu     std::pair<Value *, APInt> BaseAndOffset = {nullptr, ZeroOffset};
11233739e14aSHaicheng Wu     if (!C && CheckSROA)
11243739e14aSHaicheng Wu       BaseAndOffset = ConstantOffsetPtrs.lookup(V);
11253739e14aSHaicheng Wu 
11263739e14aSHaicheng Wu     if (!C && !BaseAndOffset.first)
11273739e14aSHaicheng Wu       // The incoming value is neither a constant nor a pointer with constant
11283739e14aSHaicheng Wu       // offset, exit early.
11293739e14aSHaicheng Wu       return true;
11303739e14aSHaicheng Wu 
11313739e14aSHaicheng Wu     if (FirstC) {
11323739e14aSHaicheng Wu       if (FirstC == C)
11333739e14aSHaicheng Wu         // If we've seen a constant incoming value before and it is the same
11343739e14aSHaicheng Wu         // constant we see this time, continue checking the next incoming value.
11353739e14aSHaicheng Wu         continue;
11363739e14aSHaicheng Wu       // Otherwise early exit because we either see a different constant or saw
11373739e14aSHaicheng Wu       // a constant before but we have a pointer with constant offset this time.
11383739e14aSHaicheng Wu       return true;
11393739e14aSHaicheng Wu     }
11403739e14aSHaicheng Wu 
11413739e14aSHaicheng Wu     if (FirstV) {
11423739e14aSHaicheng Wu       // The same logic as above, but check pointer with constant offset here.
11433739e14aSHaicheng Wu       if (FirstBaseAndOffset == BaseAndOffset)
11443739e14aSHaicheng Wu         continue;
11453739e14aSHaicheng Wu       return true;
11463739e14aSHaicheng Wu     }
11473739e14aSHaicheng Wu 
11483739e14aSHaicheng Wu     if (C) {
11493739e14aSHaicheng Wu       // This is the 1st time we've seen a constant, record it.
11503739e14aSHaicheng Wu       FirstC = C;
11513739e14aSHaicheng Wu       continue;
11523739e14aSHaicheng Wu     }
11533739e14aSHaicheng Wu 
11543739e14aSHaicheng Wu     // The remaining case is that this is the 1st time we've seen a pointer with
11553739e14aSHaicheng Wu     // constant offset, record it.
11563739e14aSHaicheng Wu     FirstV = V;
11573739e14aSHaicheng Wu     FirstBaseAndOffset = BaseAndOffset;
11583739e14aSHaicheng Wu   }
11593739e14aSHaicheng Wu 
11603739e14aSHaicheng Wu   // Check if we can map phi to a constant.
11613739e14aSHaicheng Wu   if (FirstC) {
11623739e14aSHaicheng Wu     SimplifiedValues[&I] = FirstC;
11633739e14aSHaicheng Wu     return true;
11643739e14aSHaicheng Wu   }
11653739e14aSHaicheng Wu 
11663739e14aSHaicheng Wu   // Check if we can map phi to a pointer with constant offset.
11673739e14aSHaicheng Wu   if (FirstBaseAndOffset.first) {
11683739e14aSHaicheng Wu     ConstantOffsetPtrs[&I] = FirstBaseAndOffset;
11693739e14aSHaicheng Wu 
117006408758SMircea Trofin     if (auto *SROAArg = getSROAArgForValueOrNull(FirstV))
11713739e14aSHaicheng Wu       SROAArgValues[&I] = SROAArg;
11723739e14aSHaicheng Wu   }
11733739e14aSHaicheng Wu 
11747adc3a2bSChandler Carruth   return true;
11757adc3a2bSChandler Carruth }
11767adc3a2bSChandler Carruth 
11775f8f34e4SAdrian Prantl /// Check we can fold GEPs of constant-offset call site argument pointers.
1178d3558b5dSEvgeny Astigeevich /// This requires target data and inbounds GEPs.
1179d3558b5dSEvgeny Astigeevich ///
1180d3558b5dSEvgeny Astigeevich /// \return true if the specified GEP can be folded.
1181d3558b5dSEvgeny Astigeevich bool CallAnalyzer::canFoldInboundsGEP(GetElementPtrInst &I) {
1182d3558b5dSEvgeny Astigeevich   // Check if we have a base + offset for the pointer.
1183d3558b5dSEvgeny Astigeevich   std::pair<Value *, APInt> BaseAndOffset =
1184d3558b5dSEvgeny Astigeevich       ConstantOffsetPtrs.lookup(I.getPointerOperand());
1185d3558b5dSEvgeny Astigeevich   if (!BaseAndOffset.first)
1186d3558b5dSEvgeny Astigeevich     return false;
1187d3558b5dSEvgeny Astigeevich 
1188d3558b5dSEvgeny Astigeevich   // Check if the offset of this GEP is constant, and if so accumulate it
1189d3558b5dSEvgeny Astigeevich   // into Offset.
1190d3558b5dSEvgeny Astigeevich   if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second))
1191d3558b5dSEvgeny Astigeevich     return false;
1192d3558b5dSEvgeny Astigeevich 
1193d3558b5dSEvgeny Astigeevich   // Add the result as a new mapping to Base + Offset.
1194d3558b5dSEvgeny Astigeevich   ConstantOffsetPtrs[&I] = BaseAndOffset;
1195d3558b5dSEvgeny Astigeevich 
1196d3558b5dSEvgeny Astigeevich   return true;
1197d3558b5dSEvgeny Astigeevich }
1198d3558b5dSEvgeny Astigeevich 
11997adc3a2bSChandler Carruth bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
120006408758SMircea Trofin   auto *SROAArg = getSROAArgForValueOrNull(I.getPointerOperand());
12017adc3a2bSChandler Carruth 
1202a8b9cdc9SEaswaran Raman   // Lambda to check whether a GEP's indices are all constant.
1203a8b9cdc9SEaswaran Raman   auto IsGEPOffsetConstant = [&](GetElementPtrInst &GEP) {
120491aff1d8SNick Desaulniers     for (const Use &Op : GEP.indices())
120591aff1d8SNick Desaulniers       if (!isa<Constant>(Op) && !SimplifiedValues.lookup(Op))
1206a8b9cdc9SEaswaran Raman         return false;
1207a8b9cdc9SEaswaran Raman     return true;
1208a8b9cdc9SEaswaran Raman   };
1209a8b9cdc9SEaswaran Raman 
1210d48c7859SKirill Naumov   if (!DisableGEPConstOperand)
1211d48c7859SKirill Naumov     if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1212d48c7859SKirill Naumov         SmallVector<Constant *, 2> Indices;
1213d48c7859SKirill Naumov         for (unsigned int Index = 1 ; Index < COps.size() ; ++Index)
1214d48c7859SKirill Naumov             Indices.push_back(COps[Index]);
1215d48c7859SKirill Naumov         return ConstantExpr::getGetElementPtr(I.getSourceElementType(), COps[0],
1216d48c7859SKirill Naumov                                               Indices, I.isInBounds());
1217d48c7859SKirill Naumov         }))
1218d48c7859SKirill Naumov       return true;
1219d48c7859SKirill Naumov 
1220d3558b5dSEvgeny Astigeevich   if ((I.isInBounds() && canFoldInboundsGEP(I)) || IsGEPOffsetConstant(I)) {
122106408758SMircea Trofin     if (SROAArg)
12227adc3a2bSChandler Carruth       SROAArgValues[&I] = SROAArg;
12237adc3a2bSChandler Carruth 
12247adc3a2bSChandler Carruth     // Constant GEPs are modeled as free.
12257adc3a2bSChandler Carruth     return true;
12267adc3a2bSChandler Carruth   }
12277adc3a2bSChandler Carruth 
12287adc3a2bSChandler Carruth   // Variable GEPs will require math and will disable SROA.
122906408758SMircea Trofin   if (SROAArg)
123006408758SMircea Trofin     disableSROAForArg(SROAArg);
1231201b191bSHaicheng Wu   return isGEPFree(I);
12327adc3a2bSChandler Carruth }
12337adc3a2bSChandler Carruth 
1234617f6364SEaswaran Raman /// Simplify \p I if its operands are constants and update SimplifiedValues.
1235617f6364SEaswaran Raman /// \p Evaluate is a callable specific to instruction type that evaluates the
1236617f6364SEaswaran Raman /// instruction when all the operands are constants.
1237617f6364SEaswaran Raman template <typename Callable>
1238617f6364SEaswaran Raman bool CallAnalyzer::simplifyInstruction(Instruction &I, Callable Evaluate) {
1239617f6364SEaswaran Raman   SmallVector<Constant *, 2> COps;
1240617f6364SEaswaran Raman   for (Value *Op : I.operands()) {
1241617f6364SEaswaran Raman     Constant *COp = dyn_cast<Constant>(Op);
12427adc3a2bSChandler Carruth     if (!COp)
1243617f6364SEaswaran Raman       COp = SimplifiedValues.lookup(Op);
1244617f6364SEaswaran Raman     if (!COp)
1245617f6364SEaswaran Raman       return false;
1246617f6364SEaswaran Raman     COps.push_back(COp);
1247617f6364SEaswaran Raman   }
1248617f6364SEaswaran Raman   auto *C = Evaluate(COps);
1249617f6364SEaswaran Raman   if (!C)
1250617f6364SEaswaran Raman     return false;
12517adc3a2bSChandler Carruth   SimplifiedValues[&I] = C;
12527adc3a2bSChandler Carruth   return true;
12537adc3a2bSChandler Carruth }
12547adc3a2bSChandler Carruth 
1255617f6364SEaswaran Raman bool CallAnalyzer::visitBitCast(BitCastInst &I) {
1256617f6364SEaswaran Raman   // Propagate constants through bitcasts.
1257617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1258617f6364SEaswaran Raman         return ConstantExpr::getBitCast(COps[0], I.getType());
1259617f6364SEaswaran Raman       }))
1260617f6364SEaswaran Raman     return true;
1261617f6364SEaswaran Raman 
12627adc3a2bSChandler Carruth   // Track base/offsets through casts
1263567556aaSChad Rosier   std::pair<Value *, APInt> BaseAndOffset =
1264567556aaSChad Rosier       ConstantOffsetPtrs.lookup(I.getOperand(0));
12657adc3a2bSChandler Carruth   // Casts don't change the offset, just wrap it up.
12667adc3a2bSChandler Carruth   if (BaseAndOffset.first)
12677adc3a2bSChandler Carruth     ConstantOffsetPtrs[&I] = BaseAndOffset;
12687adc3a2bSChandler Carruth 
12697adc3a2bSChandler Carruth   // Also look for SROA candidates here.
127006408758SMircea Trofin   if (auto *SROAArg = getSROAArgForValueOrNull(I.getOperand(0)))
12717adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
12727adc3a2bSChandler Carruth 
12737adc3a2bSChandler Carruth   // Bitcasts are always zero cost.
12747adc3a2bSChandler Carruth   return true;
12757adc3a2bSChandler Carruth }
12767adc3a2bSChandler Carruth 
12777adc3a2bSChandler Carruth bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
12787adc3a2bSChandler Carruth   // Propagate constants through ptrtoint.
1279617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1280617f6364SEaswaran Raman         return ConstantExpr::getPtrToInt(COps[0], I.getType());
1281617f6364SEaswaran Raman       }))
12827adc3a2bSChandler Carruth     return true;
12837adc3a2bSChandler Carruth 
12847adc3a2bSChandler Carruth   // Track base/offset pairs when converted to a plain integer provided the
12857adc3a2bSChandler Carruth   // integer is large enough to represent the pointer.
12867adc3a2bSChandler Carruth   unsigned IntegerSize = I.getType()->getScalarSizeInBits();
128777f32994SBjorn Pettersson   unsigned AS = I.getOperand(0)->getType()->getPointerAddressSpace();
1288faf848acSMikael Holmen   if (IntegerSize == DL.getPointerSizeInBits(AS)) {
1289567556aaSChad Rosier     std::pair<Value *, APInt> BaseAndOffset =
1290567556aaSChad Rosier         ConstantOffsetPtrs.lookup(I.getOperand(0));
12917adc3a2bSChandler Carruth     if (BaseAndOffset.first)
12927adc3a2bSChandler Carruth       ConstantOffsetPtrs[&I] = BaseAndOffset;
12937adc3a2bSChandler Carruth   }
12947adc3a2bSChandler Carruth 
12957adc3a2bSChandler Carruth   // This is really weird. Technically, ptrtoint will disable SROA. However,
12967adc3a2bSChandler Carruth   // unless that ptrtoint is *used* somewhere in the live basic blocks after
12977adc3a2bSChandler Carruth   // inlining, it will be nuked, and SROA should proceed. All of the uses which
12987adc3a2bSChandler Carruth   // would block SROA would also block SROA if applied directly to a pointer,
12997adc3a2bSChandler Carruth   // and so we can just add the integer in here. The only places where SROA is
13007adc3a2bSChandler Carruth   // preserved either cannot fire on an integer, or won't in-and-of themselves
13017adc3a2bSChandler Carruth   // disable SROA (ext) w/o some later use that we would see and disable.
130206408758SMircea Trofin   if (auto *SROAArg = getSROAArgForValueOrNull(I.getOperand(0)))
13037adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
13047adc3a2bSChandler Carruth 
1305e9c9329aSSam Parker   return TargetTransformInfo::TCC_Free ==
1306e9c9329aSSam Parker          TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
13077adc3a2bSChandler Carruth }
13087adc3a2bSChandler Carruth 
13097adc3a2bSChandler Carruth bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
13107adc3a2bSChandler Carruth   // Propagate constants through ptrtoint.
1311617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1312617f6364SEaswaran Raman         return ConstantExpr::getIntToPtr(COps[0], I.getType());
1313617f6364SEaswaran Raman       }))
13147adc3a2bSChandler Carruth     return true;
13157adc3a2bSChandler Carruth 
13167adc3a2bSChandler Carruth   // Track base/offset pairs when round-tripped through a pointer without
13177adc3a2bSChandler Carruth   // modifications provided the integer is not too large.
13187adc3a2bSChandler Carruth   Value *Op = I.getOperand(0);
13197adc3a2bSChandler Carruth   unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
132077f32994SBjorn Pettersson   if (IntegerSize <= DL.getPointerTypeSizeInBits(I.getType())) {
13217adc3a2bSChandler Carruth     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
13227adc3a2bSChandler Carruth     if (BaseAndOffset.first)
13237adc3a2bSChandler Carruth       ConstantOffsetPtrs[&I] = BaseAndOffset;
13247adc3a2bSChandler Carruth   }
13257adc3a2bSChandler Carruth 
13267adc3a2bSChandler Carruth   // "Propagate" SROA here in the same manner as we do for ptrtoint above.
132706408758SMircea Trofin   if (auto *SROAArg = getSROAArgForValueOrNull(Op))
13287adc3a2bSChandler Carruth     SROAArgValues[&I] = SROAArg;
13297adc3a2bSChandler Carruth 
1330e9c9329aSSam Parker   return TargetTransformInfo::TCC_Free ==
1331e9c9329aSSam Parker          TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
13327adc3a2bSChandler Carruth }
13337adc3a2bSChandler Carruth 
13347adc3a2bSChandler Carruth bool CallAnalyzer::visitCastInst(CastInst &I) {
1335ab53c5e5SCraig Topper   // Propagate constants through casts.
1336617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1337617f6364SEaswaran Raman         return ConstantExpr::getCast(I.getOpcode(), COps[0], I.getType());
1338617f6364SEaswaran Raman       }))
13397adc3a2bSChandler Carruth     return true;
13407adc3a2bSChandler Carruth 
134110563e16SEric Christopher   // Disable SROA in the face of arbitrary casts we don't explicitly list
134210563e16SEric Christopher   // elsewhere.
13437adc3a2bSChandler Carruth   disableSROA(I.getOperand(0));
13447adc3a2bSChandler Carruth 
134539ed9a60SEli Friedman   // If this is a floating-point cast, and the target says this operation
134639ed9a60SEli Friedman   // is expensive, this may eventually become a library call. Treat the cost
134739ed9a60SEli Friedman   // as such.
134839ed9a60SEli Friedman   switch (I.getOpcode()) {
134939ed9a60SEli Friedman   case Instruction::FPTrunc:
135039ed9a60SEli Friedman   case Instruction::FPExt:
135139ed9a60SEli Friedman   case Instruction::UIToFP:
135239ed9a60SEli Friedman   case Instruction::SIToFP:
135339ed9a60SEli Friedman   case Instruction::FPToUI:
135439ed9a60SEli Friedman   case Instruction::FPToSI:
135539ed9a60SEli Friedman     if (TTI.getFPOpCost(I.getType()) == TargetTransformInfo::TCC_Expensive)
135606408758SMircea Trofin       onCallPenalty();
13574dc0b1acSReid Kleckner     break;
135839ed9a60SEli Friedman   default:
135939ed9a60SEli Friedman     break;
136039ed9a60SEli Friedman   }
136139ed9a60SEli Friedman 
1362e9c9329aSSam Parker   return TargetTransformInfo::TCC_Free ==
1363e9c9329aSSam Parker          TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency);
13647adc3a2bSChandler Carruth }
13657adc3a2bSChandler Carruth 
13667adc3a2bSChandler Carruth bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) {
13677adc3a2bSChandler Carruth   Value *Operand = I.getOperand(0);
1368617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1369617f6364SEaswaran Raman         return ConstantFoldInstOperands(&I, COps[0], DL);
1370617f6364SEaswaran Raman       }))
13717adc3a2bSChandler Carruth     return true;
13727adc3a2bSChandler Carruth 
1373ab53c5e5SCraig Topper   // Disable any SROA on the argument to arbitrary unary instructions.
13747adc3a2bSChandler Carruth   disableSROA(Operand);
13757adc3a2bSChandler Carruth 
13767adc3a2bSChandler Carruth   return false;
13777adc3a2bSChandler Carruth }
13787adc3a2bSChandler Carruth 
13797adc3a2bSChandler Carruth bool CallAnalyzer::paramHasAttr(Argument *A, Attribute::AttrKind Attr) {
1380652168a9SFedor Sergeev   return CandidateCall.paramHasAttr(A->getArgNo(), Attr);
13817adc3a2bSChandler Carruth }
13827adc3a2bSChandler Carruth 
13837adc3a2bSChandler Carruth bool CallAnalyzer::isKnownNonNullInCallee(Value *V) {
13847adc3a2bSChandler Carruth   // Does the *call site* have the NonNull attribute set on an argument?  We
13857adc3a2bSChandler Carruth   // use the attribute on the call site to memoize any analysis done in the
13867adc3a2bSChandler Carruth   // caller. This will also trip if the callee function has a non-null
13877adc3a2bSChandler Carruth   // parameter attribute, but that's a less interesting case because hopefully
13887adc3a2bSChandler Carruth   // the callee would already have been simplified based on that.
13897adc3a2bSChandler Carruth   if (Argument *A = dyn_cast<Argument>(V))
13907adc3a2bSChandler Carruth     if (paramHasAttr(A, Attribute::NonNull))
13917adc3a2bSChandler Carruth       return true;
13927adc3a2bSChandler Carruth 
13937adc3a2bSChandler Carruth   // Is this an alloca in the caller?  This is distinct from the attribute case
13947adc3a2bSChandler Carruth   // above because attributes aren't updated within the inliner itself and we
13957adc3a2bSChandler Carruth   // always want to catch the alloca derived case.
13967adc3a2bSChandler Carruth   if (isAllocaDerivedArg(V))
13977adc3a2bSChandler Carruth     // We can actually predict the result of comparisons between an
13987adc3a2bSChandler Carruth     // alloca-derived value and null. Note that this fires regardless of
13997adc3a2bSChandler Carruth     // SROA firing.
14007adc3a2bSChandler Carruth     return true;
14017adc3a2bSChandler Carruth 
14027adc3a2bSChandler Carruth   return false;
14037adc3a2bSChandler Carruth }
14047adc3a2bSChandler Carruth 
1405652168a9SFedor Sergeev bool CallAnalyzer::allowSizeGrowth(CallBase &Call) {
14069a3fc17aSEaswaran Raman   // If the normal destination of the invoke or the parent block of the call
14079a3fc17aSEaswaran Raman   // site is unreachable-terminated, there is little point in inlining this
14089a3fc17aSEaswaran Raman   // unless there is literally zero cost.
14099a3fc17aSEaswaran Raman   // FIXME: Note that it is possible that an unreachable-terminated block has a
14109a3fc17aSEaswaran Raman   // hot entry. For example, in below scenario inlining hot_call_X() may be
14119a3fc17aSEaswaran Raman   // beneficial :
14129a3fc17aSEaswaran Raman   // main() {
14139a3fc17aSEaswaran Raman   //   hot_call_1();
14149a3fc17aSEaswaran Raman   //   ...
14159a3fc17aSEaswaran Raman   //   hot_call_N()
14169a3fc17aSEaswaran Raman   //   exit(0);
14179a3fc17aSEaswaran Raman   // }
14189a3fc17aSEaswaran Raman   // For now, we are not handling this corner case here as it is rare in real
14199a3fc17aSEaswaran Raman   // code. In future, we should elaborate this based on BPI and BFI in more
14209a3fc17aSEaswaran Raman   // general threshold adjusting heuristics in updateThreshold().
1421652168a9SFedor Sergeev   if (InvokeInst *II = dyn_cast<InvokeInst>(&Call)) {
14229a3fc17aSEaswaran Raman     if (isa<UnreachableInst>(II->getNormalDest()->getTerminator()))
14239a3fc17aSEaswaran Raman       return false;
1424652168a9SFedor Sergeev   } else if (isa<UnreachableInst>(Call.getParent()->getTerminator()))
14259a3fc17aSEaswaran Raman     return false;
14269a3fc17aSEaswaran Raman 
14279a3fc17aSEaswaran Raman   return true;
14289a3fc17aSEaswaran Raman }
14299a3fc17aSEaswaran Raman 
143006408758SMircea Trofin bool InlineCostCallAnalyzer::isColdCallSite(CallBase &Call,
1431652168a9SFedor Sergeev                                             BlockFrequencyInfo *CallerBFI) {
1432c5fa6358SEaswaran Raman   // If global profile summary is available, then callsite's coldness is
1433c5fa6358SEaswaran Raman   // determined based on that.
1434bba762a1SChandler Carruth   if (PSI && PSI->hasProfileSummary())
1435ec73ae11SMircea Trofin     return PSI->isColdCallSite(Call, CallerBFI);
1436bba762a1SChandler Carruth 
1437bba762a1SChandler Carruth   // Otherwise we need BFI to be available.
1438c5fa6358SEaswaran Raman   if (!CallerBFI)
1439c5fa6358SEaswaran Raman     return false;
1440c5fa6358SEaswaran Raman 
1441bba762a1SChandler Carruth   // Determine if the callsite is cold relative to caller's entry. We could
1442bba762a1SChandler Carruth   // potentially cache the computation of scaled entry frequency, but the added
1443bba762a1SChandler Carruth   // complexity is not worth it unless this scaling shows up high in the
1444bba762a1SChandler Carruth   // profiles.
1445c5fa6358SEaswaran Raman   const BranchProbability ColdProb(ColdCallSiteRelFreq, 100);
1446652168a9SFedor Sergeev   auto CallSiteBB = Call.getParent();
1447c5fa6358SEaswaran Raman   auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB);
1448c5fa6358SEaswaran Raman   auto CallerEntryFreq =
1449652168a9SFedor Sergeev       CallerBFI->getBlockFreq(&(Call.getCaller()->getEntryBlock()));
1450c5fa6358SEaswaran Raman   return CallSiteFreq < CallerEntryFreq * ColdProb;
1451c5fa6358SEaswaran Raman }
1452c5fa6358SEaswaran Raman 
1453974d4eeaSEaswaran Raman Optional<int>
145406408758SMircea Trofin InlineCostCallAnalyzer::getHotCallSiteThreshold(CallBase &Call,
1455974d4eeaSEaswaran Raman                                                 BlockFrequencyInfo *CallerBFI) {
1456bba762a1SChandler Carruth 
1457974d4eeaSEaswaran Raman   // If global profile summary is available, then callsite's hotness is
1458974d4eeaSEaswaran Raman   // determined based on that.
1459ec73ae11SMircea Trofin   if (PSI && PSI->hasProfileSummary() && PSI->isHotCallSite(Call, CallerBFI))
1460bba762a1SChandler Carruth     return Params.HotCallSiteThreshold;
1461974d4eeaSEaswaran Raman 
1462bba762a1SChandler Carruth   // Otherwise we need BFI to be available and to have a locally hot callsite
1463bba762a1SChandler Carruth   // threshold.
1464bba762a1SChandler Carruth   if (!CallerBFI || !Params.LocallyHotCallSiteThreshold)
1465974d4eeaSEaswaran Raman     return None;
1466974d4eeaSEaswaran Raman 
1467bba762a1SChandler Carruth   // Determine if the callsite is hot relative to caller's entry. We could
1468bba762a1SChandler Carruth   // potentially cache the computation of scaled entry frequency, but the added
1469bba762a1SChandler Carruth   // complexity is not worth it unless this scaling shows up high in the
1470bba762a1SChandler Carruth   // profiles.
1471652168a9SFedor Sergeev   auto CallSiteBB = Call.getParent();
1472974d4eeaSEaswaran Raman   auto CallSiteFreq = CallerBFI->getBlockFreq(CallSiteBB).getFrequency();
1473974d4eeaSEaswaran Raman   auto CallerEntryFreq = CallerBFI->getEntryFreq();
1474974d4eeaSEaswaran Raman   if (CallSiteFreq >= CallerEntryFreq * HotCallSiteRelFreq)
1475bba762a1SChandler Carruth     return Params.LocallyHotCallSiteThreshold;
1476bba762a1SChandler Carruth 
1477bba762a1SChandler Carruth   // Otherwise treat it normally.
1478974d4eeaSEaswaran Raman   return None;
1479974d4eeaSEaswaran Raman }
1480974d4eeaSEaswaran Raman 
148106408758SMircea Trofin void InlineCostCallAnalyzer::updateThreshold(CallBase &Call, Function &Callee) {
14829a3fc17aSEaswaran Raman   // If no size growth is allowed for this inlining, set Threshold to 0.
1483652168a9SFedor Sergeev   if (!allowSizeGrowth(Call)) {
14849a3fc17aSEaswaran Raman     Threshold = 0;
14859a3fc17aSEaswaran Raman     return;
14869a3fc17aSEaswaran Raman   }
14879a3fc17aSEaswaran Raman 
1488652168a9SFedor Sergeev   Function *Caller = Call.getCaller();
14891c57cc2bSEaswaran Raman 
14901c57cc2bSEaswaran Raman   // return min(A, B) if B is valid.
14911c57cc2bSEaswaran Raman   auto MinIfValid = [](int A, Optional<int> B) {
14921c57cc2bSEaswaran Raman     return B ? std::min(A, B.getValue()) : A;
14931c57cc2bSEaswaran Raman   };
14941c57cc2bSEaswaran Raman 
14950d58fcacSEaswaran Raman   // return max(A, B) if B is valid.
14960d58fcacSEaswaran Raman   auto MaxIfValid = [](int A, Optional<int> B) {
14970d58fcacSEaswaran Raman     return B ? std::max(A, B.getValue()) : A;
14980d58fcacSEaswaran Raman   };
14990d58fcacSEaswaran Raman 
150051b809bfSEaswaran Raman   // Various bonus percentages. These are multiplied by Threshold to get the
150151b809bfSEaswaran Raman   // bonus values.
150251b809bfSEaswaran Raman   // SingleBBBonus: This bonus is applied if the callee has a single reachable
150351b809bfSEaswaran Raman   // basic block at the given callsite context. This is speculatively applied
150451b809bfSEaswaran Raman   // and withdrawn if more than one basic block is seen.
150551b809bfSEaswaran Raman   //
150651b809bfSEaswaran Raman   // LstCallToStaticBonus: This large bonus is applied to ensure the inlining
150751b809bfSEaswaran Raman   // of the last call to a static function as inlining such functions is
150851b809bfSEaswaran Raman   // guaranteed to reduce code size.
150951b809bfSEaswaran Raman   //
151051b809bfSEaswaran Raman   // These bonus percentages may be set to 0 based on properties of the caller
151151b809bfSEaswaran Raman   // and the callsite.
151251b809bfSEaswaran Raman   int SingleBBBonusPercent = 50;
1513d912a9baSDaniil Fukalov   int VectorBonusPercent = TTI.getInlinerVectorBonusPercent();
151402647f73SJordan Rupprecht   int LastCallToStaticBonus = InlineConstants::LastCallToStaticBonus;
151551b809bfSEaswaran Raman 
151651b809bfSEaswaran Raman   // Lambda to set all the above bonus and bonus percentages to 0.
151751b809bfSEaswaran Raman   auto DisallowAllBonuses = [&]() {
151851b809bfSEaswaran Raman     SingleBBBonusPercent = 0;
151951b809bfSEaswaran Raman     VectorBonusPercent = 0;
152051b809bfSEaswaran Raman     LastCallToStaticBonus = 0;
152151b809bfSEaswaran Raman   };
152251b809bfSEaswaran Raman 
15231c57cc2bSEaswaran Raman   // Use the OptMinSizeThreshold or OptSizeThreshold knob if they are available
15241c57cc2bSEaswaran Raman   // and reduce the threshold if the caller has the necessary attribute.
152585bd3978SEvandro Menezes   if (Caller->hasMinSize()) {
15261c57cc2bSEaswaran Raman     Threshold = MinIfValid(Threshold, Params.OptMinSizeThreshold);
152751b809bfSEaswaran Raman     // For minsize, we want to disable the single BB bonus and the vector
152851b809bfSEaswaran Raman     // bonuses, but not the last-call-to-static bonus. Inlining the last call to
152951b809bfSEaswaran Raman     // a static function will, at the minimum, eliminate the parameter setup and
153051b809bfSEaswaran Raman     // call/return instructions.
153151b809bfSEaswaran Raman     SingleBBBonusPercent = 0;
153251b809bfSEaswaran Raman     VectorBonusPercent = 0;
153385bd3978SEvandro Menezes   } else if (Caller->hasOptSize())
15341c57cc2bSEaswaran Raman     Threshold = MinIfValid(Threshold, Params.OptSizeThreshold);
1535f4bb2f0dSEaswaran Raman 
1536e08b139dSEaswaran Raman   // Adjust the threshold based on inlinehint attribute and profile based
1537e08b139dSEaswaran Raman   // hotness information if the caller does not have MinSize attribute.
153885bd3978SEvandro Menezes   if (!Caller->hasMinSize()) {
1539e08b139dSEaswaran Raman     if (Callee.hasFnAttribute(Attribute::InlineHint))
15400d58fcacSEaswaran Raman       Threshold = MaxIfValid(Threshold, Params.HintThreshold);
1541bba762a1SChandler Carruth 
15423cd1479cSEaswaran Raman     // FIXME: After switching to the new passmanager, simplify the logic below
1543bba762a1SChandler Carruth     // by checking only the callsite hotness/coldness as we will reliably
1544bba762a1SChandler Carruth     // have local profile information.
15453cd1479cSEaswaran Raman     //
1546bba762a1SChandler Carruth     // Callsite hotness and coldness can be determined if sample profile is
1547bba762a1SChandler Carruth     // used (which adds hotness metadata to calls) or if caller's
1548bba762a1SChandler Carruth     // BlockFrequencyInfo is available.
154908e2386dSMircea Trofin     BlockFrequencyInfo *CallerBFI = GetBFI ? &(GetBFI(*Caller)) : nullptr;
1550652168a9SFedor Sergeev     auto HotCallSiteThreshold = getHotCallSiteThreshold(Call, CallerBFI);
155185bd3978SEvandro Menezes     if (!Caller->hasOptSize() && HotCallSiteThreshold) {
1552d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Hot callsite.\n");
1553974d4eeaSEaswaran Raman       // FIXME: This should update the threshold only if it exceeds the
1554974d4eeaSEaswaran Raman       // current threshold, but AutoFDO + ThinLTO currently relies on this
1555974d4eeaSEaswaran Raman       // behavior to prevent inlining of hot callsites during ThinLTO
1556974d4eeaSEaswaran Raman       // compile phase.
1557974d4eeaSEaswaran Raman       Threshold = HotCallSiteThreshold.getValue();
1558652168a9SFedor Sergeev     } else if (isColdCallSite(Call, CallerBFI)) {
1559d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Cold callsite.\n");
156051b809bfSEaswaran Raman       // Do not apply bonuses for a cold callsite including the
156151b809bfSEaswaran Raman       // LastCallToStatic bonus. While this bonus might result in code size
156251b809bfSEaswaran Raman       // reduction, it can cause the size of a non-cold caller to increase
156351b809bfSEaswaran Raman       // preventing it from being inlined.
156451b809bfSEaswaran Raman       DisallowAllBonuses();
15653cd1479cSEaswaran Raman       Threshold = MinIfValid(Threshold, Params.ColdCallSiteThreshold);
1566bba762a1SChandler Carruth     } else if (PSI) {
1567bba762a1SChandler Carruth       // Use callee's global profile information only if we have no way of
1568bba762a1SChandler Carruth       // determining this via callsite information.
15693cd1479cSEaswaran Raman       if (PSI->isFunctionEntryHot(&Callee)) {
1570d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Hot callee.\n");
1571e08b139dSEaswaran Raman         // If callsite hotness can not be determined, we may still know
1572e08b139dSEaswaran Raman         // that the callee is hot and treat it as a weaker hint for threshold
1573e08b139dSEaswaran Raman         // increase.
1574e08b139dSEaswaran Raman         Threshold = MaxIfValid(Threshold, Params.HintThreshold);
1575e08b139dSEaswaran Raman       } else if (PSI->isFunctionEntryCold(&Callee)) {
1576d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Cold callee.\n");
157751b809bfSEaswaran Raman         // Do not apply bonuses for a cold callee including the
157851b809bfSEaswaran Raman         // LastCallToStatic bonus. While this bonus might result in code size
157951b809bfSEaswaran Raman         // reduction, it can cause the size of a non-cold caller to increase
158051b809bfSEaswaran Raman         // preventing it from being inlined.
158151b809bfSEaswaran Raman         DisallowAllBonuses();
15821c57cc2bSEaswaran Raman         Threshold = MinIfValid(Threshold, Params.ColdThreshold);
1583e08b139dSEaswaran Raman       }
1584e08b139dSEaswaran Raman     }
1585e08b139dSEaswaran Raman   }
15868650a4daSJustin Lebar 
1587b7b99b07SStanislav Mekhanoshin   Threshold += TTI.adjustInliningThreshold(&Call);
1588b7b99b07SStanislav Mekhanoshin 
158902647f73SJordan Rupprecht   // Finally, take the target-specific inlining threshold multiplier into
159002647f73SJordan Rupprecht   // account.
15918650a4daSJustin Lebar   Threshold *= TTI.getInliningThresholdMultiplier();
159251b809bfSEaswaran Raman 
159351b809bfSEaswaran Raman   SingleBBBonus = Threshold * SingleBBBonusPercent / 100;
159451b809bfSEaswaran Raman   VectorBonus = Threshold * VectorBonusPercent / 100;
159551b809bfSEaswaran Raman 
159602647f73SJordan Rupprecht   bool OnlyOneCallAndLocalLinkage =
159702647f73SJordan Rupprecht       F.hasLocalLinkage() && F.hasOneUse() && &F == Call.getCalledFunction();
159802647f73SJordan Rupprecht   // If there is only one call of the function, and it has internal linkage,
159902647f73SJordan Rupprecht   // the cost of inlining it drops dramatically. It may seem odd to update
160002647f73SJordan Rupprecht   // Cost in updateThreshold, but the bonus depends on the logic in this method.
160102647f73SJordan Rupprecht   if (OnlyOneCallAndLocalLinkage)
160202647f73SJordan Rupprecht     Cost -= LastCallToStaticBonus;
1603f4bb2f0dSEaswaran Raman }
1604f4bb2f0dSEaswaran Raman 
16057adc3a2bSChandler Carruth bool CallAnalyzer::visitCmpInst(CmpInst &I) {
16067adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
16077adc3a2bSChandler Carruth   // First try to handle simplified comparisons.
1608617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1609617f6364SEaswaran Raman         return ConstantExpr::getCompare(I.getPredicate(), COps[0], COps[1]);
1610617f6364SEaswaran Raman       }))
16117adc3a2bSChandler Carruth     return true;
16127adc3a2bSChandler Carruth 
16137adc3a2bSChandler Carruth   if (I.getOpcode() == Instruction::FCmp)
16147adc3a2bSChandler Carruth     return false;
16157adc3a2bSChandler Carruth 
16167adc3a2bSChandler Carruth   // Otherwise look for a comparison between constant offset pointers with
16177adc3a2bSChandler Carruth   // a common base.
16187adc3a2bSChandler Carruth   Value *LHSBase, *RHSBase;
16197adc3a2bSChandler Carruth   APInt LHSOffset, RHSOffset;
16207adc3a2bSChandler Carruth   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
16217adc3a2bSChandler Carruth   if (LHSBase) {
16227adc3a2bSChandler Carruth     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
16237adc3a2bSChandler Carruth     if (RHSBase && LHSBase == RHSBase) {
16247adc3a2bSChandler Carruth       // We have common bases, fold the icmp to a constant based on the
16257adc3a2bSChandler Carruth       // offsets.
16267adc3a2bSChandler Carruth       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
16277adc3a2bSChandler Carruth       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
16287adc3a2bSChandler Carruth       if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
16297adc3a2bSChandler Carruth         SimplifiedValues[&I] = C;
16307adc3a2bSChandler Carruth         ++NumConstantPtrCmps;
16317adc3a2bSChandler Carruth         return true;
16327adc3a2bSChandler Carruth       }
16337adc3a2bSChandler Carruth     }
16347adc3a2bSChandler Carruth   }
16357adc3a2bSChandler Carruth 
16367adc3a2bSChandler Carruth   // If the comparison is an equality comparison with null, we can simplify it
16377adc3a2bSChandler Carruth   // if we know the value (argument) can't be null
16387adc3a2bSChandler Carruth   if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)) &&
16397adc3a2bSChandler Carruth       isKnownNonNullInCallee(I.getOperand(0))) {
16407adc3a2bSChandler Carruth     bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
16417adc3a2bSChandler Carruth     SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
16427adc3a2bSChandler Carruth                                       : ConstantInt::getFalse(I.getType());
16437adc3a2bSChandler Carruth     return true;
16447adc3a2bSChandler Carruth   }
164506408758SMircea Trofin   return handleSROA(I.getOperand(0), isa<ConstantPointerNull>(I.getOperand(1)));
16467adc3a2bSChandler Carruth }
16477adc3a2bSChandler Carruth 
16487adc3a2bSChandler Carruth bool CallAnalyzer::visitSub(BinaryOperator &I) {
16497adc3a2bSChandler Carruth   // Try to handle a special case: we can fold computing the difference of two
16507adc3a2bSChandler Carruth   // constant-related pointers.
16517adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
16527adc3a2bSChandler Carruth   Value *LHSBase, *RHSBase;
16537adc3a2bSChandler Carruth   APInt LHSOffset, RHSOffset;
16547adc3a2bSChandler Carruth   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
16557adc3a2bSChandler Carruth   if (LHSBase) {
16567adc3a2bSChandler Carruth     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
16577adc3a2bSChandler Carruth     if (RHSBase && LHSBase == RHSBase) {
16587adc3a2bSChandler Carruth       // We have common bases, fold the subtract to a constant based on the
16597adc3a2bSChandler Carruth       // offsets.
16607adc3a2bSChandler Carruth       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
16617adc3a2bSChandler Carruth       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
16627adc3a2bSChandler Carruth       if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
16637adc3a2bSChandler Carruth         SimplifiedValues[&I] = C;
16647adc3a2bSChandler Carruth         ++NumConstantPtrDiffs;
16657adc3a2bSChandler Carruth         return true;
16667adc3a2bSChandler Carruth       }
16677adc3a2bSChandler Carruth     }
16687adc3a2bSChandler Carruth   }
16697adc3a2bSChandler Carruth 
16707adc3a2bSChandler Carruth   // Otherwise, fall back to the generic logic for simplifying and handling
16717adc3a2bSChandler Carruth   // instructions.
16727adc3a2bSChandler Carruth   return Base::visitSub(I);
16737adc3a2bSChandler Carruth }
16747adc3a2bSChandler Carruth 
16757adc3a2bSChandler Carruth bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
16767adc3a2bSChandler Carruth   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
16776d14dfe8SHaicheng Wu   Constant *CLHS = dyn_cast<Constant>(LHS);
16786d14dfe8SHaicheng Wu   if (!CLHS)
16796d14dfe8SHaicheng Wu     CLHS = SimplifiedValues.lookup(LHS);
16806d14dfe8SHaicheng Wu   Constant *CRHS = dyn_cast<Constant>(RHS);
16816d14dfe8SHaicheng Wu   if (!CRHS)
16826d14dfe8SHaicheng Wu     CRHS = SimplifiedValues.lookup(RHS);
16836d14dfe8SHaicheng Wu 
16847adc3a2bSChandler Carruth   Value *SimpleV = nullptr;
16857adc3a2bSChandler Carruth   if (auto FI = dyn_cast<FPMathOperator>(&I))
16865a956c85SMircea Trofin     SimpleV = SimplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS,
16875a956c85SMircea Trofin                             FI->getFastMathFlags(), DL);
16887adc3a2bSChandler Carruth   else
16896d14dfe8SHaicheng Wu     SimpleV =
16906d14dfe8SHaicheng Wu         SimplifyBinOp(I.getOpcode(), CLHS ? CLHS : LHS, CRHS ? CRHS : RHS, DL);
16917adc3a2bSChandler Carruth 
16926d14dfe8SHaicheng Wu   if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
16936d14dfe8SHaicheng Wu     SimplifiedValues[&I] = C;
16946d14dfe8SHaicheng Wu 
16956d14dfe8SHaicheng Wu   if (SimpleV)
16967adc3a2bSChandler Carruth     return true;
16977adc3a2bSChandler Carruth 
16987adc3a2bSChandler Carruth   // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
16997adc3a2bSChandler Carruth   disableSROA(LHS);
17007adc3a2bSChandler Carruth   disableSROA(RHS);
17017adc3a2bSChandler Carruth 
170239ed9a60SEli Friedman   // If the instruction is floating point, and the target says this operation
170339ed9a60SEli Friedman   // is expensive, this may eventually become a library call. Treat the cost
17047cebf0afSCraig Topper   // as such. Unless it's fneg which can be implemented with an xor.
17057cebf0afSCraig Topper   using namespace llvm::PatternMatch;
170639ed9a60SEli Friedman   if (I.getType()->isFloatingPointTy() &&
17077cebf0afSCraig Topper       TTI.getFPOpCost(I.getType()) == TargetTransformInfo::TCC_Expensive &&
17087cebf0afSCraig Topper       !match(&I, m_FNeg(m_Value())))
170906408758SMircea Trofin     onCallPenalty();
171039ed9a60SEli Friedman 
17117adc3a2bSChandler Carruth   return false;
17127adc3a2bSChandler Carruth }
17137adc3a2bSChandler Carruth 
17146cda33baSCraig Topper bool CallAnalyzer::visitFNeg(UnaryOperator &I) {
17156cda33baSCraig Topper   Value *Op = I.getOperand(0);
17166cda33baSCraig Topper   Constant *COp = dyn_cast<Constant>(Op);
17176cda33baSCraig Topper   if (!COp)
17186cda33baSCraig Topper     COp = SimplifiedValues.lookup(Op);
17196cda33baSCraig Topper 
17205a956c85SMircea Trofin   Value *SimpleV = SimplifyFNegInst(
17215a956c85SMircea Trofin       COp ? COp : Op, cast<FPMathOperator>(I).getFastMathFlags(), DL);
17226cda33baSCraig Topper 
17236cda33baSCraig Topper   if (Constant *C = dyn_cast_or_null<Constant>(SimpleV))
17246cda33baSCraig Topper     SimplifiedValues[&I] = C;
17256cda33baSCraig Topper 
17266cda33baSCraig Topper   if (SimpleV)
17276cda33baSCraig Topper     return true;
17286cda33baSCraig Topper 
17296cda33baSCraig Topper   // Disable any SROA on arguments to arbitrary, unsimplified fneg.
17306cda33baSCraig Topper   disableSROA(Op);
17316cda33baSCraig Topper 
17326cda33baSCraig Topper   return false;
17336cda33baSCraig Topper }
17346cda33baSCraig Topper 
17357adc3a2bSChandler Carruth bool CallAnalyzer::visitLoad(LoadInst &I) {
173606408758SMircea Trofin   if (handleSROA(I.getPointerOperand(), I.isSimple()))
17377adc3a2bSChandler Carruth     return true;
17387adc3a2bSChandler Carruth 
1739a4461515SHaicheng Wu   // If the data is already loaded from this address and hasn't been clobbered
1740a4461515SHaicheng Wu   // by any stores or calls, this load is likely to be redundant and can be
1741a4461515SHaicheng Wu   // eliminated.
1742a4461515SHaicheng Wu   if (EnableLoadElimination &&
1743b3689cabSHaicheng Wu       !LoadAddrSet.insert(I.getPointerOperand()).second && I.isUnordered()) {
174406408758SMircea Trofin     onLoadEliminationOpportunity();
1745a4461515SHaicheng Wu     return true;
1746a4461515SHaicheng Wu   }
1747a4461515SHaicheng Wu 
17487adc3a2bSChandler Carruth   return false;
17497adc3a2bSChandler Carruth }
17507adc3a2bSChandler Carruth 
17517adc3a2bSChandler Carruth bool CallAnalyzer::visitStore(StoreInst &I) {
175206408758SMircea Trofin   if (handleSROA(I.getPointerOperand(), I.isSimple()))
17537adc3a2bSChandler Carruth     return true;
17547adc3a2bSChandler Carruth 
1755a4461515SHaicheng Wu   // The store can potentially clobber loads and prevent repeated loads from
1756a4461515SHaicheng Wu   // being eliminated.
1757a4461515SHaicheng Wu   // FIXME:
1758a4461515SHaicheng Wu   // 1. We can probably keep an initial set of eliminatable loads substracted
1759a4461515SHaicheng Wu   // from the cost even when we finally see a store. We just need to disable
1760a4461515SHaicheng Wu   // *further* accumulation of elimination savings.
1761a4461515SHaicheng Wu   // 2. We should probably at some point thread MemorySSA for the callee into
1762a4461515SHaicheng Wu   // this and then use that to actually compute *really* precise savings.
1763a4461515SHaicheng Wu   disableLoadElimination();
17647adc3a2bSChandler Carruth   return false;
17657adc3a2bSChandler Carruth }
17667adc3a2bSChandler Carruth 
17677adc3a2bSChandler Carruth bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) {
17687adc3a2bSChandler Carruth   // Constant folding for extract value is trivial.
1769617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1770617f6364SEaswaran Raman         return ConstantExpr::getExtractValue(COps[0], I.getIndices());
1771617f6364SEaswaran Raman       }))
17727adc3a2bSChandler Carruth     return true;
17737adc3a2bSChandler Carruth 
17747adc3a2bSChandler Carruth   // SROA can look through these but give them a cost.
17757adc3a2bSChandler Carruth   return false;
17767adc3a2bSChandler Carruth }
17777adc3a2bSChandler Carruth 
17787adc3a2bSChandler Carruth bool CallAnalyzer::visitInsertValue(InsertValueInst &I) {
17797adc3a2bSChandler Carruth   // Constant folding for insert value is trivial.
1780617f6364SEaswaran Raman   if (simplifyInstruction(I, [&](SmallVectorImpl<Constant *> &COps) {
1781617f6364SEaswaran Raman         return ConstantExpr::getInsertValue(/*AggregateOperand*/ COps[0],
1782617f6364SEaswaran Raman                                             /*InsertedValueOperand*/ COps[1],
1783617f6364SEaswaran Raman                                             I.getIndices());
1784617f6364SEaswaran Raman       }))
17857adc3a2bSChandler Carruth     return true;
17867adc3a2bSChandler Carruth 
17877adc3a2bSChandler Carruth   // SROA can look through these but give them a cost.
17887adc3a2bSChandler Carruth   return false;
17897adc3a2bSChandler Carruth }
17907adc3a2bSChandler Carruth 
17915f8f34e4SAdrian Prantl /// Try to simplify a call site.
17927adc3a2bSChandler Carruth ///
17937adc3a2bSChandler Carruth /// Takes a concrete function and callsite and tries to actually simplify it by
17947adc3a2bSChandler Carruth /// analyzing the arguments and call itself with instsimplify. Returns true if
17957adc3a2bSChandler Carruth /// it has simplified the callsite to some other entity (a constant), making it
17967adc3a2bSChandler Carruth /// free.
1797652168a9SFedor Sergeev bool CallAnalyzer::simplifyCallSite(Function *F, CallBase &Call) {
17987adc3a2bSChandler Carruth   // FIXME: Using the instsimplify logic directly for this is inefficient
17997adc3a2bSChandler Carruth   // because we have to continually rebuild the argument list even when no
18007adc3a2bSChandler Carruth   // simplifications can be performed. Until that is fixed with remapping
18017adc3a2bSChandler Carruth   // inside of instsimplify, directly constant fold calls here.
1802652168a9SFedor Sergeev   if (!canConstantFoldCallTo(&Call, F))
18037adc3a2bSChandler Carruth     return false;
18047adc3a2bSChandler Carruth 
18057adc3a2bSChandler Carruth   // Try to re-map the arguments to constants.
18067adc3a2bSChandler Carruth   SmallVector<Constant *, 4> ConstantArgs;
1807652168a9SFedor Sergeev   ConstantArgs.reserve(Call.arg_size());
1808652168a9SFedor Sergeev   for (Value *I : Call.args()) {
1809652168a9SFedor Sergeev     Constant *C = dyn_cast<Constant>(I);
18107adc3a2bSChandler Carruth     if (!C)
1811652168a9SFedor Sergeev       C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(I));
18127adc3a2bSChandler Carruth     if (!C)
18137adc3a2bSChandler Carruth       return false; // This argument doesn't map to a constant.
18147adc3a2bSChandler Carruth 
18157adc3a2bSChandler Carruth     ConstantArgs.push_back(C);
18167adc3a2bSChandler Carruth   }
1817652168a9SFedor Sergeev   if (Constant *C = ConstantFoldCall(&Call, F, ConstantArgs)) {
1818652168a9SFedor Sergeev     SimplifiedValues[&Call] = C;
18197adc3a2bSChandler Carruth     return true;
18207adc3a2bSChandler Carruth   }
18217adc3a2bSChandler Carruth 
18227adc3a2bSChandler Carruth   return false;
18237adc3a2bSChandler Carruth }
18247adc3a2bSChandler Carruth 
1825652168a9SFedor Sergeev bool CallAnalyzer::visitCallBase(CallBase &Call) {
1826652168a9SFedor Sergeev   if (Call.hasFnAttr(Attribute::ReturnsTwice) &&
18277adc3a2bSChandler Carruth       !F.hasFnAttribute(Attribute::ReturnsTwice)) {
18287adc3a2bSChandler Carruth     // This aborts the entire analysis.
18297adc3a2bSChandler Carruth     ExposesReturnsTwice = true;
18307adc3a2bSChandler Carruth     return false;
18317adc3a2bSChandler Carruth   }
1832652168a9SFedor Sergeev   if (isa<CallInst>(Call) && cast<CallInst>(Call).cannotDuplicate())
18337adc3a2bSChandler Carruth     ContainsNoDuplicateCall = true;
18347adc3a2bSChandler Carruth 
1835825debe8SEhud Katz   Value *Callee = Call.getCalledOperand();
1836825debe8SEhud Katz   Function *F = dyn_cast_or_null<Function>(Callee);
1837825debe8SEhud Katz   bool IsIndirectCall = !F;
1838825debe8SEhud Katz   if (IsIndirectCall) {
1839825debe8SEhud Katz     // Check if this happens to be an indirect function call to a known function
1840825debe8SEhud Katz     // in this inline context. If not, we've done all we can.
1841825debe8SEhud Katz     F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
1842825debe8SEhud Katz     if (!F) {
184306408758SMircea Trofin       onCallArgumentSetup(Call);
1844825debe8SEhud Katz 
1845825debe8SEhud Katz       if (!Call.onlyReadsMemory())
1846825debe8SEhud Katz         disableLoadElimination();
1847825debe8SEhud Katz       return Base::visitCallBase(Call);
1848825debe8SEhud Katz     }
1849825debe8SEhud Katz   }
1850825debe8SEhud Katz 
1851825debe8SEhud Katz   assert(F && "Expected a call to a known function");
1852825debe8SEhud Katz 
18537adc3a2bSChandler Carruth   // When we have a concrete function, first try to simplify it directly.
1854652168a9SFedor Sergeev   if (simplifyCallSite(F, Call))
18557adc3a2bSChandler Carruth     return true;
18567adc3a2bSChandler Carruth 
18577adc3a2bSChandler Carruth   // Next check if it is an intrinsic we know about.
18587adc3a2bSChandler Carruth   // FIXME: Lift this into part of the InstVisitor.
1859652168a9SFedor Sergeev   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&Call)) {
18607adc3a2bSChandler Carruth     switch (II->getIntrinsicID()) {
18617adc3a2bSChandler Carruth     default:
1862652168a9SFedor Sergeev       if (!Call.onlyReadsMemory() && !isAssumeLikeIntrinsic(II))
1863a4461515SHaicheng Wu         disableLoadElimination();
1864652168a9SFedor Sergeev       return Base::visitCallBase(Call);
18657adc3a2bSChandler Carruth 
18667dd8dbf4SPeter Collingbourne     case Intrinsic::load_relative:
186706408758SMircea Trofin       onLoadRelativeIntrinsic();
18687dd8dbf4SPeter Collingbourne       return false;
18697dd8dbf4SPeter Collingbourne 
18707adc3a2bSChandler Carruth     case Intrinsic::memset:
18717adc3a2bSChandler Carruth     case Intrinsic::memcpy:
18727adc3a2bSChandler Carruth     case Intrinsic::memmove:
1873a4461515SHaicheng Wu       disableLoadElimination();
18747adc3a2bSChandler Carruth       // SROA can usually chew through these intrinsics, but they aren't free.
18757adc3a2bSChandler Carruth       return false;
18764296ea72SVitaly Buka     case Intrinsic::icall_branch_funnel:
18777adc3a2bSChandler Carruth     case Intrinsic::localescape:
18784296ea72SVitaly Buka       HasUninlineableIntrinsic = true;
18797adc3a2bSChandler Carruth       return false;
188080788d80SFlorian Hahn     case Intrinsic::vastart:
188177beee41SSameer AbuAsal       InitsVargArgs = true;
188280788d80SFlorian Hahn       return false;
18837adc3a2bSChandler Carruth     }
18847adc3a2bSChandler Carruth   }
18857adc3a2bSChandler Carruth 
1886652168a9SFedor Sergeev   if (F == Call.getFunction()) {
18877adc3a2bSChandler Carruth     // This flag will fully abort the analysis, so don't bother with anything
18887adc3a2bSChandler Carruth     // else.
18897adc3a2bSChandler Carruth     IsRecursiveCall = true;
18907adc3a2bSChandler Carruth     return false;
18917adc3a2bSChandler Carruth   }
18927adc3a2bSChandler Carruth 
18937adc3a2bSChandler Carruth   if (TTI.isLoweredToCall(F)) {
189406408758SMircea Trofin     onLoweredCall(F, Call, IsIndirectCall);
1895825debe8SEhud Katz   }
18967adc3a2bSChandler Carruth 
1897825debe8SEhud Katz   if (!(Call.onlyReadsMemory() || (IsIndirectCall && F->onlyReadsMemory())))
1898a4461515SHaicheng Wu     disableLoadElimination();
1899652168a9SFedor Sergeev   return Base::visitCallBase(Call);
19007adc3a2bSChandler Carruth }
19017adc3a2bSChandler Carruth 
19027adc3a2bSChandler Carruth bool CallAnalyzer::visitReturnInst(ReturnInst &RI) {
19037adc3a2bSChandler Carruth   // At least one return instruction will be free after inlining.
19047adc3a2bSChandler Carruth   bool Free = !HasReturn;
19057adc3a2bSChandler Carruth   HasReturn = true;
19067adc3a2bSChandler Carruth   return Free;
19077adc3a2bSChandler Carruth }
19087adc3a2bSChandler Carruth 
19097adc3a2bSChandler Carruth bool CallAnalyzer::visitBranchInst(BranchInst &BI) {
19107adc3a2bSChandler Carruth   // We model unconditional branches as essentially free -- they really
19117adc3a2bSChandler Carruth   // shouldn't exist at all, but handling them makes the behavior of the
19127adc3a2bSChandler Carruth   // inliner more regular and predictable. Interestingly, conditional branches
19137adc3a2bSChandler Carruth   // which will fold away are also free.
19147adc3a2bSChandler Carruth   return BI.isUnconditional() || isa<ConstantInt>(BI.getCondition()) ||
19157adc3a2bSChandler Carruth          dyn_cast_or_null<ConstantInt>(
19167adc3a2bSChandler Carruth              SimplifiedValues.lookup(BI.getCondition()));
19177adc3a2bSChandler Carruth }
19187adc3a2bSChandler Carruth 
19193ec848bcSHaicheng Wu bool CallAnalyzer::visitSelectInst(SelectInst &SI) {
19203ec848bcSHaicheng Wu   bool CheckSROA = SI.getType()->isPointerTy();
19213ec848bcSHaicheng Wu   Value *TrueVal = SI.getTrueValue();
19223ec848bcSHaicheng Wu   Value *FalseVal = SI.getFalseValue();
19233ec848bcSHaicheng Wu 
19243ec848bcSHaicheng Wu   Constant *TrueC = dyn_cast<Constant>(TrueVal);
19253ec848bcSHaicheng Wu   if (!TrueC)
19263ec848bcSHaicheng Wu     TrueC = SimplifiedValues.lookup(TrueVal);
19273ec848bcSHaicheng Wu   Constant *FalseC = dyn_cast<Constant>(FalseVal);
19283ec848bcSHaicheng Wu   if (!FalseC)
19293ec848bcSHaicheng Wu     FalseC = SimplifiedValues.lookup(FalseVal);
19303ec848bcSHaicheng Wu   Constant *CondC =
19313ec848bcSHaicheng Wu       dyn_cast_or_null<Constant>(SimplifiedValues.lookup(SI.getCondition()));
19323ec848bcSHaicheng Wu 
19333ec848bcSHaicheng Wu   if (!CondC) {
19343ec848bcSHaicheng Wu     // Select C, X, X => X
19353ec848bcSHaicheng Wu     if (TrueC == FalseC && TrueC) {
19363ec848bcSHaicheng Wu       SimplifiedValues[&SI] = TrueC;
19373ec848bcSHaicheng Wu       return true;
19383ec848bcSHaicheng Wu     }
19393ec848bcSHaicheng Wu 
19403ec848bcSHaicheng Wu     if (!CheckSROA)
19413ec848bcSHaicheng Wu       return Base::visitSelectInst(SI);
19423ec848bcSHaicheng Wu 
19433ec848bcSHaicheng Wu     std::pair<Value *, APInt> TrueBaseAndOffset =
19443ec848bcSHaicheng Wu         ConstantOffsetPtrs.lookup(TrueVal);
19453ec848bcSHaicheng Wu     std::pair<Value *, APInt> FalseBaseAndOffset =
19463ec848bcSHaicheng Wu         ConstantOffsetPtrs.lookup(FalseVal);
19473ec848bcSHaicheng Wu     if (TrueBaseAndOffset == FalseBaseAndOffset && TrueBaseAndOffset.first) {
19483ec848bcSHaicheng Wu       ConstantOffsetPtrs[&SI] = TrueBaseAndOffset;
19493ec848bcSHaicheng Wu 
195006408758SMircea Trofin       if (auto *SROAArg = getSROAArgForValueOrNull(TrueVal))
19513ec848bcSHaicheng Wu         SROAArgValues[&SI] = SROAArg;
19523ec848bcSHaicheng Wu       return true;
19533ec848bcSHaicheng Wu     }
19543ec848bcSHaicheng Wu 
19553ec848bcSHaicheng Wu     return Base::visitSelectInst(SI);
19563ec848bcSHaicheng Wu   }
19573ec848bcSHaicheng Wu 
19583ec848bcSHaicheng Wu   // Select condition is a constant.
19593ec848bcSHaicheng Wu   Value *SelectedV = CondC->isAllOnesValue()
19603ec848bcSHaicheng Wu                          ? TrueVal
19613ec848bcSHaicheng Wu                          : (CondC->isNullValue()) ? FalseVal : nullptr;
19623ec848bcSHaicheng Wu   if (!SelectedV) {
19633ec848bcSHaicheng Wu     // Condition is a vector constant that is not all 1s or all 0s.  If all
19643ec848bcSHaicheng Wu     // operands are constants, ConstantExpr::getSelect() can handle the cases
19653ec848bcSHaicheng Wu     // such as select vectors.
19663ec848bcSHaicheng Wu     if (TrueC && FalseC) {
19673ec848bcSHaicheng Wu       if (auto *C = ConstantExpr::getSelect(CondC, TrueC, FalseC)) {
19683ec848bcSHaicheng Wu         SimplifiedValues[&SI] = C;
19693ec848bcSHaicheng Wu         return true;
19703ec848bcSHaicheng Wu       }
19713ec848bcSHaicheng Wu     }
19723ec848bcSHaicheng Wu     return Base::visitSelectInst(SI);
19733ec848bcSHaicheng Wu   }
19743ec848bcSHaicheng Wu 
19753ec848bcSHaicheng Wu   // Condition is either all 1s or all 0s. SI can be simplified.
19763ec848bcSHaicheng Wu   if (Constant *SelectedC = dyn_cast<Constant>(SelectedV)) {
19773ec848bcSHaicheng Wu     SimplifiedValues[&SI] = SelectedC;
19783ec848bcSHaicheng Wu     return true;
19793ec848bcSHaicheng Wu   }
19803ec848bcSHaicheng Wu 
19813ec848bcSHaicheng Wu   if (!CheckSROA)
19823ec848bcSHaicheng Wu     return true;
19833ec848bcSHaicheng Wu 
19843ec848bcSHaicheng Wu   std::pair<Value *, APInt> BaseAndOffset =
19853ec848bcSHaicheng Wu       ConstantOffsetPtrs.lookup(SelectedV);
19863ec848bcSHaicheng Wu   if (BaseAndOffset.first) {
19873ec848bcSHaicheng Wu     ConstantOffsetPtrs[&SI] = BaseAndOffset;
19883ec848bcSHaicheng Wu 
198906408758SMircea Trofin     if (auto *SROAArg = getSROAArgForValueOrNull(SelectedV))
19903ec848bcSHaicheng Wu       SROAArgValues[&SI] = SROAArg;
19913ec848bcSHaicheng Wu   }
19923ec848bcSHaicheng Wu 
19933ec848bcSHaicheng Wu   return true;
19943ec848bcSHaicheng Wu }
19953ec848bcSHaicheng Wu 
19967adc3a2bSChandler Carruth bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) {
19977adc3a2bSChandler Carruth   // We model unconditional switches as free, see the comments on handling
19987adc3a2bSChandler Carruth   // branches.
19997adc3a2bSChandler Carruth   if (isa<ConstantInt>(SI.getCondition()))
20007adc3a2bSChandler Carruth     return true;
20017adc3a2bSChandler Carruth   if (Value *V = SimplifiedValues.lookup(SI.getCondition()))
20027adc3a2bSChandler Carruth     if (isa<ConstantInt>(V))
20037adc3a2bSChandler Carruth       return true;
20047adc3a2bSChandler Carruth 
20057ad02eeeSEric Christopher   // Assume the most general case where the switch is lowered into
2006919f9e8dSJun Bum Lim   // either a jump table, bit test, or a balanced binary tree consisting of
2007919f9e8dSJun Bum Lim   // case clusters without merging adjacent clusters with the same
2008919f9e8dSJun Bum Lim   // destination. We do not consider the switches that are lowered with a mix
2009919f9e8dSJun Bum Lim   // of jump table/bit test/binary search tree. The cost of the switch is
2010919f9e8dSJun Bum Lim   // proportional to the size of the tree or the size of jump table range.
20112960d41eSJun Bum Lim   //
20122960d41eSJun Bum Lim   // NB: We convert large switches which are just used to initialize large phi
20132960d41eSJun Bum Lim   // nodes to lookup tables instead in simplify-cfg, so this shouldn't prevent
20142960d41eSJun Bum Lim   // inlining those. It will prevent inlining in cases where the optimization
20152960d41eSJun Bum Lim   // does not (yet) fire.
2016919f9e8dSJun Bum Lim 
2017919f9e8dSJun Bum Lim   unsigned JumpTableSize = 0;
201808e2386dSMircea Trofin   BlockFrequencyInfo *BFI = GetBFI ? &(GetBFI(F)) : nullptr;
2019919f9e8dSJun Bum Lim   unsigned NumCaseCluster =
20200d987e41SHiroshi Yamauchi       TTI.getEstimatedNumberOfCaseClusters(SI, JumpTableSize, PSI, BFI);
2021919f9e8dSJun Bum Lim 
202206408758SMircea Trofin   onFinalizeSwitch(JumpTableSize, NumCaseCluster);
2023919f9e8dSJun Bum Lim   return false;
2024919f9e8dSJun Bum Lim }
2025919f9e8dSJun Bum Lim 
20267adc3a2bSChandler Carruth bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) {
20277adc3a2bSChandler Carruth   // We never want to inline functions that contain an indirectbr.  This is
20287adc3a2bSChandler Carruth   // incorrect because all the blockaddress's (in static global initializers
20297adc3a2bSChandler Carruth   // for example) would be referring to the original function, and this
20307adc3a2bSChandler Carruth   // indirect jump would jump from the inlined copy of the function into the
20317adc3a2bSChandler Carruth   // original function which is extremely undefined behavior.
20327adc3a2bSChandler Carruth   // FIXME: This logic isn't really right; we can safely inline functions with
20337adc3a2bSChandler Carruth   // indirectbr's as long as no other function or global references the
20347adc3a2bSChandler Carruth   // blockaddress of a block within the current function.
20357adc3a2bSChandler Carruth   HasIndirectBr = true;
20367adc3a2bSChandler Carruth   return false;
20377adc3a2bSChandler Carruth }
20387adc3a2bSChandler Carruth 
20397adc3a2bSChandler Carruth bool CallAnalyzer::visitResumeInst(ResumeInst &RI) {
20407adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
20417adc3a2bSChandler Carruth   // the inline cost of a resume instruction.
20427adc3a2bSChandler Carruth   return false;
20437adc3a2bSChandler Carruth }
20447adc3a2bSChandler Carruth 
20457adc3a2bSChandler Carruth bool CallAnalyzer::visitCleanupReturnInst(CleanupReturnInst &CRI) {
20467adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
20477adc3a2bSChandler Carruth   // the inline cost of a cleanupret instruction.
20487adc3a2bSChandler Carruth   return false;
20497adc3a2bSChandler Carruth }
20507adc3a2bSChandler Carruth 
20517adc3a2bSChandler Carruth bool CallAnalyzer::visitCatchReturnInst(CatchReturnInst &CRI) {
20527adc3a2bSChandler Carruth   // FIXME: It's not clear that a single instruction is an accurate model for
20538220bcc5SJoseph Tremoulet   // the inline cost of a catchret instruction.
20547adc3a2bSChandler Carruth   return false;
20557adc3a2bSChandler Carruth }
20567adc3a2bSChandler Carruth 
20577adc3a2bSChandler Carruth bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) {
20587adc3a2bSChandler Carruth   // FIXME: It might be reasonably to discount the cost of instructions leading
20597adc3a2bSChandler Carruth   // to unreachable as they have the lowest possible impact on both runtime and
20607adc3a2bSChandler Carruth   // code size.
20617adc3a2bSChandler Carruth   return true; // No actual code is needed for unreachable.
20627adc3a2bSChandler Carruth }
20637adc3a2bSChandler Carruth 
20647adc3a2bSChandler Carruth bool CallAnalyzer::visitInstruction(Instruction &I) {
20657adc3a2bSChandler Carruth   // Some instructions are free. All of the free intrinsics can also be
20667adc3a2bSChandler Carruth   // handled by SROA, etc.
2067e9c9329aSSam Parker   if (TargetTransformInfo::TCC_Free ==
2068e9c9329aSSam Parker       TTI.getUserCost(&I, TargetTransformInfo::TCK_SizeAndLatency))
20697adc3a2bSChandler Carruth     return true;
20707adc3a2bSChandler Carruth 
20717adc3a2bSChandler Carruth   // We found something we don't understand or can't handle. Mark any SROA-able
20727adc3a2bSChandler Carruth   // values in the operand list as no longer viable.
207391aff1d8SNick Desaulniers   for (const Use &Op : I.operands())
207491aff1d8SNick Desaulniers     disableSROA(Op);
20757adc3a2bSChandler Carruth 
20767adc3a2bSChandler Carruth   return false;
20777adc3a2bSChandler Carruth }
20787adc3a2bSChandler Carruth 
20795f8f34e4SAdrian Prantl /// Analyze a basic block for its contribution to the inline cost.
20807adc3a2bSChandler Carruth ///
20817adc3a2bSChandler Carruth /// This method walks the analyzer over every instruction in the given basic
20827adc3a2bSChandler Carruth /// block and accounts for their cost during inlining at this callsite. It
20837adc3a2bSChandler Carruth /// aborts early if the threshold has been exceeded or an impossible to inline
20847adc3a2bSChandler Carruth /// construct has been detected. It returns false if inlining is no longer
20857adc3a2bSChandler Carruth /// viable, and true if inlining remains viable.
2086c0aa4b75SDavid Bolvansky InlineResult
2087c0aa4b75SDavid Bolvansky CallAnalyzer::analyzeBlock(BasicBlock *BB,
20887adc3a2bSChandler Carruth                            SmallPtrSetImpl<const Value *> &EphValues) {
208991aff1d8SNick Desaulniers   for (Instruction &I : *BB) {
20907adc3a2bSChandler Carruth     // FIXME: Currently, the number of instructions in a function regardless of
20917adc3a2bSChandler Carruth     // our ability to simplify them during inline to constants or dead code,
20927adc3a2bSChandler Carruth     // are actually used by the vector bonus heuristic. As long as that's true,
20937adc3a2bSChandler Carruth     // we have to special case debug intrinsics here to prevent differences in
20947adc3a2bSChandler Carruth     // inlining due to debug symbols. Eventually, the number of unsimplified
20957adc3a2bSChandler Carruth     // instructions shouldn't factor into the cost computation, but until then,
20967adc3a2bSChandler Carruth     // hack around it here.
20977adc3a2bSChandler Carruth     if (isa<DbgInfoIntrinsic>(I))
20987adc3a2bSChandler Carruth       continue;
20997adc3a2bSChandler Carruth 
2100f3c44569SHongtao Yu     // Skip pseudo-probes.
2101f3c44569SHongtao Yu     if (isa<PseudoProbeInst>(I))
2102f3c44569SHongtao Yu       continue;
2103f3c44569SHongtao Yu 
21047adc3a2bSChandler Carruth     // Skip ephemeral values.
210591aff1d8SNick Desaulniers     if (EphValues.count(&I))
21067adc3a2bSChandler Carruth       continue;
21077adc3a2bSChandler Carruth 
21087adc3a2bSChandler Carruth     ++NumInstructions;
210991aff1d8SNick Desaulniers     if (isa<ExtractElementInst>(I) || I.getType()->isVectorTy())
21107adc3a2bSChandler Carruth       ++NumVectorInstructions;
21117adc3a2bSChandler Carruth 
21127adc3a2bSChandler Carruth     // If the instruction simplified to a constant, there is no cost to this
21137adc3a2bSChandler Carruth     // instruction. Visit the instructions using our InstVisitor to account for
21147adc3a2bSChandler Carruth     // all of the per-instruction logic. The visit tree returns true if we
21157adc3a2bSChandler Carruth     // consumed the instruction in any way, and false if the instruction's base
21167adc3a2bSChandler Carruth     // cost should count against inlining.
211791aff1d8SNick Desaulniers     onInstructionAnalysisStart(&I);
2118c965fd94SKirill Naumov 
211991aff1d8SNick Desaulniers     if (Base::visit(&I))
21207adc3a2bSChandler Carruth       ++NumInstructionsSimplified;
21217adc3a2bSChandler Carruth     else
212214a16faeSMircea Trofin       onMissedSimplification();
21237adc3a2bSChandler Carruth 
212491aff1d8SNick Desaulniers     onInstructionAnalysisFinish(&I);
21250812c5beSHaicheng Wu     using namespace ore;
21267adc3a2bSChandler Carruth     // If the visit this instruction detected an uninlinable pattern, abort.
21275466597fSMircea Trofin     InlineResult IR = InlineResult::success();
2128c0aa4b75SDavid Bolvansky     if (IsRecursiveCall)
21295466597fSMircea Trofin       IR = InlineResult::failure("recursive");
2130c0aa4b75SDavid Bolvansky     else if (ExposesReturnsTwice)
21315466597fSMircea Trofin       IR = InlineResult::failure("exposes returns twice");
2132c0aa4b75SDavid Bolvansky     else if (HasDynamicAlloca)
21335466597fSMircea Trofin       IR = InlineResult::failure("dynamic alloca");
2134c0aa4b75SDavid Bolvansky     else if (HasIndirectBr)
21355466597fSMircea Trofin       IR = InlineResult::failure("indirect branch");
2136c0aa4b75SDavid Bolvansky     else if (HasUninlineableIntrinsic)
21375466597fSMircea Trofin       IR = InlineResult::failure("uninlinable intrinsic");
213877beee41SSameer AbuAsal     else if (InitsVargArgs)
21395466597fSMircea Trofin       IR = InlineResult::failure("varargs");
21405466597fSMircea Trofin     if (!IR.isSuccess()) {
21410812c5beSHaicheng Wu       if (ORE)
21429590658fSVivek Pandya         ORE->emit([&]() {
21439590658fSVivek Pandya           return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline",
2144652168a9SFedor Sergeev                                           &CandidateCall)
2145c0aa4b75SDavid Bolvansky                  << NV("Callee", &F) << " has uninlinable pattern ("
21465466597fSMircea Trofin                  << NV("InlineResult", IR.getFailureReason())
2147c0aa4b75SDavid Bolvansky                  << ") and cost is not fully computed";
21489590658fSVivek Pandya         });
2149c0aa4b75SDavid Bolvansky       return IR;
21500812c5beSHaicheng Wu     }
21517adc3a2bSChandler Carruth 
21527adc3a2bSChandler Carruth     // If the caller is a recursive function then we don't want to inline
21537adc3a2bSChandler Carruth     // functions which allocate a lot of stack space because it would increase
21547adc3a2bSChandler Carruth     // the caller stack usage dramatically.
21557adc3a2bSChandler Carruth     if (IsCallerRecursive &&
21560812c5beSHaicheng Wu         AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller) {
21575466597fSMircea Trofin       auto IR =
21585466597fSMircea Trofin           InlineResult::failure("recursive and allocates too much stack space");
21590812c5beSHaicheng Wu       if (ORE)
21609590658fSVivek Pandya         ORE->emit([&]() {
21619590658fSVivek Pandya           return OptimizationRemarkMissed(DEBUG_TYPE, "NeverInline",
2162652168a9SFedor Sergeev                                           &CandidateCall)
21635466597fSMircea Trofin                  << NV("Callee", &F) << " is "
21645466597fSMircea Trofin                  << NV("InlineResult", IR.getFailureReason())
2165c0aa4b75SDavid Bolvansky                  << ". Cost is not fully computed";
21669590658fSVivek Pandya         });
2167c0aa4b75SDavid Bolvansky       return IR;
21680812c5beSHaicheng Wu     }
21697adc3a2bSChandler Carruth 
217006408758SMircea Trofin     if (shouldStop())
21715466597fSMircea Trofin       return InlineResult::failure(
21725466597fSMircea Trofin           "Call site analysis is not favorable to inlining.");
21737adc3a2bSChandler Carruth   }
21747adc3a2bSChandler Carruth 
21755466597fSMircea Trofin   return InlineResult::success();
21767adc3a2bSChandler Carruth }
21777adc3a2bSChandler Carruth 
21785f8f34e4SAdrian Prantl /// Compute the base pointer and cumulative constant offsets for V.
21797adc3a2bSChandler Carruth ///
21807adc3a2bSChandler Carruth /// This strips all constant offsets off of V, leaving it the base pointer, and
21817adc3a2bSChandler Carruth /// accumulates the total constant offset applied in the returned constant. It
21827adc3a2bSChandler Carruth /// returns 0 if V is not a pointer, and returns the constant '0' if there are
21837adc3a2bSChandler Carruth /// no constant offsets applied.
21847adc3a2bSChandler Carruth ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
21857adc3a2bSChandler Carruth   if (!V->getType()->isPointerTy())
21867adc3a2bSChandler Carruth     return nullptr;
21877adc3a2bSChandler Carruth 
218877f32994SBjorn Pettersson   unsigned AS = V->getType()->getPointerAddressSpace();
2189945b7e5aSElena Demikhovsky   unsigned IntPtrWidth = DL.getIndexSizeInBits(AS);
21907adc3a2bSChandler Carruth   APInt Offset = APInt::getNullValue(IntPtrWidth);
21917adc3a2bSChandler Carruth 
21927adc3a2bSChandler Carruth   // Even though we don't look through PHI nodes, we could be called on an
21937adc3a2bSChandler Carruth   // instruction in an unreachable block, which may be on a cycle.
21947adc3a2bSChandler Carruth   SmallPtrSet<Value *, 4> Visited;
21957adc3a2bSChandler Carruth   Visited.insert(V);
21967adc3a2bSChandler Carruth   do {
21977adc3a2bSChandler Carruth     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
21987adc3a2bSChandler Carruth       if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
21997adc3a2bSChandler Carruth         return nullptr;
22007adc3a2bSChandler Carruth       V = GEP->getPointerOperand();
22017adc3a2bSChandler Carruth     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
22027adc3a2bSChandler Carruth       V = cast<Operator>(V)->getOperand(0);
22037adc3a2bSChandler Carruth     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
22045ce32728SSanjoy Das       if (GA->isInterposable())
22057adc3a2bSChandler Carruth         break;
22067adc3a2bSChandler Carruth       V = GA->getAliasee();
22077adc3a2bSChandler Carruth     } else {
22087adc3a2bSChandler Carruth       break;
22097adc3a2bSChandler Carruth     }
22107adc3a2bSChandler Carruth     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
22117adc3a2bSChandler Carruth   } while (Visited.insert(V).second);
22127adc3a2bSChandler Carruth 
221397572775SNicola Zaghen   Type *IdxPtrTy = DL.getIndexType(V->getType());
221497572775SNicola Zaghen   return cast<ConstantInt>(ConstantInt::get(IdxPtrTy, Offset));
22157adc3a2bSChandler Carruth }
22167adc3a2bSChandler Carruth 
22175f8f34e4SAdrian Prantl /// Find dead blocks due to deleted CFG edges during inlining.
22183739e14aSHaicheng Wu ///
22193739e14aSHaicheng Wu /// If we know the successor of the current block, \p CurrBB, has to be \p
22203739e14aSHaicheng Wu /// NextBB, the other successors of \p CurrBB are dead if these successors have
22213739e14aSHaicheng Wu /// no live incoming CFG edges.  If one block is found to be dead, we can
22223739e14aSHaicheng Wu /// continue growing the dead block list by checking the successors of the dead
22233739e14aSHaicheng Wu /// blocks to see if all their incoming edges are dead or not.
22243739e14aSHaicheng Wu void CallAnalyzer::findDeadBlocks(BasicBlock *CurrBB, BasicBlock *NextBB) {
22253739e14aSHaicheng Wu   auto IsEdgeDead = [&](BasicBlock *Pred, BasicBlock *Succ) {
222602a2bb2fSHiroshi Inoue     // A CFG edge is dead if the predecessor is dead or the predecessor has a
22273739e14aSHaicheng Wu     // known successor which is not the one under exam.
22283739e14aSHaicheng Wu     return (DeadBlocks.count(Pred) ||
22293739e14aSHaicheng Wu             (KnownSuccessors[Pred] && KnownSuccessors[Pred] != Succ));
22303739e14aSHaicheng Wu   };
22313739e14aSHaicheng Wu 
22323739e14aSHaicheng Wu   auto IsNewlyDead = [&](BasicBlock *BB) {
22333739e14aSHaicheng Wu     // If all the edges to a block are dead, the block is also dead.
22343739e14aSHaicheng Wu     return (!DeadBlocks.count(BB) &&
22353739e14aSHaicheng Wu             llvm::all_of(predecessors(BB),
22363739e14aSHaicheng Wu                          [&](BasicBlock *P) { return IsEdgeDead(P, BB); }));
22373739e14aSHaicheng Wu   };
22383739e14aSHaicheng Wu 
22393739e14aSHaicheng Wu   for (BasicBlock *Succ : successors(CurrBB)) {
22403739e14aSHaicheng Wu     if (Succ == NextBB || !IsNewlyDead(Succ))
22413739e14aSHaicheng Wu       continue;
22423739e14aSHaicheng Wu     SmallVector<BasicBlock *, 4> NewDead;
22433739e14aSHaicheng Wu     NewDead.push_back(Succ);
22443739e14aSHaicheng Wu     while (!NewDead.empty()) {
22453739e14aSHaicheng Wu       BasicBlock *Dead = NewDead.pop_back_val();
22463739e14aSHaicheng Wu       if (DeadBlocks.insert(Dead))
22473739e14aSHaicheng Wu         // Continue growing the dead block lists.
22483739e14aSHaicheng Wu         for (BasicBlock *S : successors(Dead))
22493739e14aSHaicheng Wu           if (IsNewlyDead(S))
22503739e14aSHaicheng Wu             NewDead.push_back(S);
22513739e14aSHaicheng Wu     }
22523739e14aSHaicheng Wu   }
22533739e14aSHaicheng Wu }
22543739e14aSHaicheng Wu 
22555f8f34e4SAdrian Prantl /// Analyze a call site for potential inlining.
22567adc3a2bSChandler Carruth ///
22577adc3a2bSChandler Carruth /// Returns true if inlining this call is viable, and false if it is not
22587adc3a2bSChandler Carruth /// viable. It computes the cost and adjusts the threshold based on numerous
22597adc3a2bSChandler Carruth /// factors and heuristics. If this method returns false but the computed cost
22607adc3a2bSChandler Carruth /// is below the computed threshold, then inlining was forcibly disabled by
22617adc3a2bSChandler Carruth /// some artifact of the routine.
226293ac81ccSMircea Trofin InlineResult CallAnalyzer::analyze() {
22637adc3a2bSChandler Carruth   ++NumCallsAnalyzed;
22647adc3a2bSChandler Carruth 
226506408758SMircea Trofin   auto Result = onAnalysisStart();
22665466597fSMircea Trofin   if (!Result.isSuccess())
226706408758SMircea Trofin     return Result;
22687adc3a2bSChandler Carruth 
22697adc3a2bSChandler Carruth   if (F.empty())
22705466597fSMircea Trofin     return InlineResult::success();
22717adc3a2bSChandler Carruth 
227293ac81ccSMircea Trofin   Function *Caller = CandidateCall.getFunction();
22737adc3a2bSChandler Carruth   // Check if the caller function is recursive itself.
22747adc3a2bSChandler Carruth   for (User *U : Caller->users()) {
2275652168a9SFedor Sergeev     CallBase *Call = dyn_cast<CallBase>(U);
2276652168a9SFedor Sergeev     if (Call && Call->getFunction() == Caller) {
22777adc3a2bSChandler Carruth       IsCallerRecursive = true;
22787adc3a2bSChandler Carruth       break;
22797adc3a2bSChandler Carruth     }
22807adc3a2bSChandler Carruth   }
22817adc3a2bSChandler Carruth 
22827adc3a2bSChandler Carruth   // Populate our simplified values by mapping from function arguments to call
22837adc3a2bSChandler Carruth   // arguments with known important simplifications.
228493ac81ccSMircea Trofin   auto CAI = CandidateCall.arg_begin();
228591aff1d8SNick Desaulniers   for (Argument &FAI : F.args()) {
228693ac81ccSMircea Trofin     assert(CAI != CandidateCall.arg_end());
22877adc3a2bSChandler Carruth     if (Constant *C = dyn_cast<Constant>(CAI))
228891aff1d8SNick Desaulniers       SimplifiedValues[&FAI] = C;
22897adc3a2bSChandler Carruth 
22907adc3a2bSChandler Carruth     Value *PtrArg = *CAI;
22917adc3a2bSChandler Carruth     if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
229291aff1d8SNick Desaulniers       ConstantOffsetPtrs[&FAI] = std::make_pair(PtrArg, C->getValue());
22937adc3a2bSChandler Carruth 
22947adc3a2bSChandler Carruth       // We can SROA any pointer arguments derived from alloca instructions.
229506408758SMircea Trofin       if (auto *SROAArg = dyn_cast<AllocaInst>(PtrArg)) {
229691aff1d8SNick Desaulniers         SROAArgValues[&FAI] = SROAArg;
229706408758SMircea Trofin         onInitializeSROAArg(SROAArg);
22982e42cc7aSMircea Trofin         EnabledSROAAllocas.insert(SROAArg);
22997adc3a2bSChandler Carruth       }
23007adc3a2bSChandler Carruth     }
230191aff1d8SNick Desaulniers     ++CAI;
23027adc3a2bSChandler Carruth   }
23037adc3a2bSChandler Carruth   NumConstantArgs = SimplifiedValues.size();
23047adc3a2bSChandler Carruth   NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
23057adc3a2bSChandler Carruth   NumAllocaArgs = SROAArgValues.size();
23067adc3a2bSChandler Carruth 
23077adc3a2bSChandler Carruth   // FIXME: If a caller has multiple calls to a callee, we end up recomputing
23087adc3a2bSChandler Carruth   // the ephemeral values multiple times (and they're completely determined by
23097adc3a2bSChandler Carruth   // the callee, so this is purely duplicate work).
23107adc3a2bSChandler Carruth   SmallPtrSet<const Value *, 32> EphValues;
2311aec2fa35SDaniel Jasper   CodeMetrics::collectEphemeralValues(&F, &GetAssumptionCache(F), EphValues);
23127adc3a2bSChandler Carruth 
23137adc3a2bSChandler Carruth   // The worklist of live basic blocks in the callee *after* inlining. We avoid
23147adc3a2bSChandler Carruth   // adding basic blocks of the callee which can be proven to be dead for this
23157adc3a2bSChandler Carruth   // particular call site in order to get more accurate cost estimates. This
23167adc3a2bSChandler Carruth   // requires a somewhat heavyweight iteration pattern: we need to walk the
23177adc3a2bSChandler Carruth   // basic blocks in a breadth-first order as we insert live successors. To
23187adc3a2bSChandler Carruth   // accomplish this, prioritizing for small iterations because we exit after
23197adc3a2bSChandler Carruth   // crossing our threshold, we use a small-size optimized SetVector.
23207adc3a2bSChandler Carruth   typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
2321567556aaSChad Rosier                     SmallPtrSet<BasicBlock *, 16>>
2322567556aaSChad Rosier       BBSetVector;
23237adc3a2bSChandler Carruth   BBSetVector BBWorklist;
23247adc3a2bSChandler Carruth   BBWorklist.insert(&F.getEntryBlock());
232506408758SMircea Trofin 
23267adc3a2bSChandler Carruth   // Note that we *must not* cache the size, this loop grows the worklist.
23277adc3a2bSChandler Carruth   for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
232806408758SMircea Trofin     if (shouldStop())
23297adc3a2bSChandler Carruth       break;
23307adc3a2bSChandler Carruth 
23317adc3a2bSChandler Carruth     BasicBlock *BB = BBWorklist[Idx];
23327adc3a2bSChandler Carruth     if (BB->empty())
23337adc3a2bSChandler Carruth       continue;
23347adc3a2bSChandler Carruth 
23359895c701SKazu Hirata     onBlockStart(BB);
23369895c701SKazu Hirata 
2337639b29b1SNick Desaulniers     // Disallow inlining a blockaddress with uses other than strictly callbr.
2338639b29b1SNick Desaulniers     // A blockaddress only has defined behavior for an indirect branch in the
2339639b29b1SNick Desaulniers     // same function, and we do not currently support inlining indirect
2340639b29b1SNick Desaulniers     // branches.  But, the inliner may not see an indirect branch that ends up
2341639b29b1SNick Desaulniers     // being dead code at a particular call site. If the blockaddress escapes
2342639b29b1SNick Desaulniers     // the function, e.g., via a global variable, inlining may lead to an
2343639b29b1SNick Desaulniers     // invalid cross-function reference.
2344639b29b1SNick Desaulniers     // FIXME: pr/39560: continue relaxing this overt restriction.
23456a84cd3bSNick Desaulniers     if (BB->hasAddressTaken())
2346639b29b1SNick Desaulniers       for (User *U : BlockAddress::get(&*BB)->users())
2347639b29b1SNick Desaulniers         if (!isa<CallBrInst>(*U))
23485466597fSMircea Trofin           return InlineResult::failure("blockaddress used outside of callbr");
23497adc3a2bSChandler Carruth 
23507adc3a2bSChandler Carruth     // Analyze the cost of this block. If we blow through the threshold, this
23517adc3a2bSChandler Carruth     // returns false, and we can bail on out.
2352c0aa4b75SDavid Bolvansky     InlineResult IR = analyzeBlock(BB, EphValues);
23535466597fSMircea Trofin     if (!IR.isSuccess())
2354c0aa4b75SDavid Bolvansky       return IR;
23557adc3a2bSChandler Carruth 
2356edb12a83SChandler Carruth     Instruction *TI = BB->getTerminator();
23577adc3a2bSChandler Carruth 
23587adc3a2bSChandler Carruth     // Add in the live successors by first checking whether we have terminator
23597adc3a2bSChandler Carruth     // that may be simplified based on the values simplified by this call.
23607adc3a2bSChandler Carruth     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
23617adc3a2bSChandler Carruth       if (BI->isConditional()) {
23627adc3a2bSChandler Carruth         Value *Cond = BI->getCondition();
2363567556aaSChad Rosier         if (ConstantInt *SimpleCond =
2364567556aaSChad Rosier                 dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
23653739e14aSHaicheng Wu           BasicBlock *NextBB = BI->getSuccessor(SimpleCond->isZero() ? 1 : 0);
23663739e14aSHaicheng Wu           BBWorklist.insert(NextBB);
23673739e14aSHaicheng Wu           KnownSuccessors[BB] = NextBB;
23683739e14aSHaicheng Wu           findDeadBlocks(BB, NextBB);
23697adc3a2bSChandler Carruth           continue;
23707adc3a2bSChandler Carruth         }
23717adc3a2bSChandler Carruth       }
23727adc3a2bSChandler Carruth     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
23737adc3a2bSChandler Carruth       Value *Cond = SI->getCondition();
2374567556aaSChad Rosier       if (ConstantInt *SimpleCond =
2375567556aaSChad Rosier               dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
23763739e14aSHaicheng Wu         BasicBlock *NextBB = SI->findCaseValue(SimpleCond)->getCaseSuccessor();
23773739e14aSHaicheng Wu         BBWorklist.insert(NextBB);
23783739e14aSHaicheng Wu         KnownSuccessors[BB] = NextBB;
23793739e14aSHaicheng Wu         findDeadBlocks(BB, NextBB);
23807adc3a2bSChandler Carruth         continue;
23817adc3a2bSChandler Carruth       }
23827adc3a2bSChandler Carruth     }
23837adc3a2bSChandler Carruth 
23847adc3a2bSChandler Carruth     // If we're unable to select a particular successor, just count all of
23857adc3a2bSChandler Carruth     // them.
23867adc3a2bSChandler Carruth     for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
23877adc3a2bSChandler Carruth          ++TIdx)
23887adc3a2bSChandler Carruth       BBWorklist.insert(TI->getSuccessor(TIdx));
23897adc3a2bSChandler Carruth 
239006408758SMircea Trofin     onBlockAnalyzed(BB);
23917adc3a2bSChandler Carruth   }
23927adc3a2bSChandler Carruth 
239393ac81ccSMircea Trofin   bool OnlyOneCallAndLocalLinkage = F.hasLocalLinkage() && F.hasOneUse() &&
239493ac81ccSMircea Trofin                                     &F == CandidateCall.getCalledFunction();
23957adc3a2bSChandler Carruth   // If this is a noduplicate call, we can still inline as long as
23967adc3a2bSChandler Carruth   // inlining this would cause the removal of the caller (so the instruction
23977adc3a2bSChandler Carruth   // is not actually duplicated, just moved).
23987adc3a2bSChandler Carruth   if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall)
23995466597fSMircea Trofin     return InlineResult::failure("noduplicate");
24007adc3a2bSChandler Carruth 
240106408758SMircea Trofin   return finalizeAnalysis();
24027adc3a2bSChandler Carruth }
24037adc3a2bSChandler Carruth 
2404ca899bf9SKirill Naumov void InlineCostCallAnalyzer::print() {
24057adc3a2bSChandler Carruth #define DEBUG_PRINT_STAT(x) dbgs() << "      " #x ": " << x << "\n"
24061022b5ebSKirill Naumov   if (PrintInstructionComments)
2407c965fd94SKirill Naumov     F.print(dbgs(), &Writer);
24087adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantArgs);
24097adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
24107adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumAllocaArgs);
24117adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantPtrCmps);
24127adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumConstantPtrDiffs);
24137adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumInstructionsSimplified);
24147adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(NumInstructions);
24157adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(SROACostSavings);
24167adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(SROACostSavingsLost);
2417a4461515SHaicheng Wu   DEBUG_PRINT_STAT(LoadEliminationCost);
24187adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
24197adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(Cost);
24207adc3a2bSChandler Carruth   DEBUG_PRINT_STAT(Threshold);
24217adc3a2bSChandler Carruth #undef DEBUG_PRINT_STAT
24227adc3a2bSChandler Carruth }
2423ca899bf9SKirill Naumov 
2424ca899bf9SKirill Naumov #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2425ca899bf9SKirill Naumov /// Dump stats about this call's analysis.
2426ca899bf9SKirill Naumov LLVM_DUMP_METHOD void InlineCostCallAnalyzer::dump() {
2427ca899bf9SKirill Naumov   print();
2428ca899bf9SKirill Naumov }
24297adc3a2bSChandler Carruth #endif
24307adc3a2bSChandler Carruth 
24315f8f34e4SAdrian Prantl /// Test that there are no attribute conflicts between Caller and Callee
24327adc3a2bSChandler Carruth ///        that prevent inlining.
2433f9ca75f1STeresa Johnson static bool functionsHaveCompatibleAttributes(
2434f9ca75f1STeresa Johnson     Function *Caller, Function *Callee, TargetTransformInfo &TTI,
2435f9ca75f1STeresa Johnson     function_ref<const TargetLibraryInfo &(Function &)> &GetTLI) {
2436f9ca75f1STeresa Johnson   // Note that CalleeTLI must be a copy not a reference. The legacy pass manager
2437f9ca75f1STeresa Johnson   // caches the most recently created TLI in the TargetLibraryInfoWrapperPass
2438f9ca75f1STeresa Johnson   // object, and always returns the same object (which is overwritten on each
2439f9ca75f1STeresa Johnson   // GetTLI call). Therefore we copy the first result.
2440f9ca75f1STeresa Johnson   auto CalleeTLI = GetTLI(*Callee);
24417adc3a2bSChandler Carruth   return TTI.areInlineCompatible(Caller, Callee) &&
2442f9ca75f1STeresa Johnson          GetTLI(*Caller).areInlineCompatible(CalleeTLI,
2443ed03d948SMehdi Amini                                              InlineCallerSupersetNoBuiltin) &&
24441cb242ebSAkira Hatanaka          AttributeFuncs::areInlineCompatible(*Caller, *Callee);
24457adc3a2bSChandler Carruth }
24467adc3a2bSChandler Carruth 
2447652168a9SFedor Sergeev int llvm::getCallsiteCost(CallBase &Call, const DataLayout &DL) {
2448351d9b01SXinliang David Li   int Cost = 0;
2449652168a9SFedor Sergeev   for (unsigned I = 0, E = Call.arg_size(); I != E; ++I) {
2450652168a9SFedor Sergeev     if (Call.isByValArgument(I)) {
2451351d9b01SXinliang David Li       // We approximate the number of loads and stores needed by dividing the
2452351d9b01SXinliang David Li       // size of the byval type by the target's pointer size.
2453652168a9SFedor Sergeev       PointerType *PTy = cast<PointerType>(Call.getArgOperand(I)->getType());
2454351d9b01SXinliang David Li       unsigned TypeSize = DL.getTypeSizeInBits(PTy->getElementType());
245577f32994SBjorn Pettersson       unsigned AS = PTy->getAddressSpace();
245677f32994SBjorn Pettersson       unsigned PointerSize = DL.getPointerSizeInBits(AS);
2457351d9b01SXinliang David Li       // Ceiling division.
2458351d9b01SXinliang David Li       unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
2459351d9b01SXinliang David Li 
2460351d9b01SXinliang David Li       // If it generates more than 8 stores it is likely to be expanded as an
2461351d9b01SXinliang David Li       // inline memcpy so we take that as an upper bound. Otherwise we assume
2462351d9b01SXinliang David Li       // one load and one store per word copied.
2463351d9b01SXinliang David Li       // FIXME: The maxStoresPerMemcpy setting from the target should be used
2464351d9b01SXinliang David Li       // here instead of a magic number of 8, but it's not available via
2465351d9b01SXinliang David Li       // DataLayout.
2466351d9b01SXinliang David Li       NumStores = std::min(NumStores, 8U);
2467351d9b01SXinliang David Li 
2468351d9b01SXinliang David Li       Cost += 2 * NumStores * InlineConstants::InstrCost;
2469351d9b01SXinliang David Li     } else {
2470351d9b01SXinliang David Li       // For non-byval arguments subtract off one instruction per call
2471351d9b01SXinliang David Li       // argument.
2472351d9b01SXinliang David Li       Cost += InlineConstants::InstrCost;
2473351d9b01SXinliang David Li     }
2474351d9b01SXinliang David Li   }
2475351d9b01SXinliang David Li   // The call instruction also disappears after inlining.
2476351d9b01SXinliang David Li   Cost += InlineConstants::InstrCost + InlineConstants::CallPenalty;
2477351d9b01SXinliang David Li   return Cost;
2478351d9b01SXinliang David Li }
2479351d9b01SXinliang David Li 
2480ab6a6837SSean Silva InlineCost llvm::getInlineCost(
2481652168a9SFedor Sergeev     CallBase &Call, const InlineParams &Params, TargetTransformInfo &CalleeTTI,
248208e2386dSMircea Trofin     function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
2483f9ca75f1STeresa Johnson     function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
248408e2386dSMircea Trofin     function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
24850812c5beSHaicheng Wu     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
2486652168a9SFedor Sergeev   return getInlineCost(Call, Call.getCalledFunction(), Params, CalleeTTI,
248708e2386dSMircea Trofin                        GetAssumptionCache, GetTLI, GetBFI, PSI, ORE);
2488b9f7120eSEaswaran Raman }
2489b9f7120eSEaswaran Raman 
2490011a07c0SMircea Trofin Optional<int> llvm::getInliningCostEstimate(
24918a4013edSMircea Trofin     CallBase &Call, TargetTransformInfo &CalleeTTI,
249208e2386dSMircea Trofin     function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
249308e2386dSMircea Trofin     function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
24948a4013edSMircea Trofin     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
24958a4013edSMircea Trofin   const InlineParams Params = {/* DefaultThreshold*/ 0,
24968a4013edSMircea Trofin                                /*HintThreshold*/ {},
24978a4013edSMircea Trofin                                /*ColdThreshold*/ {},
24988a4013edSMircea Trofin                                /*OptSizeThreshold*/ {},
24998a4013edSMircea Trofin                                /*OptMinSizeThreshold*/ {},
25008a4013edSMircea Trofin                                /*HotCallSiteThreshold*/ {},
25018a4013edSMircea Trofin                                /*LocallyHotCallSiteThreshold*/ {},
25028a4013edSMircea Trofin                                /*ColdCallSiteThreshold*/ {},
2503347a599eSKazu Hirata                                /*ComputeFullInlineCost*/ true,
2504347a599eSKazu Hirata                                /*EnableDeferral*/ true};
25058a4013edSMircea Trofin 
250608e2386dSMircea Trofin   InlineCostCallAnalyzer CA(*Call.getCalledFunction(), Call, Params, CalleeTTI,
250708e2386dSMircea Trofin                             GetAssumptionCache, GetBFI, PSI, ORE, true,
25088a4013edSMircea Trofin                             /*IgnoreThreshold*/ true);
25098a4013edSMircea Trofin   auto R = CA.analyze();
25108a4013edSMircea Trofin   if (!R.isSuccess())
25118a4013edSMircea Trofin     return None;
25128a4013edSMircea Trofin   return CA.getCost();
25138a4013edSMircea Trofin }
25148a4013edSMircea Trofin 
2515201498c6SMircea Trofin Optional<InlineResult> llvm::getAttributeBasedInliningDecision(
2516201498c6SMircea Trofin     CallBase &Call, Function *Callee, TargetTransformInfo &CalleeTTI,
2517201498c6SMircea Trofin     function_ref<const TargetLibraryInfo &(Function &)> GetTLI) {
2518f4bb2f0dSEaswaran Raman 
25197adc3a2bSChandler Carruth   // Cannot inline indirect calls.
25207adc3a2bSChandler Carruth   if (!Callee)
2521201498c6SMircea Trofin     return InlineResult::failure("indirect call");
25227adc3a2bSChandler Carruth 
252331e60b91SXun Li   // When callee coroutine function is inlined into caller coroutine function
252431e60b91SXun Li   // before coro-split pass,
252531e60b91SXun Li   // coro-early pass can not handle this quiet well.
252631e60b91SXun Li   // So we won't inline the coroutine function if it have not been unsplited
252731e60b91SXun Li   if (Callee->isPresplitCoroutine())
252831e60b91SXun Li     return InlineResult::failure("unsplited coroutine call");
252931e60b91SXun Li 
25303851496eSBjorn Pettersson   // Never inline calls with byval arguments that does not have the alloca
25313851496eSBjorn Pettersson   // address space. Since byval arguments can be replaced with a copy to an
25323851496eSBjorn Pettersson   // alloca, the inlined code would need to be adjusted to handle that the
25333851496eSBjorn Pettersson   // argument is in the alloca address space (so it is a little bit complicated
25343851496eSBjorn Pettersson   // to solve).
25353851496eSBjorn Pettersson   unsigned AllocaAS = Callee->getParent()->getDataLayout().getAllocaAddrSpace();
2536652168a9SFedor Sergeev   for (unsigned I = 0, E = Call.arg_size(); I != E; ++I)
2537652168a9SFedor Sergeev     if (Call.isByValArgument(I)) {
2538652168a9SFedor Sergeev       PointerType *PTy = cast<PointerType>(Call.getArgOperand(I)->getType());
25393851496eSBjorn Pettersson       if (PTy->getAddressSpace() != AllocaAS)
2540201498c6SMircea Trofin         return InlineResult::failure("byval arguments without alloca"
2541c0aa4b75SDavid Bolvansky                                      " address space");
25423851496eSBjorn Pettersson     }
25433851496eSBjorn Pettersson 
25447adc3a2bSChandler Carruth   // Calls to functions with always-inline attributes should be inlined
25457adc3a2bSChandler Carruth   // whenever possible.
2546652168a9SFedor Sergeev   if (Call.hasFnAttr(Attribute::AlwaysInline)) {
254715b17d0aSYevgeny Rouban     auto IsViable = isInlineViable(*Callee);
25485466597fSMircea Trofin     if (IsViable.isSuccess())
2549201498c6SMircea Trofin       return InlineResult::success();
2550201498c6SMircea Trofin     return InlineResult::failure(IsViable.getFailureReason());
25517adc3a2bSChandler Carruth   }
25527adc3a2bSChandler Carruth 
25537adc3a2bSChandler Carruth   // Never inline functions with conflicting attributes (unless callee has
25547adc3a2bSChandler Carruth   // always-inline attribute).
2555652168a9SFedor Sergeev   Function *Caller = Call.getCaller();
2556f9ca75f1STeresa Johnson   if (!functionsHaveCompatibleAttributes(Caller, Callee, CalleeTTI, GetTLI))
2557201498c6SMircea Trofin     return InlineResult::failure("conflicting attributes");
25587adc3a2bSChandler Carruth 
25597adc3a2bSChandler Carruth   // Don't inline this call if the caller has the optnone attribute.
256085bd3978SEvandro Menezes   if (Caller->hasOptNone())
2561201498c6SMircea Trofin     return InlineResult::failure("optnone attribute");
25627adc3a2bSChandler Carruth 
256377eeac3dSManoj Gupta   // Don't inline a function that treats null pointer as valid into a caller
256477eeac3dSManoj Gupta   // that does not have this attribute.
256577eeac3dSManoj Gupta   if (!Caller->nullPointerIsDefined() && Callee->nullPointerIsDefined())
2566201498c6SMircea Trofin     return InlineResult::failure("nullptr definitions incompatible");
256777eeac3dSManoj Gupta 
2568c0aa4b75SDavid Bolvansky   // Don't inline functions which can be interposed at link-time.
2569c0aa4b75SDavid Bolvansky   if (Callee->isInterposable())
2570201498c6SMircea Trofin     return InlineResult::failure("interposable");
2571c0aa4b75SDavid Bolvansky 
2572c0aa4b75SDavid Bolvansky   // Don't inline functions marked noinline.
2573c0aa4b75SDavid Bolvansky   if (Callee->hasFnAttribute(Attribute::NoInline))
2574201498c6SMircea Trofin     return InlineResult::failure("noinline function attribute");
2575c0aa4b75SDavid Bolvansky 
2576c0aa4b75SDavid Bolvansky   // Don't inline call sites marked noinline.
2577652168a9SFedor Sergeev   if (Call.isNoInline())
2578201498c6SMircea Trofin     return InlineResult::failure("noinline call site attribute");
2579201498c6SMircea Trofin 
2580bc044a88SNick Desaulniers   // Don't inline functions if one does not have any stack protector attribute
2581bc044a88SNick Desaulniers   // but the other does.
2582bc044a88SNick Desaulniers   if (Caller->hasStackProtectorFnAttr() && !Callee->hasStackProtectorFnAttr())
2583bc044a88SNick Desaulniers     return InlineResult::failure(
2584bc044a88SNick Desaulniers         "stack protected caller but callee requested no stack protector");
2585bc044a88SNick Desaulniers   if (Callee->hasStackProtectorFnAttr() && !Caller->hasStackProtectorFnAttr())
2586bc044a88SNick Desaulniers     return InlineResult::failure(
2587bc044a88SNick Desaulniers         "stack protected callee but caller requested no stack protector");
2588bc044a88SNick Desaulniers 
2589201498c6SMircea Trofin   return None;
2590201498c6SMircea Trofin }
2591201498c6SMircea Trofin 
2592201498c6SMircea Trofin InlineCost llvm::getInlineCost(
2593201498c6SMircea Trofin     CallBase &Call, Function *Callee, const InlineParams &Params,
2594201498c6SMircea Trofin     TargetTransformInfo &CalleeTTI,
259508e2386dSMircea Trofin     function_ref<AssumptionCache &(Function &)> GetAssumptionCache,
2596201498c6SMircea Trofin     function_ref<const TargetLibraryInfo &(Function &)> GetTLI,
259708e2386dSMircea Trofin     function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
2598201498c6SMircea Trofin     ProfileSummaryInfo *PSI, OptimizationRemarkEmitter *ORE) {
2599201498c6SMircea Trofin 
2600201498c6SMircea Trofin   auto UserDecision =
2601201498c6SMircea Trofin       llvm::getAttributeBasedInliningDecision(Call, Callee, CalleeTTI, GetTLI);
2602201498c6SMircea Trofin 
2603201498c6SMircea Trofin   if (UserDecision.hasValue()) {
2604201498c6SMircea Trofin     if (UserDecision->isSuccess())
2605201498c6SMircea Trofin       return llvm::InlineCost::getAlways("always inline attribute");
2606201498c6SMircea Trofin     return llvm::InlineCost::getNever(UserDecision->getFailureReason());
2607201498c6SMircea Trofin   }
26087adc3a2bSChandler Carruth 
2609d34e60caSNicola Zaghen   LLVM_DEBUG(llvm::dbgs() << "      Analyzing call of " << Callee->getName()
2610201498c6SMircea Trofin                           << "... (caller:" << Call.getCaller()->getName()
2611201498c6SMircea Trofin                           << ")\n");
26127adc3a2bSChandler Carruth 
261308e2386dSMircea Trofin   InlineCostCallAnalyzer CA(*Callee, Call, Params, CalleeTTI,
261408e2386dSMircea Trofin                             GetAssumptionCache, GetBFI, PSI, ORE);
261593ac81ccSMircea Trofin   InlineResult ShouldInline = CA.analyze();
26167adc3a2bSChandler Carruth 
2617d34e60caSNicola Zaghen   LLVM_DEBUG(CA.dump());
26187adc3a2bSChandler Carruth 
26197adc3a2bSChandler Carruth   // Check if there was a reason to force inlining or no inlining.
26205466597fSMircea Trofin   if (!ShouldInline.isSuccess() && CA.getCost() < CA.getThreshold())
26215466597fSMircea Trofin     return InlineCost::getNever(ShouldInline.getFailureReason());
26225466597fSMircea Trofin   if (ShouldInline.isSuccess() && CA.getCost() >= CA.getThreshold())
2623c0aa4b75SDavid Bolvansky     return InlineCost::getAlways("empty function");
26247adc3a2bSChandler Carruth 
26257adc3a2bSChandler Carruth   return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());
26267adc3a2bSChandler Carruth }
26277adc3a2bSChandler Carruth 
262815b17d0aSYevgeny Rouban InlineResult llvm::isInlineViable(Function &F) {
26297adc3a2bSChandler Carruth   bool ReturnsTwice = F.hasFnAttribute(Attribute::ReturnsTwice);
263091aff1d8SNick Desaulniers   for (BasicBlock &BB : F) {
2631639b29b1SNick Desaulniers     // Disallow inlining of functions which contain indirect branches.
263291aff1d8SNick Desaulniers     if (isa<IndirectBrInst>(BB.getTerminator()))
26335466597fSMircea Trofin       return InlineResult::failure("contains indirect branches");
263415b17d0aSYevgeny Rouban 
2635639b29b1SNick Desaulniers     // Disallow inlining of blockaddresses which are used by non-callbr
2636639b29b1SNick Desaulniers     // instructions.
263791aff1d8SNick Desaulniers     if (BB.hasAddressTaken())
263891aff1d8SNick Desaulniers       for (User *U : BlockAddress::get(&BB)->users())
2639639b29b1SNick Desaulniers         if (!isa<CallBrInst>(*U))
26405466597fSMircea Trofin           return InlineResult::failure("blockaddress used outside of callbr");
26417adc3a2bSChandler Carruth 
264291aff1d8SNick Desaulniers     for (auto &II : BB) {
2643652168a9SFedor Sergeev       CallBase *Call = dyn_cast<CallBase>(&II);
2644652168a9SFedor Sergeev       if (!Call)
26457adc3a2bSChandler Carruth         continue;
26467adc3a2bSChandler Carruth 
26477adc3a2bSChandler Carruth       // Disallow recursive calls.
2648bc044a88SNick Desaulniers       Function *Callee = Call->getCalledFunction();
2649bc044a88SNick Desaulniers       if (&F == Callee)
26505466597fSMircea Trofin         return InlineResult::failure("recursive call");
26517adc3a2bSChandler Carruth 
26527adc3a2bSChandler Carruth       // Disallow calls which expose returns-twice to a function not previously
26537adc3a2bSChandler Carruth       // attributed as such.
2654652168a9SFedor Sergeev       if (!ReturnsTwice && isa<CallInst>(Call) &&
2655652168a9SFedor Sergeev           cast<CallInst>(Call)->canReturnTwice())
26565466597fSMircea Trofin         return InlineResult::failure("exposes returns-twice attribute");
26577adc3a2bSChandler Carruth 
2658bc044a88SNick Desaulniers       if (Callee)
2659bc044a88SNick Desaulniers         switch (Callee->getIntrinsicID()) {
26601636651eSFlorian Hahn         default:
26611636651eSFlorian Hahn           break;
266206408758SMircea Trofin         case llvm::Intrinsic::icall_branch_funnel:
26634296ea72SVitaly Buka           // Disallow inlining of @llvm.icall.branch.funnel because current
26644296ea72SVitaly Buka           // backend can't separate call targets from call arguments.
26655466597fSMircea Trofin           return InlineResult::failure(
26665466597fSMircea Trofin               "disallowed inlining of @llvm.icall.branch.funnel");
266706408758SMircea Trofin         case llvm::Intrinsic::localescape:
26687adc3a2bSChandler Carruth           // Disallow inlining functions that call @llvm.localescape. Doing this
26697adc3a2bSChandler Carruth           // correctly would require major changes to the inliner.
26705466597fSMircea Trofin           return InlineResult::failure(
26715466597fSMircea Trofin               "disallowed inlining of @llvm.localescape");
26721636651eSFlorian Hahn         case llvm::Intrinsic::vastart:
267306408758SMircea Trofin           // Disallow inlining of functions that initialize VarArgs with
267406408758SMircea Trofin           // va_start.
26755466597fSMircea Trofin           return InlineResult::failure(
26765466597fSMircea Trofin               "contains VarArgs initialized with va_start");
26777adc3a2bSChandler Carruth         }
26787adc3a2bSChandler Carruth     }
26791636651eSFlorian Hahn   }
26807adc3a2bSChandler Carruth 
26815466597fSMircea Trofin   return InlineResult::success();
26827adc3a2bSChandler Carruth }
26831c57cc2bSEaswaran Raman 
26841c57cc2bSEaswaran Raman // APIs to create InlineParams based on command line flags and/or other
26851c57cc2bSEaswaran Raman // parameters.
26861c57cc2bSEaswaran Raman 
26871c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams(int Threshold) {
26881c57cc2bSEaswaran Raman   InlineParams Params;
26891c57cc2bSEaswaran Raman 
26901c57cc2bSEaswaran Raman   // This field is the threshold to use for a callee by default. This is
26911c57cc2bSEaswaran Raman   // derived from one or more of:
26921c57cc2bSEaswaran Raman   //  * optimization or size-optimization levels,
26931c57cc2bSEaswaran Raman   //  * a value passed to createFunctionInliningPass function, or
26941c57cc2bSEaswaran Raman   //  * the -inline-threshold flag.
26951c57cc2bSEaswaran Raman   //  If the -inline-threshold flag is explicitly specified, that is used
26961c57cc2bSEaswaran Raman   //  irrespective of anything else.
26971c57cc2bSEaswaran Raman   if (InlineThreshold.getNumOccurrences() > 0)
26981c57cc2bSEaswaran Raman     Params.DefaultThreshold = InlineThreshold;
26991c57cc2bSEaswaran Raman   else
27001c57cc2bSEaswaran Raman     Params.DefaultThreshold = Threshold;
27011c57cc2bSEaswaran Raman 
27021c57cc2bSEaswaran Raman   // Set the HintThreshold knob from the -inlinehint-threshold.
27031c57cc2bSEaswaran Raman   Params.HintThreshold = HintThreshold;
27041c57cc2bSEaswaran Raman 
27051c57cc2bSEaswaran Raman   // Set the HotCallSiteThreshold knob from the -hot-callsite-threshold.
27061c57cc2bSEaswaran Raman   Params.HotCallSiteThreshold = HotCallSiteThreshold;
27071c57cc2bSEaswaran Raman 
2708974d4eeaSEaswaran Raman   // If the -locally-hot-callsite-threshold is explicitly specified, use it to
2709974d4eeaSEaswaran Raman   // populate LocallyHotCallSiteThreshold. Later, we populate
2710974d4eeaSEaswaran Raman   // Params.LocallyHotCallSiteThreshold from -locally-hot-callsite-threshold if
2711974d4eeaSEaswaran Raman   // we know that optimization level is O3 (in the getInlineParams variant that
2712974d4eeaSEaswaran Raman   // takes the opt and size levels).
2713974d4eeaSEaswaran Raman   // FIXME: Remove this check (and make the assignment unconditional) after
2714974d4eeaSEaswaran Raman   // addressing size regression issues at O2.
2715974d4eeaSEaswaran Raman   if (LocallyHotCallSiteThreshold.getNumOccurrences() > 0)
2716974d4eeaSEaswaran Raman     Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold;
2717974d4eeaSEaswaran Raman 
27185a956c85SMircea Trofin   // Set the ColdCallSiteThreshold knob from the
27195a956c85SMircea Trofin   // -inline-cold-callsite-threshold.
272012585b01SEaswaran Raman   Params.ColdCallSiteThreshold = ColdCallSiteThreshold;
272112585b01SEaswaran Raman 
27221c57cc2bSEaswaran Raman   // Set the OptMinSizeThreshold and OptSizeThreshold params only if the
27231c57cc2bSEaswaran Raman   // -inlinehint-threshold commandline option is not explicitly given. If that
27241c57cc2bSEaswaran Raman   // option is present, then its value applies even for callees with size and
27251c57cc2bSEaswaran Raman   // minsize attributes.
27261c57cc2bSEaswaran Raman   // If the -inline-threshold is not specified, set the ColdThreshold from the
27271c57cc2bSEaswaran Raman   // -inlinecold-threshold even if it is not explicitly passed. If
27281c57cc2bSEaswaran Raman   // -inline-threshold is specified, then -inlinecold-threshold needs to be
27291c57cc2bSEaswaran Raman   // explicitly specified to set the ColdThreshold knob
27301c57cc2bSEaswaran Raman   if (InlineThreshold.getNumOccurrences() == 0) {
27311c57cc2bSEaswaran Raman     Params.OptMinSizeThreshold = InlineConstants::OptMinSizeThreshold;
27321c57cc2bSEaswaran Raman     Params.OptSizeThreshold = InlineConstants::OptSizeThreshold;
27331c57cc2bSEaswaran Raman     Params.ColdThreshold = ColdThreshold;
27341c57cc2bSEaswaran Raman   } else if (ColdThreshold.getNumOccurrences() > 0) {
27351c57cc2bSEaswaran Raman     Params.ColdThreshold = ColdThreshold;
27361c57cc2bSEaswaran Raman   }
27371c57cc2bSEaswaran Raman   return Params;
27381c57cc2bSEaswaran Raman }
27391c57cc2bSEaswaran Raman 
27401c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams() {
27417f37a802STeresa Johnson   return getInlineParams(DefaultThreshold);
27421c57cc2bSEaswaran Raman }
27431c57cc2bSEaswaran Raman 
27441c57cc2bSEaswaran Raman // Compute the default threshold for inlining based on the opt level and the
27451c57cc2bSEaswaran Raman // size opt level.
27461c57cc2bSEaswaran Raman static int computeThresholdFromOptLevels(unsigned OptLevel,
27471c57cc2bSEaswaran Raman                                          unsigned SizeOptLevel) {
27481c57cc2bSEaswaran Raman   if (OptLevel > 2)
27491c57cc2bSEaswaran Raman     return InlineConstants::OptAggressiveThreshold;
27501c57cc2bSEaswaran Raman   if (SizeOptLevel == 1) // -Os
27511c57cc2bSEaswaran Raman     return InlineConstants::OptSizeThreshold;
27521c57cc2bSEaswaran Raman   if (SizeOptLevel == 2) // -Oz
27531c57cc2bSEaswaran Raman     return InlineConstants::OptMinSizeThreshold;
27547f37a802STeresa Johnson   return DefaultThreshold;
27551c57cc2bSEaswaran Raman }
27561c57cc2bSEaswaran Raman 
27571c57cc2bSEaswaran Raman InlineParams llvm::getInlineParams(unsigned OptLevel, unsigned SizeOptLevel) {
2758974d4eeaSEaswaran Raman   auto Params =
2759974d4eeaSEaswaran Raman       getInlineParams(computeThresholdFromOptLevels(OptLevel, SizeOptLevel));
2760974d4eeaSEaswaran Raman   // At O3, use the value of -locally-hot-callsite-threshold option to populate
2761974d4eeaSEaswaran Raman   // Params.LocallyHotCallSiteThreshold. Below O3, this flag has effect only
2762974d4eeaSEaswaran Raman   // when it is specified explicitly.
2763974d4eeaSEaswaran Raman   if (OptLevel > 2)
2764974d4eeaSEaswaran Raman     Params.LocallyHotCallSiteThreshold = LocallyHotCallSiteThreshold;
2765974d4eeaSEaswaran Raman   return Params;
27661c57cc2bSEaswaran Raman }
27676a5d7d49SKirill Naumov 
27686a5d7d49SKirill Naumov PreservedAnalyses
27696a5d7d49SKirill Naumov InlineCostAnnotationPrinterPass::run(Function &F,
27706a5d7d49SKirill Naumov                                      FunctionAnalysisManager &FAM) {
27716a5d7d49SKirill Naumov   PrintInstructionComments = true;
27726a5d7d49SKirill Naumov   std::function<AssumptionCache &(Function &)> GetAssumptionCache = [&](
27736a5d7d49SKirill Naumov       Function &F) -> AssumptionCache & {
27746a5d7d49SKirill Naumov     return FAM.getResult<AssumptionAnalysis>(F);
27756a5d7d49SKirill Naumov   };
27766a5d7d49SKirill Naumov   Module *M = F.getParent();
27776a5d7d49SKirill Naumov   ProfileSummaryInfo PSI(*M);
27786a5d7d49SKirill Naumov   DataLayout DL(M);
27796a5d7d49SKirill Naumov   TargetTransformInfo TTI(DL);
27806a5d7d49SKirill Naumov   // FIXME: Redesign the usage of InlineParams to expand the scope of this pass.
27816a5d7d49SKirill Naumov   // In the current implementation, the type of InlineParams doesn't matter as
27826a5d7d49SKirill Naumov   // the pass serves only for verification of inliner's decisions.
27836a5d7d49SKirill Naumov   // We can add a flag which determines InlineParams for this run. Right now,
27846a5d7d49SKirill Naumov   // the default InlineParams are used.
27856a5d7d49SKirill Naumov   const InlineParams Params = llvm::getInlineParams();
27866a5d7d49SKirill Naumov   for (BasicBlock &BB : F) {
27876a5d7d49SKirill Naumov     for (Instruction &I : BB) {
27886a5d7d49SKirill Naumov       if (CallInst *CI = dyn_cast<CallInst>(&I)) {
27896a5d7d49SKirill Naumov         Function *CalledFunction = CI->getCalledFunction();
27906a5d7d49SKirill Naumov         if (!CalledFunction || CalledFunction->isDeclaration())
27916a5d7d49SKirill Naumov           continue;
27926a5d7d49SKirill Naumov         OptimizationRemarkEmitter ORE(CalledFunction);
27936a5d7d49SKirill Naumov         InlineCostCallAnalyzer ICCA(*CalledFunction, *CI, Params, TTI,
27946a5d7d49SKirill Naumov                                     GetAssumptionCache, nullptr, &PSI, &ORE);
27956a5d7d49SKirill Naumov         ICCA.analyze();
27966a5d7d49SKirill Naumov         OS << "      Analyzing call of " << CalledFunction->getName()
27976a5d7d49SKirill Naumov            << "... (caller:" << CI->getCaller()->getName() << ")\n";
27986a5d7d49SKirill Naumov         ICCA.print();
27996a5d7d49SKirill Naumov       }
28006a5d7d49SKirill Naumov     }
28016a5d7d49SKirill Naumov   }
28026a5d7d49SKirill Naumov   return PreservedAnalyses::all();
28036a5d7d49SKirill Naumov }
2804