1 //===- InlineCost.cpp - Cost analysis for inliner -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements inline cost analysis.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Analysis/InlineCost.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/AssumptionCache.h"
21 #include "llvm/Analysis/CodeMetrics.h"
22 #include "llvm/Analysis/ConstantFolding.h"
23 #include "llvm/Analysis/InstructionSimplify.h"
24 #include "llvm/Analysis/TargetTransformInfo.h"
25 #include "llvm/IR/CallSite.h"
26 #include "llvm/IR/CallingConv.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/GetElementPtrTypeIterator.h"
29 #include "llvm/IR/GlobalAlias.h"
30 #include "llvm/IR/InstVisitor.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/IR/Operator.h"
33 #include "llvm/ProfileData/ProfileCommon.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/raw_ostream.h"
36 
37 using namespace llvm;
38 
39 #define DEBUG_TYPE "inline-cost"
40 
41 STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed");
42 
43 // Threshold to use when optsize is specified (and there is no
44 // -inline-threshold).
45 const int OptSizeThreshold = 75;
46 
47 // Threshold to use when -Oz is specified (and there is no -inline-threshold).
48 const int OptMinSizeThreshold = 25;
49 
50 // Threshold to use when -O[34] is specified (and there is no
51 // -inline-threshold).
52 const int OptAggressiveThreshold = 275;
53 
54 static cl::opt<int> DefaultInlineThreshold(
55     "inline-threshold", cl::Hidden, cl::init(225), cl::ZeroOrMore,
56     cl::desc("Control the amount of inlining to perform (default = 225)"));
57 
58 static cl::opt<int> HintThreshold(
59     "inlinehint-threshold", cl::Hidden, cl::init(325),
60     cl::desc("Threshold for inlining functions with inline hint"));
61 
62 // We introduce this threshold to help performance of instrumentation based
63 // PGO before we actually hook up inliner with analysis passes such as BPI and
64 // BFI.
65 static cl::opt<int> ColdThreshold(
66     "inlinecold-threshold", cl::Hidden, cl::init(225),
67     cl::desc("Threshold for inlining functions with cold attribute"));
68 
69 namespace {
70 
71 class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> {
72   typedef InstVisitor<CallAnalyzer, bool> Base;
73   friend class InstVisitor<CallAnalyzer, bool>;
74 
75   /// The TargetTransformInfo available for this compilation.
76   const TargetTransformInfo &TTI;
77 
78   /// The cache of @llvm.assume intrinsics.
79   AssumptionCacheTracker *ACT;
80 
81   // The called function.
82   Function &F;
83 
84   // The candidate callsite being analyzed. Please do not use this to do
85   // analysis in the caller function; we want the inline cost query to be
86   // easily cacheable. Instead, use the cover function paramHasAttr.
87   CallSite CandidateCS;
88 
89   int Threshold;
90   int Cost;
91 
92   bool IsCallerRecursive;
93   bool IsRecursiveCall;
94   bool ExposesReturnsTwice;
95   bool HasDynamicAlloca;
96   bool ContainsNoDuplicateCall;
97   bool HasReturn;
98   bool HasIndirectBr;
99   bool HasFrameEscape;
100 
101   /// Number of bytes allocated statically by the callee.
102   uint64_t AllocatedSize;
103   unsigned NumInstructions, NumVectorInstructions;
104   int FiftyPercentVectorBonus, TenPercentVectorBonus;
105   int VectorBonus;
106 
107   // While we walk the potentially-inlined instructions, we build up and
108   // maintain a mapping of simplified values specific to this callsite. The
109   // idea is to propagate any special information we have about arguments to
110   // this call through the inlinable section of the function, and account for
111   // likely simplifications post-inlining. The most important aspect we track
112   // is CFG altering simplifications -- when we prove a basic block dead, that
113   // can cause dramatic shifts in the cost of inlining a function.
114   DenseMap<Value *, Constant *> SimplifiedValues;
115 
116   // Keep track of the values which map back (through function arguments) to
117   // allocas on the caller stack which could be simplified through SROA.
118   DenseMap<Value *, Value *> SROAArgValues;
119 
120   // The mapping of caller Alloca values to their accumulated cost savings. If
121   // we have to disable SROA for one of the allocas, this tells us how much
122   // cost must be added.
123   DenseMap<Value *, int> SROAArgCosts;
124 
125   // Keep track of values which map to a pointer base and constant offset.
126   DenseMap<Value *, std::pair<Value *, APInt> > ConstantOffsetPtrs;
127 
128   // Custom simplification helper routines.
129   bool isAllocaDerivedArg(Value *V);
130   bool lookupSROAArgAndCost(Value *V, Value *&Arg,
131                             DenseMap<Value *, int>::iterator &CostIt);
132   void disableSROA(DenseMap<Value *, int>::iterator CostIt);
133   void disableSROA(Value *V);
134   void accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
135                           int InstructionCost);
136   bool isGEPOffsetConstant(GetElementPtrInst &GEP);
137   bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
138   bool simplifyCallSite(Function *F, CallSite CS);
139   ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
140 
141   /// Return true if the given argument to the function being considered for
142   /// inlining has the given attribute set either at the call site or the
143   /// function declaration.  Primarily used to inspect call site specific
144   /// attributes since these can be more precise than the ones on the callee
145   /// itself.
146   bool paramHasAttr(Argument *A, Attribute::AttrKind Attr);
147 
148   /// Return true if the given value is known non null within the callee if
149   /// inlined through this particular callsite.
150   bool isKnownNonNullInCallee(Value *V);
151 
152   /// Update Threshold based on callsite properties such as callee
153   /// attributes and callee hotness for PGO builds. The Callee is explicitly
154   /// passed to support analyzing indirect calls whose target is inferred by
155   /// analysis.
156   void updateThreshold(CallSite CS, Function &Callee);
157 
158   /// Return true if size growth is allowed when inlining the callee at CS.
159   bool allowSizeGrowth(CallSite CS);
160 
161   // Custom analysis routines.
162   bool analyzeBlock(BasicBlock *BB, SmallPtrSetImpl<const Value *> &EphValues);
163 
164   // Disable several entry points to the visitor so we don't accidentally use
165   // them by declaring but not defining them here.
166   void visit(Module *);     void visit(Module &);
167   void visit(Function *);   void visit(Function &);
168   void visit(BasicBlock *); void visit(BasicBlock &);
169 
170   // Provide base case for our instruction visit.
171   bool visitInstruction(Instruction &I);
172 
173   // Our visit overrides.
174   bool visitAlloca(AllocaInst &I);
175   bool visitPHI(PHINode &I);
176   bool visitGetElementPtr(GetElementPtrInst &I);
177   bool visitBitCast(BitCastInst &I);
178   bool visitPtrToInt(PtrToIntInst &I);
179   bool visitIntToPtr(IntToPtrInst &I);
180   bool visitCastInst(CastInst &I);
181   bool visitUnaryInstruction(UnaryInstruction &I);
182   bool visitCmpInst(CmpInst &I);
183   bool visitSub(BinaryOperator &I);
184   bool visitBinaryOperator(BinaryOperator &I);
185   bool visitLoad(LoadInst &I);
186   bool visitStore(StoreInst &I);
187   bool visitExtractValue(ExtractValueInst &I);
188   bool visitInsertValue(InsertValueInst &I);
189   bool visitCallSite(CallSite CS);
190   bool visitReturnInst(ReturnInst &RI);
191   bool visitBranchInst(BranchInst &BI);
192   bool visitSwitchInst(SwitchInst &SI);
193   bool visitIndirectBrInst(IndirectBrInst &IBI);
194   bool visitResumeInst(ResumeInst &RI);
195   bool visitCleanupReturnInst(CleanupReturnInst &RI);
196   bool visitCatchReturnInst(CatchReturnInst &RI);
197   bool visitUnreachableInst(UnreachableInst &I);
198 
199 public:
200   CallAnalyzer(const TargetTransformInfo &TTI, AssumptionCacheTracker *ACT,
201                Function &Callee, int Threshold, CallSite CSArg)
202     : TTI(TTI), ACT(ACT), F(Callee), CandidateCS(CSArg), Threshold(Threshold),
203         Cost(0), IsCallerRecursive(false), IsRecursiveCall(false),
204         ExposesReturnsTwice(false), HasDynamicAlloca(false),
205         ContainsNoDuplicateCall(false), HasReturn(false), HasIndirectBr(false),
206         HasFrameEscape(false), AllocatedSize(0), NumInstructions(0),
207         NumVectorInstructions(0), FiftyPercentVectorBonus(0),
208         TenPercentVectorBonus(0), VectorBonus(0), NumConstantArgs(0),
209         NumConstantOffsetPtrArgs(0), NumAllocaArgs(0), NumConstantPtrCmps(0),
210         NumConstantPtrDiffs(0), NumInstructionsSimplified(0),
211         SROACostSavings(0), SROACostSavingsLost(0) {}
212 
213   bool analyzeCall(CallSite CS);
214 
215   int getThreshold() { return Threshold; }
216   int getCost() { return Cost; }
217 
218   // Keep a bunch of stats about the cost savings found so we can print them
219   // out when debugging.
220   unsigned NumConstantArgs;
221   unsigned NumConstantOffsetPtrArgs;
222   unsigned NumAllocaArgs;
223   unsigned NumConstantPtrCmps;
224   unsigned NumConstantPtrDiffs;
225   unsigned NumInstructionsSimplified;
226   unsigned SROACostSavings;
227   unsigned SROACostSavingsLost;
228 
229   void dump();
230 };
231 
232 } // namespace
233 
234 /// \brief Test whether the given value is an Alloca-derived function argument.
235 bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
236   return SROAArgValues.count(V);
237 }
238 
239 /// \brief Lookup the SROA-candidate argument and cost iterator which V maps to.
240 /// Returns false if V does not map to a SROA-candidate.
241 bool CallAnalyzer::lookupSROAArgAndCost(
242     Value *V, Value *&Arg, DenseMap<Value *, int>::iterator &CostIt) {
243   if (SROAArgValues.empty() || SROAArgCosts.empty())
244     return false;
245 
246   DenseMap<Value *, Value *>::iterator ArgIt = SROAArgValues.find(V);
247   if (ArgIt == SROAArgValues.end())
248     return false;
249 
250   Arg = ArgIt->second;
251   CostIt = SROAArgCosts.find(Arg);
252   return CostIt != SROAArgCosts.end();
253 }
254 
255 /// \brief Disable SROA for the candidate marked by this cost iterator.
256 ///
257 /// This marks the candidate as no longer viable for SROA, and adds the cost
258 /// savings associated with it back into the inline cost measurement.
259 void CallAnalyzer::disableSROA(DenseMap<Value *, int>::iterator CostIt) {
260   // If we're no longer able to perform SROA we need to undo its cost savings
261   // and prevent subsequent analysis.
262   Cost += CostIt->second;
263   SROACostSavings -= CostIt->second;
264   SROACostSavingsLost += CostIt->second;
265   SROAArgCosts.erase(CostIt);
266 }
267 
268 /// \brief If 'V' maps to a SROA candidate, disable SROA for it.
269 void CallAnalyzer::disableSROA(Value *V) {
270   Value *SROAArg;
271   DenseMap<Value *, int>::iterator CostIt;
272   if (lookupSROAArgAndCost(V, SROAArg, CostIt))
273     disableSROA(CostIt);
274 }
275 
276 /// \brief Accumulate the given cost for a particular SROA candidate.
277 void CallAnalyzer::accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
278                                       int InstructionCost) {
279   CostIt->second += InstructionCost;
280   SROACostSavings += InstructionCost;
281 }
282 
283 /// \brief Check whether a GEP's indices are all constant.
284 ///
285 /// Respects any simplified values known during the analysis of this callsite.
286 bool CallAnalyzer::isGEPOffsetConstant(GetElementPtrInst &GEP) {
287   for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I)
288     if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I))
289       return false;
290 
291   return true;
292 }
293 
294 /// \brief Accumulate a constant GEP offset into an APInt if possible.
295 ///
296 /// Returns false if unable to compute the offset for any reason. Respects any
297 /// simplified values known during the analysis of this callsite.
298 bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
299   const DataLayout &DL = F.getParent()->getDataLayout();
300   unsigned IntPtrWidth = DL.getPointerSizeInBits();
301   assert(IntPtrWidth == Offset.getBitWidth());
302 
303   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
304        GTI != GTE; ++GTI) {
305     ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
306     if (!OpC)
307       if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
308         OpC = dyn_cast<ConstantInt>(SimpleOp);
309     if (!OpC)
310       return false;
311     if (OpC->isZero()) continue;
312 
313     // Handle a struct index, which adds its field offset to the pointer.
314     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
315       unsigned ElementIdx = OpC->getZExtValue();
316       const StructLayout *SL = DL.getStructLayout(STy);
317       Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
318       continue;
319     }
320 
321     APInt TypeSize(IntPtrWidth, DL.getTypeAllocSize(GTI.getIndexedType()));
322     Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
323   }
324   return true;
325 }
326 
327 bool CallAnalyzer::visitAlloca(AllocaInst &I) {
328   // Check whether inlining will turn a dynamic alloca into a static
329   // alloca, and handle that case.
330   if (I.isArrayAllocation()) {
331     if (Constant *Size = SimplifiedValues.lookup(I.getArraySize())) {
332       ConstantInt *AllocSize = dyn_cast<ConstantInt>(Size);
333       assert(AllocSize && "Allocation size not a constant int?");
334       Type *Ty = I.getAllocatedType();
335       AllocatedSize += Ty->getPrimitiveSizeInBits() * AllocSize->getZExtValue();
336       return Base::visitAlloca(I);
337     }
338   }
339 
340   // Accumulate the allocated size.
341   if (I.isStaticAlloca()) {
342     const DataLayout &DL = F.getParent()->getDataLayout();
343     Type *Ty = I.getAllocatedType();
344     AllocatedSize += DL.getTypeAllocSize(Ty);
345   }
346 
347   // We will happily inline static alloca instructions.
348   if (I.isStaticAlloca())
349     return Base::visitAlloca(I);
350 
351   // FIXME: This is overly conservative. Dynamic allocas are inefficient for
352   // a variety of reasons, and so we would like to not inline them into
353   // functions which don't currently have a dynamic alloca. This simply
354   // disables inlining altogether in the presence of a dynamic alloca.
355   HasDynamicAlloca = true;
356   return false;
357 }
358 
359 bool CallAnalyzer::visitPHI(PHINode &I) {
360   // FIXME: We should potentially be tracking values through phi nodes,
361   // especially when they collapse to a single value due to deleted CFG edges
362   // during inlining.
363 
364   // FIXME: We need to propagate SROA *disabling* through phi nodes, even
365   // though we don't want to propagate it's bonuses. The idea is to disable
366   // SROA if it *might* be used in an inappropriate manner.
367 
368   // Phi nodes are always zero-cost.
369   return true;
370 }
371 
372 bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
373   Value *SROAArg;
374   DenseMap<Value *, int>::iterator CostIt;
375   bool SROACandidate = lookupSROAArgAndCost(I.getPointerOperand(),
376                                             SROAArg, CostIt);
377 
378   // Try to fold GEPs of constant-offset call site argument pointers. This
379   // requires target data and inbounds GEPs.
380   if (I.isInBounds()) {
381     // Check if we have a base + offset for the pointer.
382     Value *Ptr = I.getPointerOperand();
383     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Ptr);
384     if (BaseAndOffset.first) {
385       // Check if the offset of this GEP is constant, and if so accumulate it
386       // into Offset.
387       if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)) {
388         // Non-constant GEPs aren't folded, and disable SROA.
389         if (SROACandidate)
390           disableSROA(CostIt);
391         return false;
392       }
393 
394       // Add the result as a new mapping to Base + Offset.
395       ConstantOffsetPtrs[&I] = BaseAndOffset;
396 
397       // Also handle SROA candidates here, we already know that the GEP is
398       // all-constant indexed.
399       if (SROACandidate)
400         SROAArgValues[&I] = SROAArg;
401 
402       return true;
403     }
404   }
405 
406   if (isGEPOffsetConstant(I)) {
407     if (SROACandidate)
408       SROAArgValues[&I] = SROAArg;
409 
410     // Constant GEPs are modeled as free.
411     return true;
412   }
413 
414   // Variable GEPs will require math and will disable SROA.
415   if (SROACandidate)
416     disableSROA(CostIt);
417   return false;
418 }
419 
420 bool CallAnalyzer::visitBitCast(BitCastInst &I) {
421   // Propagate constants through bitcasts.
422   Constant *COp = dyn_cast<Constant>(I.getOperand(0));
423   if (!COp)
424     COp = SimplifiedValues.lookup(I.getOperand(0));
425   if (COp)
426     if (Constant *C = ConstantExpr::getBitCast(COp, I.getType())) {
427       SimplifiedValues[&I] = C;
428       return true;
429     }
430 
431   // Track base/offsets through casts
432   std::pair<Value *, APInt> BaseAndOffset
433     = ConstantOffsetPtrs.lookup(I.getOperand(0));
434   // Casts don't change the offset, just wrap it up.
435   if (BaseAndOffset.first)
436     ConstantOffsetPtrs[&I] = BaseAndOffset;
437 
438   // Also look for SROA candidates here.
439   Value *SROAArg;
440   DenseMap<Value *, int>::iterator CostIt;
441   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
442     SROAArgValues[&I] = SROAArg;
443 
444   // Bitcasts are always zero cost.
445   return true;
446 }
447 
448 bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
449   // Propagate constants through ptrtoint.
450   Constant *COp = dyn_cast<Constant>(I.getOperand(0));
451   if (!COp)
452     COp = SimplifiedValues.lookup(I.getOperand(0));
453   if (COp)
454     if (Constant *C = ConstantExpr::getPtrToInt(COp, I.getType())) {
455       SimplifiedValues[&I] = C;
456       return true;
457     }
458 
459   // Track base/offset pairs when converted to a plain integer provided the
460   // integer is large enough to represent the pointer.
461   unsigned IntegerSize = I.getType()->getScalarSizeInBits();
462   const DataLayout &DL = F.getParent()->getDataLayout();
463   if (IntegerSize >= DL.getPointerSizeInBits()) {
464     std::pair<Value *, APInt> BaseAndOffset
465       = ConstantOffsetPtrs.lookup(I.getOperand(0));
466     if (BaseAndOffset.first)
467       ConstantOffsetPtrs[&I] = BaseAndOffset;
468   }
469 
470   // This is really weird. Technically, ptrtoint will disable SROA. However,
471   // unless that ptrtoint is *used* somewhere in the live basic blocks after
472   // inlining, it will be nuked, and SROA should proceed. All of the uses which
473   // would block SROA would also block SROA if applied directly to a pointer,
474   // and so we can just add the integer in here. The only places where SROA is
475   // preserved either cannot fire on an integer, or won't in-and-of themselves
476   // disable SROA (ext) w/o some later use that we would see and disable.
477   Value *SROAArg;
478   DenseMap<Value *, int>::iterator CostIt;
479   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
480     SROAArgValues[&I] = SROAArg;
481 
482   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
483 }
484 
485 bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
486   // Propagate constants through ptrtoint.
487   Constant *COp = dyn_cast<Constant>(I.getOperand(0));
488   if (!COp)
489     COp = SimplifiedValues.lookup(I.getOperand(0));
490   if (COp)
491     if (Constant *C = ConstantExpr::getIntToPtr(COp, I.getType())) {
492       SimplifiedValues[&I] = C;
493       return true;
494     }
495 
496   // Track base/offset pairs when round-tripped through a pointer without
497   // modifications provided the integer is not too large.
498   Value *Op = I.getOperand(0);
499   unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
500   const DataLayout &DL = F.getParent()->getDataLayout();
501   if (IntegerSize <= DL.getPointerSizeInBits()) {
502     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
503     if (BaseAndOffset.first)
504       ConstantOffsetPtrs[&I] = BaseAndOffset;
505   }
506 
507   // "Propagate" SROA here in the same manner as we do for ptrtoint above.
508   Value *SROAArg;
509   DenseMap<Value *, int>::iterator CostIt;
510   if (lookupSROAArgAndCost(Op, SROAArg, CostIt))
511     SROAArgValues[&I] = SROAArg;
512 
513   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
514 }
515 
516 bool CallAnalyzer::visitCastInst(CastInst &I) {
517   // Propagate constants through ptrtoint.
518   Constant *COp = dyn_cast<Constant>(I.getOperand(0));
519   if (!COp)
520     COp = SimplifiedValues.lookup(I.getOperand(0));
521   if (COp)
522     if (Constant *C = ConstantExpr::getCast(I.getOpcode(), COp, I.getType())) {
523       SimplifiedValues[&I] = C;
524       return true;
525     }
526 
527   // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere.
528   disableSROA(I.getOperand(0));
529 
530   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
531 }
532 
533 bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) {
534   Value *Operand = I.getOperand(0);
535   Constant *COp = dyn_cast<Constant>(Operand);
536   if (!COp)
537     COp = SimplifiedValues.lookup(Operand);
538   if (COp) {
539     const DataLayout &DL = F.getParent()->getDataLayout();
540     if (Constant *C = ConstantFoldInstOperands(&I, COp, DL)) {
541       SimplifiedValues[&I] = C;
542       return true;
543     }
544   }
545 
546   // Disable any SROA on the argument to arbitrary unary operators.
547   disableSROA(Operand);
548 
549   return false;
550 }
551 
552 bool CallAnalyzer::paramHasAttr(Argument *A, Attribute::AttrKind Attr) {
553   unsigned ArgNo = A->getArgNo();
554   return CandidateCS.paramHasAttr(ArgNo+1, Attr);
555 }
556 
557 bool CallAnalyzer::isKnownNonNullInCallee(Value *V) {
558   // Does the *call site* have the NonNull attribute set on an argument?  We
559   // use the attribute on the call site to memoize any analysis done in the
560   // caller. This will also trip if the callee function has a non-null
561   // parameter attribute, but that's a less interesting case because hopefully
562   // the callee would already have been simplified based on that.
563   if (Argument *A = dyn_cast<Argument>(V))
564     if (paramHasAttr(A, Attribute::NonNull))
565       return true;
566 
567   // Is this an alloca in the caller?  This is distinct from the attribute case
568   // above because attributes aren't updated within the inliner itself and we
569   // always want to catch the alloca derived case.
570   if (isAllocaDerivedArg(V))
571     // We can actually predict the result of comparisons between an
572     // alloca-derived value and null. Note that this fires regardless of
573     // SROA firing.
574     return true;
575 
576   return false;
577 }
578 
579 bool CallAnalyzer::allowSizeGrowth(CallSite CS) {
580   // If the normal destination of the invoke or the parent block of the call
581   // site is unreachable-terminated, there is little point in inlining this
582   // unless there is literally zero cost.
583   // FIXME: Note that it is possible that an unreachable-terminated block has a
584   // hot entry. For example, in below scenario inlining hot_call_X() may be
585   // beneficial :
586   // main() {
587   //   hot_call_1();
588   //   ...
589   //   hot_call_N()
590   //   exit(0);
591   // }
592   // For now, we are not handling this corner case here as it is rare in real
593   // code. In future, we should elaborate this based on BPI and BFI in more
594   // general threshold adjusting heuristics in updateThreshold().
595   Instruction *Instr = CS.getInstruction();
596   if (InvokeInst *II = dyn_cast<InvokeInst>(Instr)) {
597     if (isa<UnreachableInst>(II->getNormalDest()->getTerminator()))
598       return false;
599   } else if (isa<UnreachableInst>(Instr->getParent()->getTerminator()))
600     return false;
601 
602   return true;
603 }
604 
605 void CallAnalyzer::updateThreshold(CallSite CS, Function &Callee) {
606   // If no size growth is allowed for this inlining, set Threshold to 0.
607   if (!allowSizeGrowth(CS)) {
608     Threshold = 0;
609     return;
610   }
611 
612   // If -inline-threshold is not given, listen to the optsize and minsize
613   // attributes when they would decrease the threshold.
614   Function *Caller = CS.getCaller();
615 
616   if (!(DefaultInlineThreshold.getNumOccurrences() > 0)) {
617     if (Caller->optForMinSize() && OptMinSizeThreshold < Threshold)
618       Threshold = OptMinSizeThreshold;
619     else if (Caller->optForSize() && OptSizeThreshold < Threshold)
620       Threshold = OptSizeThreshold;
621   }
622 
623   // If profile information is available, use that to adjust threshold of hot
624   // and cold functions.
625   // FIXME: The heuristic used below for determining hotness and coldness are
626   // based on preliminary SPEC tuning and may not be optimal. Replace this with
627   // a well-tuned heuristic based on *callsite* hotness and not callee hotness.
628   uint64_t FunctionCount = 0, MaxFunctionCount = 0;
629   bool HasPGOCounts = false;
630   ProfileSummary *PS = ProfileSummary::getProfileSummary(Callee.getParent());
631   if (Callee.getEntryCount() && PS) {
632     HasPGOCounts = true;
633     FunctionCount = Callee.getEntryCount().getValue();
634     MaxFunctionCount = PS->getMaxFunctionCount();
635   }
636 
637   // Listen to the inlinehint attribute or profile based hotness information
638   // when it would increase the threshold and the caller does not need to
639   // minimize its size.
640   bool InlineHint =
641       Callee.hasFnAttribute(Attribute::InlineHint) ||
642       (HasPGOCounts &&
643        FunctionCount >= (uint64_t)(0.3 * (double)MaxFunctionCount));
644   if (InlineHint && HintThreshold > Threshold && !Caller->optForMinSize())
645     Threshold = HintThreshold;
646 
647   // Listen to the cold attribute or profile based coldness information
648   // when it would decrease the threshold.
649   bool ColdCallee =
650       Callee.hasFnAttribute(Attribute::Cold) ||
651       (HasPGOCounts &&
652        FunctionCount <= (uint64_t)(0.01 * (double)MaxFunctionCount));
653   // Command line argument for DefaultInlineThreshold will override the default
654   // ColdThreshold. If we have -inline-threshold but no -inlinecold-threshold,
655   // do not use the default cold threshold even if it is smaller.
656   if ((DefaultInlineThreshold.getNumOccurrences() == 0 ||
657        ColdThreshold.getNumOccurrences() > 0) &&
658       ColdCallee && ColdThreshold < Threshold)
659     Threshold = ColdThreshold;
660 
661   // Finally, take the target-specific inlining threshold multiplier into
662   // account.
663   Threshold *= TTI.getInliningThresholdMultiplier();
664 }
665 
666 bool CallAnalyzer::visitCmpInst(CmpInst &I) {
667   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
668   // First try to handle simplified comparisons.
669   if (!isa<Constant>(LHS))
670     if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
671       LHS = SimpleLHS;
672   if (!isa<Constant>(RHS))
673     if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
674       RHS = SimpleRHS;
675   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
676     if (Constant *CRHS = dyn_cast<Constant>(RHS))
677       if (Constant *C = ConstantExpr::getCompare(I.getPredicate(), CLHS, CRHS)) {
678         SimplifiedValues[&I] = C;
679         return true;
680       }
681   }
682 
683   if (I.getOpcode() == Instruction::FCmp)
684     return false;
685 
686   // Otherwise look for a comparison between constant offset pointers with
687   // a common base.
688   Value *LHSBase, *RHSBase;
689   APInt LHSOffset, RHSOffset;
690   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
691   if (LHSBase) {
692     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
693     if (RHSBase && LHSBase == RHSBase) {
694       // We have common bases, fold the icmp to a constant based on the
695       // offsets.
696       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
697       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
698       if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
699         SimplifiedValues[&I] = C;
700         ++NumConstantPtrCmps;
701         return true;
702       }
703     }
704   }
705 
706   // If the comparison is an equality comparison with null, we can simplify it
707   // if we know the value (argument) can't be null
708   if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)) &&
709       isKnownNonNullInCallee(I.getOperand(0))) {
710     bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
711     SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
712                                       : ConstantInt::getFalse(I.getType());
713     return true;
714   }
715   // Finally check for SROA candidates in comparisons.
716   Value *SROAArg;
717   DenseMap<Value *, int>::iterator CostIt;
718   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
719     if (isa<ConstantPointerNull>(I.getOperand(1))) {
720       accumulateSROACost(CostIt, InlineConstants::InstrCost);
721       return true;
722     }
723 
724     disableSROA(CostIt);
725   }
726 
727   return false;
728 }
729 
730 bool CallAnalyzer::visitSub(BinaryOperator &I) {
731   // Try to handle a special case: we can fold computing the difference of two
732   // constant-related pointers.
733   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
734   Value *LHSBase, *RHSBase;
735   APInt LHSOffset, RHSOffset;
736   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
737   if (LHSBase) {
738     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
739     if (RHSBase && LHSBase == RHSBase) {
740       // We have common bases, fold the subtract to a constant based on the
741       // offsets.
742       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
743       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
744       if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
745         SimplifiedValues[&I] = C;
746         ++NumConstantPtrDiffs;
747         return true;
748       }
749     }
750   }
751 
752   // Otherwise, fall back to the generic logic for simplifying and handling
753   // instructions.
754   return Base::visitSub(I);
755 }
756 
757 bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
758   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
759   const DataLayout &DL = F.getParent()->getDataLayout();
760   if (!isa<Constant>(LHS))
761     if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
762       LHS = SimpleLHS;
763   if (!isa<Constant>(RHS))
764     if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
765       RHS = SimpleRHS;
766   Value *SimpleV = nullptr;
767   if (auto FI = dyn_cast<FPMathOperator>(&I))
768     SimpleV =
769         SimplifyFPBinOp(I.getOpcode(), LHS, RHS, FI->getFastMathFlags(), DL);
770   else
771     SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, DL);
772 
773   if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) {
774     SimplifiedValues[&I] = C;
775     return true;
776   }
777 
778   // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
779   disableSROA(LHS);
780   disableSROA(RHS);
781 
782   return false;
783 }
784 
785 bool CallAnalyzer::visitLoad(LoadInst &I) {
786   Value *SROAArg;
787   DenseMap<Value *, int>::iterator CostIt;
788   if (lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt)) {
789     if (I.isSimple()) {
790       accumulateSROACost(CostIt, InlineConstants::InstrCost);
791       return true;
792     }
793 
794     disableSROA(CostIt);
795   }
796 
797   return false;
798 }
799 
800 bool CallAnalyzer::visitStore(StoreInst &I) {
801   Value *SROAArg;
802   DenseMap<Value *, int>::iterator CostIt;
803   if (lookupSROAArgAndCost(I.getPointerOperand(), SROAArg, CostIt)) {
804     if (I.isSimple()) {
805       accumulateSROACost(CostIt, InlineConstants::InstrCost);
806       return true;
807     }
808 
809     disableSROA(CostIt);
810   }
811 
812   return false;
813 }
814 
815 bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) {
816   // Constant folding for extract value is trivial.
817   Constant *C = dyn_cast<Constant>(I.getAggregateOperand());
818   if (!C)
819     C = SimplifiedValues.lookup(I.getAggregateOperand());
820   if (C) {
821     SimplifiedValues[&I] = ConstantExpr::getExtractValue(C, I.getIndices());
822     return true;
823   }
824 
825   // SROA can look through these but give them a cost.
826   return false;
827 }
828 
829 bool CallAnalyzer::visitInsertValue(InsertValueInst &I) {
830   // Constant folding for insert value is trivial.
831   Constant *AggC = dyn_cast<Constant>(I.getAggregateOperand());
832   if (!AggC)
833     AggC = SimplifiedValues.lookup(I.getAggregateOperand());
834   Constant *InsertedC = dyn_cast<Constant>(I.getInsertedValueOperand());
835   if (!InsertedC)
836     InsertedC = SimplifiedValues.lookup(I.getInsertedValueOperand());
837   if (AggC && InsertedC) {
838     SimplifiedValues[&I] = ConstantExpr::getInsertValue(AggC, InsertedC,
839                                                         I.getIndices());
840     return true;
841   }
842 
843   // SROA can look through these but give them a cost.
844   return false;
845 }
846 
847 /// \brief Try to simplify a call site.
848 ///
849 /// Takes a concrete function and callsite and tries to actually simplify it by
850 /// analyzing the arguments and call itself with instsimplify. Returns true if
851 /// it has simplified the callsite to some other entity (a constant), making it
852 /// free.
853 bool CallAnalyzer::simplifyCallSite(Function *F, CallSite CS) {
854   // FIXME: Using the instsimplify logic directly for this is inefficient
855   // because we have to continually rebuild the argument list even when no
856   // simplifications can be performed. Until that is fixed with remapping
857   // inside of instsimplify, directly constant fold calls here.
858   if (!canConstantFoldCallTo(F))
859     return false;
860 
861   // Try to re-map the arguments to constants.
862   SmallVector<Constant *, 4> ConstantArgs;
863   ConstantArgs.reserve(CS.arg_size());
864   for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
865        I != E; ++I) {
866     Constant *C = dyn_cast<Constant>(*I);
867     if (!C)
868       C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(*I));
869     if (!C)
870       return false; // This argument doesn't map to a constant.
871 
872     ConstantArgs.push_back(C);
873   }
874   if (Constant *C = ConstantFoldCall(F, ConstantArgs)) {
875     SimplifiedValues[CS.getInstruction()] = C;
876     return true;
877   }
878 
879   return false;
880 }
881 
882 bool CallAnalyzer::visitCallSite(CallSite CS) {
883   if (CS.hasFnAttr(Attribute::ReturnsTwice) &&
884       !F.hasFnAttribute(Attribute::ReturnsTwice)) {
885     // This aborts the entire analysis.
886     ExposesReturnsTwice = true;
887     return false;
888   }
889   if (CS.isCall() &&
890       cast<CallInst>(CS.getInstruction())->cannotDuplicate())
891     ContainsNoDuplicateCall = true;
892 
893   if (Function *F = CS.getCalledFunction()) {
894     // When we have a concrete function, first try to simplify it directly.
895     if (simplifyCallSite(F, CS))
896       return true;
897 
898     // Next check if it is an intrinsic we know about.
899     // FIXME: Lift this into part of the InstVisitor.
900     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
901       switch (II->getIntrinsicID()) {
902       default:
903         return Base::visitCallSite(CS);
904 
905       case Intrinsic::memset:
906       case Intrinsic::memcpy:
907       case Intrinsic::memmove:
908         // SROA can usually chew through these intrinsics, but they aren't free.
909         return false;
910       case Intrinsic::localescape:
911         HasFrameEscape = true;
912         return false;
913       }
914     }
915 
916     if (F == CS.getInstruction()->getParent()->getParent()) {
917       // This flag will fully abort the analysis, so don't bother with anything
918       // else.
919       IsRecursiveCall = true;
920       return false;
921     }
922 
923     if (TTI.isLoweredToCall(F)) {
924       // We account for the average 1 instruction per call argument setup
925       // here.
926       Cost += CS.arg_size() * InlineConstants::InstrCost;
927 
928       // Everything other than inline ASM will also have a significant cost
929       // merely from making the call.
930       if (!isa<InlineAsm>(CS.getCalledValue()))
931         Cost += InlineConstants::CallPenalty;
932     }
933 
934     return Base::visitCallSite(CS);
935   }
936 
937   // Otherwise we're in a very special case -- an indirect function call. See
938   // if we can be particularly clever about this.
939   Value *Callee = CS.getCalledValue();
940 
941   // First, pay the price of the argument setup. We account for the average
942   // 1 instruction per call argument setup here.
943   Cost += CS.arg_size() * InlineConstants::InstrCost;
944 
945   // Next, check if this happens to be an indirect function call to a known
946   // function in this inline context. If not, we've done all we can.
947   Function *F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
948   if (!F)
949     return Base::visitCallSite(CS);
950 
951   // If we have a constant that we are calling as a function, we can peer
952   // through it and see the function target. This happens not infrequently
953   // during devirtualization and so we want to give it a hefty bonus for
954   // inlining, but cap that bonus in the event that inlining wouldn't pan
955   // out. Pretend to inline the function, with a custom threshold.
956   CallAnalyzer CA(TTI, ACT, *F, InlineConstants::IndirectCallThreshold, CS);
957   if (CA.analyzeCall(CS)) {
958     // We were able to inline the indirect call! Subtract the cost from the
959     // threshold to get the bonus we want to apply, but don't go below zero.
960     Cost -= std::max(0, CA.getThreshold() - CA.getCost());
961   }
962 
963   return Base::visitCallSite(CS);
964 }
965 
966 bool CallAnalyzer::visitReturnInst(ReturnInst &RI) {
967   // At least one return instruction will be free after inlining.
968   bool Free = !HasReturn;
969   HasReturn = true;
970   return Free;
971 }
972 
973 bool CallAnalyzer::visitBranchInst(BranchInst &BI) {
974   // We model unconditional branches as essentially free -- they really
975   // shouldn't exist at all, but handling them makes the behavior of the
976   // inliner more regular and predictable. Interestingly, conditional branches
977   // which will fold away are also free.
978   return BI.isUnconditional() || isa<ConstantInt>(BI.getCondition()) ||
979          dyn_cast_or_null<ConstantInt>(
980              SimplifiedValues.lookup(BI.getCondition()));
981 }
982 
983 bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) {
984   // We model unconditional switches as free, see the comments on handling
985   // branches.
986   if (isa<ConstantInt>(SI.getCondition()))
987     return true;
988   if (Value *V = SimplifiedValues.lookup(SI.getCondition()))
989     if (isa<ConstantInt>(V))
990       return true;
991 
992   // Otherwise, we need to accumulate a cost proportional to the number of
993   // distinct successor blocks. This fan-out in the CFG cannot be represented
994   // for free even if we can represent the core switch as a jumptable that
995   // takes a single instruction.
996   //
997   // NB: We convert large switches which are just used to initialize large phi
998   // nodes to lookup tables instead in simplify-cfg, so this shouldn't prevent
999   // inlining those. It will prevent inlining in cases where the optimization
1000   // does not (yet) fire.
1001   SmallPtrSet<BasicBlock *, 8> SuccessorBlocks;
1002   SuccessorBlocks.insert(SI.getDefaultDest());
1003   for (auto I = SI.case_begin(), E = SI.case_end(); I != E; ++I)
1004     SuccessorBlocks.insert(I.getCaseSuccessor());
1005   // Add cost corresponding to the number of distinct destinations. The first
1006   // we model as free because of fallthrough.
1007   Cost += (SuccessorBlocks.size() - 1) * InlineConstants::InstrCost;
1008   return false;
1009 }
1010 
1011 bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) {
1012   // We never want to inline functions that contain an indirectbr.  This is
1013   // incorrect because all the blockaddress's (in static global initializers
1014   // for example) would be referring to the original function, and this
1015   // indirect jump would jump from the inlined copy of the function into the
1016   // original function which is extremely undefined behavior.
1017   // FIXME: This logic isn't really right; we can safely inline functions with
1018   // indirectbr's as long as no other function or global references the
1019   // blockaddress of a block within the current function.
1020   HasIndirectBr = true;
1021   return false;
1022 }
1023 
1024 bool CallAnalyzer::visitResumeInst(ResumeInst &RI) {
1025   // FIXME: It's not clear that a single instruction is an accurate model for
1026   // the inline cost of a resume instruction.
1027   return false;
1028 }
1029 
1030 bool CallAnalyzer::visitCleanupReturnInst(CleanupReturnInst &CRI) {
1031   // FIXME: It's not clear that a single instruction is an accurate model for
1032   // the inline cost of a cleanupret instruction.
1033   return false;
1034 }
1035 
1036 bool CallAnalyzer::visitCatchReturnInst(CatchReturnInst &CRI) {
1037   // FIXME: It's not clear that a single instruction is an accurate model for
1038   // the inline cost of a catchret instruction.
1039   return false;
1040 }
1041 
1042 bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) {
1043   // FIXME: It might be reasonably to discount the cost of instructions leading
1044   // to unreachable as they have the lowest possible impact on both runtime and
1045   // code size.
1046   return true; // No actual code is needed for unreachable.
1047 }
1048 
1049 bool CallAnalyzer::visitInstruction(Instruction &I) {
1050   // Some instructions are free. All of the free intrinsics can also be
1051   // handled by SROA, etc.
1052   if (TargetTransformInfo::TCC_Free == TTI.getUserCost(&I))
1053     return true;
1054 
1055   // We found something we don't understand or can't handle. Mark any SROA-able
1056   // values in the operand list as no longer viable.
1057   for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI)
1058     disableSROA(*OI);
1059 
1060   return false;
1061 }
1062 
1063 
1064 /// \brief Analyze a basic block for its contribution to the inline cost.
1065 ///
1066 /// This method walks the analyzer over every instruction in the given basic
1067 /// block and accounts for their cost during inlining at this callsite. It
1068 /// aborts early if the threshold has been exceeded or an impossible to inline
1069 /// construct has been detected. It returns false if inlining is no longer
1070 /// viable, and true if inlining remains viable.
1071 bool CallAnalyzer::analyzeBlock(BasicBlock *BB,
1072                                 SmallPtrSetImpl<const Value *> &EphValues) {
1073   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1074     // FIXME: Currently, the number of instructions in a function regardless of
1075     // our ability to simplify them during inline to constants or dead code,
1076     // are actually used by the vector bonus heuristic. As long as that's true,
1077     // we have to special case debug intrinsics here to prevent differences in
1078     // inlining due to debug symbols. Eventually, the number of unsimplified
1079     // instructions shouldn't factor into the cost computation, but until then,
1080     // hack around it here.
1081     if (isa<DbgInfoIntrinsic>(I))
1082       continue;
1083 
1084     // Skip ephemeral values.
1085     if (EphValues.count(&*I))
1086       continue;
1087 
1088     ++NumInstructions;
1089     if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy())
1090       ++NumVectorInstructions;
1091 
1092     // If the instruction is floating point, and the target says this operation
1093     // is expensive or the function has the "use-soft-float" attribute, this may
1094     // eventually become a library call. Treat the cost as such.
1095     if (I->getType()->isFloatingPointTy()) {
1096       bool hasSoftFloatAttr = false;
1097 
1098       // If the function has the "use-soft-float" attribute, mark it as
1099       // expensive.
1100       if (F.hasFnAttribute("use-soft-float")) {
1101         Attribute Attr = F.getFnAttribute("use-soft-float");
1102         StringRef Val = Attr.getValueAsString();
1103         if (Val == "true")
1104           hasSoftFloatAttr = true;
1105       }
1106 
1107       if (TTI.getFPOpCost(I->getType()) == TargetTransformInfo::TCC_Expensive ||
1108           hasSoftFloatAttr)
1109         Cost += InlineConstants::CallPenalty;
1110     }
1111 
1112     // If the instruction simplified to a constant, there is no cost to this
1113     // instruction. Visit the instructions using our InstVisitor to account for
1114     // all of the per-instruction logic. The visit tree returns true if we
1115     // consumed the instruction in any way, and false if the instruction's base
1116     // cost should count against inlining.
1117     if (Base::visit(&*I))
1118       ++NumInstructionsSimplified;
1119     else
1120       Cost += InlineConstants::InstrCost;
1121 
1122     // If the visit this instruction detected an uninlinable pattern, abort.
1123     if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca ||
1124         HasIndirectBr || HasFrameEscape)
1125       return false;
1126 
1127     // If the caller is a recursive function then we don't want to inline
1128     // functions which allocate a lot of stack space because it would increase
1129     // the caller stack usage dramatically.
1130     if (IsCallerRecursive &&
1131         AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
1132       return false;
1133 
1134     // Check if we've past the maximum possible threshold so we don't spin in
1135     // huge basic blocks that will never inline.
1136     if (Cost > Threshold)
1137       return false;
1138   }
1139 
1140   return true;
1141 }
1142 
1143 /// \brief Compute the base pointer and cumulative constant offsets for V.
1144 ///
1145 /// This strips all constant offsets off of V, leaving it the base pointer, and
1146 /// accumulates the total constant offset applied in the returned constant. It
1147 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
1148 /// no constant offsets applied.
1149 ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
1150   if (!V->getType()->isPointerTy())
1151     return nullptr;
1152 
1153   const DataLayout &DL = F.getParent()->getDataLayout();
1154   unsigned IntPtrWidth = DL.getPointerSizeInBits();
1155   APInt Offset = APInt::getNullValue(IntPtrWidth);
1156 
1157   // Even though we don't look through PHI nodes, we could be called on an
1158   // instruction in an unreachable block, which may be on a cycle.
1159   SmallPtrSet<Value *, 4> Visited;
1160   Visited.insert(V);
1161   do {
1162     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
1163       if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
1164         return nullptr;
1165       V = GEP->getPointerOperand();
1166     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
1167       V = cast<Operator>(V)->getOperand(0);
1168     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
1169       if (GA->isInterposable())
1170         break;
1171       V = GA->getAliasee();
1172     } else {
1173       break;
1174     }
1175     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
1176   } while (Visited.insert(V).second);
1177 
1178   Type *IntPtrTy = DL.getIntPtrType(V->getContext());
1179   return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset));
1180 }
1181 
1182 /// \brief Analyze a call site for potential inlining.
1183 ///
1184 /// Returns true if inlining this call is viable, and false if it is not
1185 /// viable. It computes the cost and adjusts the threshold based on numerous
1186 /// factors and heuristics. If this method returns false but the computed cost
1187 /// is below the computed threshold, then inlining was forcibly disabled by
1188 /// some artifact of the routine.
1189 bool CallAnalyzer::analyzeCall(CallSite CS) {
1190   ++NumCallsAnalyzed;
1191 
1192   // Perform some tweaks to the cost and threshold based on the direct
1193   // callsite information.
1194 
1195   // We want to more aggressively inline vector-dense kernels, so up the
1196   // threshold, and we'll lower it if the % of vector instructions gets too
1197   // low. Note that these bonuses are some what arbitrary and evolved over time
1198   // by accident as much as because they are principled bonuses.
1199   //
1200   // FIXME: It would be nice to remove all such bonuses. At least it would be
1201   // nice to base the bonus values on something more scientific.
1202   assert(NumInstructions == 0);
1203   assert(NumVectorInstructions == 0);
1204 
1205   // Update the threshold based on callsite properties
1206   updateThreshold(CS, F);
1207 
1208   FiftyPercentVectorBonus = 3 * Threshold / 2;
1209   TenPercentVectorBonus = 3 * Threshold / 4;
1210   const DataLayout &DL = F.getParent()->getDataLayout();
1211 
1212   // Track whether the post-inlining function would have more than one basic
1213   // block. A single basic block is often intended for inlining. Balloon the
1214   // threshold by 50% until we pass the single-BB phase.
1215   bool SingleBB = true;
1216   int SingleBBBonus = Threshold / 2;
1217 
1218   // Speculatively apply all possible bonuses to Threshold. If cost exceeds
1219   // this Threshold any time, and cost cannot decrease, we can stop processing
1220   // the rest of the function body.
1221   Threshold += (SingleBBBonus + FiftyPercentVectorBonus);
1222 
1223   // Give out bonuses per argument, as the instructions setting them up will
1224   // be gone after inlining.
1225   for (unsigned I = 0, E = CS.arg_size(); I != E; ++I) {
1226     if (CS.isByValArgument(I)) {
1227       // We approximate the number of loads and stores needed by dividing the
1228       // size of the byval type by the target's pointer size.
1229       PointerType *PTy = cast<PointerType>(CS.getArgument(I)->getType());
1230       unsigned TypeSize = DL.getTypeSizeInBits(PTy->getElementType());
1231       unsigned PointerSize = DL.getPointerSizeInBits();
1232       // Ceiling division.
1233       unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
1234 
1235       // If it generates more than 8 stores it is likely to be expanded as an
1236       // inline memcpy so we take that as an upper bound. Otherwise we assume
1237       // one load and one store per word copied.
1238       // FIXME: The maxStoresPerMemcpy setting from the target should be used
1239       // here instead of a magic number of 8, but it's not available via
1240       // DataLayout.
1241       NumStores = std::min(NumStores, 8U);
1242 
1243       Cost -= 2 * NumStores * InlineConstants::InstrCost;
1244     } else {
1245       // For non-byval arguments subtract off one instruction per call
1246       // argument.
1247       Cost -= InlineConstants::InstrCost;
1248     }
1249   }
1250 
1251   // If there is only one call of the function, and it has internal linkage,
1252   // the cost of inlining it drops dramatically.
1253   bool OnlyOneCallAndLocalLinkage = F.hasLocalLinkage() && F.hasOneUse() &&
1254     &F == CS.getCalledFunction();
1255   if (OnlyOneCallAndLocalLinkage)
1256     Cost += InlineConstants::LastCallToStaticBonus;
1257 
1258   // If this function uses the coldcc calling convention, prefer not to inline
1259   // it.
1260   if (F.getCallingConv() == CallingConv::Cold)
1261     Cost += InlineConstants::ColdccPenalty;
1262 
1263   // Check if we're done. This can happen due to bonuses and penalties.
1264   if (Cost > Threshold)
1265     return false;
1266 
1267   if (F.empty())
1268     return true;
1269 
1270   Function *Caller = CS.getInstruction()->getParent()->getParent();
1271   // Check if the caller function is recursive itself.
1272   for (User *U : Caller->users()) {
1273     CallSite Site(U);
1274     if (!Site)
1275       continue;
1276     Instruction *I = Site.getInstruction();
1277     if (I->getParent()->getParent() == Caller) {
1278       IsCallerRecursive = true;
1279       break;
1280     }
1281   }
1282 
1283   // Populate our simplified values by mapping from function arguments to call
1284   // arguments with known important simplifications.
1285   CallSite::arg_iterator CAI = CS.arg_begin();
1286   for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end();
1287        FAI != FAE; ++FAI, ++CAI) {
1288     assert(CAI != CS.arg_end());
1289     if (Constant *C = dyn_cast<Constant>(CAI))
1290       SimplifiedValues[&*FAI] = C;
1291 
1292     Value *PtrArg = *CAI;
1293     if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
1294       ConstantOffsetPtrs[&*FAI] = std::make_pair(PtrArg, C->getValue());
1295 
1296       // We can SROA any pointer arguments derived from alloca instructions.
1297       if (isa<AllocaInst>(PtrArg)) {
1298         SROAArgValues[&*FAI] = PtrArg;
1299         SROAArgCosts[PtrArg] = 0;
1300       }
1301     }
1302   }
1303   NumConstantArgs = SimplifiedValues.size();
1304   NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
1305   NumAllocaArgs = SROAArgValues.size();
1306 
1307   // FIXME: If a caller has multiple calls to a callee, we end up recomputing
1308   // the ephemeral values multiple times (and they're completely determined by
1309   // the callee, so this is purely duplicate work).
1310   SmallPtrSet<const Value *, 32> EphValues;
1311   CodeMetrics::collectEphemeralValues(&F, &ACT->getAssumptionCache(F), EphValues);
1312 
1313   // The worklist of live basic blocks in the callee *after* inlining. We avoid
1314   // adding basic blocks of the callee which can be proven to be dead for this
1315   // particular call site in order to get more accurate cost estimates. This
1316   // requires a somewhat heavyweight iteration pattern: we need to walk the
1317   // basic blocks in a breadth-first order as we insert live successors. To
1318   // accomplish this, prioritizing for small iterations because we exit after
1319   // crossing our threshold, we use a small-size optimized SetVector.
1320   typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
1321                                   SmallPtrSet<BasicBlock *, 16> > BBSetVector;
1322   BBSetVector BBWorklist;
1323   BBWorklist.insert(&F.getEntryBlock());
1324   // Note that we *must not* cache the size, this loop grows the worklist.
1325   for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
1326     // Bail out the moment we cross the threshold. This means we'll under-count
1327     // the cost, but only when undercounting doesn't matter.
1328     if (Cost > Threshold)
1329       break;
1330 
1331     BasicBlock *BB = BBWorklist[Idx];
1332     if (BB->empty())
1333       continue;
1334 
1335     // Disallow inlining a blockaddress. A blockaddress only has defined
1336     // behavior for an indirect branch in the same function, and we do not
1337     // currently support inlining indirect branches. But, the inliner may not
1338     // see an indirect branch that ends up being dead code at a particular call
1339     // site. If the blockaddress escapes the function, e.g., via a global
1340     // variable, inlining may lead to an invalid cross-function reference.
1341     if (BB->hasAddressTaken())
1342       return false;
1343 
1344     // Analyze the cost of this block. If we blow through the threshold, this
1345     // returns false, and we can bail on out.
1346     if (!analyzeBlock(BB, EphValues))
1347       return false;
1348 
1349     TerminatorInst *TI = BB->getTerminator();
1350 
1351     // Add in the live successors by first checking whether we have terminator
1352     // that may be simplified based on the values simplified by this call.
1353     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1354       if (BI->isConditional()) {
1355         Value *Cond = BI->getCondition();
1356         if (ConstantInt *SimpleCond
1357               = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
1358           BBWorklist.insert(BI->getSuccessor(SimpleCond->isZero() ? 1 : 0));
1359           continue;
1360         }
1361       }
1362     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1363       Value *Cond = SI->getCondition();
1364       if (ConstantInt *SimpleCond
1365             = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
1366         BBWorklist.insert(SI->findCaseValue(SimpleCond).getCaseSuccessor());
1367         continue;
1368       }
1369     }
1370 
1371     // If we're unable to select a particular successor, just count all of
1372     // them.
1373     for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
1374          ++TIdx)
1375       BBWorklist.insert(TI->getSuccessor(TIdx));
1376 
1377     // If we had any successors at this point, than post-inlining is likely to
1378     // have them as well. Note that we assume any basic blocks which existed
1379     // due to branches or switches which folded above will also fold after
1380     // inlining.
1381     if (SingleBB && TI->getNumSuccessors() > 1) {
1382       // Take off the bonus we applied to the threshold.
1383       Threshold -= SingleBBBonus;
1384       SingleBB = false;
1385     }
1386   }
1387 
1388   // If this is a noduplicate call, we can still inline as long as
1389   // inlining this would cause the removal of the caller (so the instruction
1390   // is not actually duplicated, just moved).
1391   if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall)
1392     return false;
1393 
1394   // We applied the maximum possible vector bonus at the beginning. Now,
1395   // subtract the excess bonus, if any, from the Threshold before
1396   // comparing against Cost.
1397   if (NumVectorInstructions <= NumInstructions / 10)
1398     Threshold -= FiftyPercentVectorBonus;
1399   else if (NumVectorInstructions <= NumInstructions / 2)
1400     Threshold -= (FiftyPercentVectorBonus - TenPercentVectorBonus);
1401 
1402   return Cost < std::max(1, Threshold);
1403 }
1404 
1405 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1406 /// \brief Dump stats about this call's analysis.
1407 LLVM_DUMP_METHOD void CallAnalyzer::dump() {
1408 #define DEBUG_PRINT_STAT(x) dbgs() << "      " #x ": " << x << "\n"
1409   DEBUG_PRINT_STAT(NumConstantArgs);
1410   DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
1411   DEBUG_PRINT_STAT(NumAllocaArgs);
1412   DEBUG_PRINT_STAT(NumConstantPtrCmps);
1413   DEBUG_PRINT_STAT(NumConstantPtrDiffs);
1414   DEBUG_PRINT_STAT(NumInstructionsSimplified);
1415   DEBUG_PRINT_STAT(NumInstructions);
1416   DEBUG_PRINT_STAT(SROACostSavings);
1417   DEBUG_PRINT_STAT(SROACostSavingsLost);
1418   DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
1419   DEBUG_PRINT_STAT(Cost);
1420   DEBUG_PRINT_STAT(Threshold);
1421 #undef DEBUG_PRINT_STAT
1422 }
1423 #endif
1424 
1425 /// \brief Test that two functions either have or have not the given attribute
1426 ///        at the same time.
1427 template<typename AttrKind>
1428 static bool attributeMatches(Function *F1, Function *F2, AttrKind Attr) {
1429   return F1->getFnAttribute(Attr) == F2->getFnAttribute(Attr);
1430 }
1431 
1432 /// \brief Test that there are no attribute conflicts between Caller and Callee
1433 ///        that prevent inlining.
1434 static bool functionsHaveCompatibleAttributes(Function *Caller,
1435                                               Function *Callee,
1436                                               TargetTransformInfo &TTI) {
1437   return TTI.areInlineCompatible(Caller, Callee) &&
1438          AttributeFuncs::areInlineCompatible(*Caller, *Callee);
1439 }
1440 
1441 InlineCost llvm::getInlineCost(CallSite CS, int DefaultThreshold,
1442                                TargetTransformInfo &CalleeTTI,
1443                                AssumptionCacheTracker *ACT) {
1444   return getInlineCost(CS, CS.getCalledFunction(), DefaultThreshold, CalleeTTI,
1445                        ACT);
1446 }
1447 
1448 int llvm::computeThresholdFromOptLevels(unsigned OptLevel,
1449                                         unsigned SizeOptLevel) {
1450   if (OptLevel > 2)
1451     return OptAggressiveThreshold;
1452   if (SizeOptLevel == 1) // -Os
1453     return OptSizeThreshold;
1454   if (SizeOptLevel == 2) // -Oz
1455     return OptMinSizeThreshold;
1456   return DefaultInlineThreshold;
1457 }
1458 
1459 int llvm::getDefaultInlineThreshold() { return DefaultInlineThreshold; }
1460 
1461 InlineCost llvm::getInlineCost(CallSite CS, Function *Callee,
1462                                int DefaultThreshold,
1463                                TargetTransformInfo &CalleeTTI,
1464                                AssumptionCacheTracker *ACT) {
1465 
1466   // Cannot inline indirect calls.
1467   if (!Callee)
1468     return llvm::InlineCost::getNever();
1469 
1470   // Calls to functions with always-inline attributes should be inlined
1471   // whenever possible.
1472   if (CS.hasFnAttr(Attribute::AlwaysInline)) {
1473     if (isInlineViable(*Callee))
1474       return llvm::InlineCost::getAlways();
1475     return llvm::InlineCost::getNever();
1476   }
1477 
1478   // Never inline functions with conflicting attributes (unless callee has
1479   // always-inline attribute).
1480   if (!functionsHaveCompatibleAttributes(CS.getCaller(), Callee, CalleeTTI))
1481     return llvm::InlineCost::getNever();
1482 
1483   // Don't inline this call if the caller has the optnone attribute.
1484   if (CS.getCaller()->hasFnAttribute(Attribute::OptimizeNone))
1485     return llvm::InlineCost::getNever();
1486 
1487   // Don't inline functions which can be interposed at link-time.  Don't inline
1488   // functions marked noinline or call sites marked noinline.
1489   // Note: inlining non-exact non-interposable fucntions is fine, since we know
1490   // we have *a* correct implementation of the source level function.
1491   if (Callee->isInterposable() ||
1492       Callee->hasFnAttribute(Attribute::NoInline) || CS.isNoInline())
1493     return llvm::InlineCost::getNever();
1494 
1495   DEBUG(llvm::dbgs() << "      Analyzing call of " << Callee->getName()
1496         << "...\n");
1497 
1498   CallAnalyzer CA(CalleeTTI, ACT, *Callee, DefaultThreshold, CS);
1499   bool ShouldInline = CA.analyzeCall(CS);
1500 
1501   DEBUG(CA.dump());
1502 
1503   // Check if there was a reason to force inlining or no inlining.
1504   if (!ShouldInline && CA.getCost() < CA.getThreshold())
1505     return InlineCost::getNever();
1506   if (ShouldInline && CA.getCost() >= CA.getThreshold())
1507     return InlineCost::getAlways();
1508 
1509   return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());
1510 }
1511 
1512 bool llvm::isInlineViable(Function &F) {
1513   bool ReturnsTwice = F.hasFnAttribute(Attribute::ReturnsTwice);
1514   for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
1515     // Disallow inlining of functions which contain indirect branches or
1516     // blockaddresses.
1517     if (isa<IndirectBrInst>(BI->getTerminator()) || BI->hasAddressTaken())
1518       return false;
1519 
1520     for (auto &II : *BI) {
1521       CallSite CS(&II);
1522       if (!CS)
1523         continue;
1524 
1525       // Disallow recursive calls.
1526       if (&F == CS.getCalledFunction())
1527         return false;
1528 
1529       // Disallow calls which expose returns-twice to a function not previously
1530       // attributed as such.
1531       if (!ReturnsTwice && CS.isCall() &&
1532           cast<CallInst>(CS.getInstruction())->canReturnTwice())
1533         return false;
1534 
1535       // Disallow inlining functions that call @llvm.localescape. Doing this
1536       // correctly would require major changes to the inliner.
1537       if (CS.getCalledFunction() &&
1538           CS.getCalledFunction()->getIntrinsicID() ==
1539               llvm::Intrinsic::localescape)
1540         return false;
1541     }
1542   }
1543 
1544   return true;
1545 }
1546