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