LLVM API Documentation

InlineCost.cpp
Go to the documentation of this file.
00001 //===- InlineCost.cpp - Cost analysis for inliner -------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements inline cost analysis.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/Analysis/InlineCost.h"
00015 #include "llvm/ADT/STLExtras.h"
00016 #include "llvm/ADT/SetVector.h"
00017 #include "llvm/ADT/SmallPtrSet.h"
00018 #include "llvm/ADT/SmallVector.h"
00019 #include "llvm/ADT/Statistic.h"
00020 #include "llvm/Analysis/ConstantFolding.h"
00021 #include "llvm/Analysis/InstructionSimplify.h"
00022 #include "llvm/Analysis/TargetTransformInfo.h"
00023 #include "llvm/IR/CallSite.h"
00024 #include "llvm/IR/CallingConv.h"
00025 #include "llvm/IR/DataLayout.h"
00026 #include "llvm/IR/GetElementPtrTypeIterator.h"
00027 #include "llvm/IR/GlobalAlias.h"
00028 #include "llvm/IR/InstVisitor.h"
00029 #include "llvm/IR/IntrinsicInst.h"
00030 #include "llvm/IR/Operator.h"
00031 #include "llvm/Support/Debug.h"
00032 #include "llvm/Support/raw_ostream.h"
00033 
00034 using namespace llvm;
00035 
00036 #define DEBUG_TYPE "inline-cost"
00037 
00038 STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed");
00039 
00040 namespace {
00041 
00042 class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> {
00043   typedef InstVisitor<CallAnalyzer, bool> Base;
00044   friend class InstVisitor<CallAnalyzer, bool>;
00045 
00046   // DataLayout if available, or null.
00047   const DataLayout *const DL;
00048 
00049   /// The TargetTransformInfo available for this compilation.
00050   const TargetTransformInfo &TTI;
00051 
00052   // The called function.
00053   Function &F;
00054 
00055   int Threshold;
00056   int Cost;
00057 
00058   bool IsCallerRecursive;
00059   bool IsRecursiveCall;
00060   bool ExposesReturnsTwice;
00061   bool HasDynamicAlloca;
00062   bool ContainsNoDuplicateCall;
00063   bool HasReturn;
00064   bool HasIndirectBr;
00065 
00066   /// Number of bytes allocated statically by the callee.
00067   uint64_t AllocatedSize;
00068   unsigned NumInstructions, NumVectorInstructions;
00069   int FiftyPercentVectorBonus, TenPercentVectorBonus;
00070   int VectorBonus;
00071 
00072   // While we walk the potentially-inlined instructions, we build up and
00073   // maintain a mapping of simplified values specific to this callsite. The
00074   // idea is to propagate any special information we have about arguments to
00075   // this call through the inlinable section of the function, and account for
00076   // likely simplifications post-inlining. The most important aspect we track
00077   // is CFG altering simplifications -- when we prove a basic block dead, that
00078   // can cause dramatic shifts in the cost of inlining a function.
00079   DenseMap<Value *, Constant *> SimplifiedValues;
00080 
00081   // Keep track of the values which map back (through function arguments) to
00082   // allocas on the caller stack which could be simplified through SROA.
00083   DenseMap<Value *, Value *> SROAArgValues;
00084 
00085   // The mapping of caller Alloca values to their accumulated cost savings. If
00086   // we have to disable SROA for one of the allocas, this tells us how much
00087   // cost must be added.
00088   DenseMap<Value *, int> SROAArgCosts;
00089 
00090   // Keep track of values which map to a pointer base and constant offset.
00091   DenseMap<Value *, std::pair<Value *, APInt> > ConstantOffsetPtrs;
00092 
00093   // Custom simplification helper routines.
00094   bool isAllocaDerivedArg(Value *V);
00095   bool lookupSROAArgAndCost(Value *V, Value *&Arg,
00096                             DenseMap<Value *, int>::iterator &CostIt);
00097   void disableSROA(DenseMap<Value *, int>::iterator CostIt);
00098   void disableSROA(Value *V);
00099   void accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
00100                           int InstructionCost);
00101   bool isGEPOffsetConstant(GetElementPtrInst &GEP);
00102   bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
00103   bool simplifyCallSite(Function *F, CallSite CS);
00104   ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
00105 
00106   // Custom analysis routines.
00107   bool analyzeBlock(BasicBlock *BB);
00108 
00109   // Disable several entry points to the visitor so we don't accidentally use
00110   // them by declaring but not defining them here.
00111   void visit(Module *);     void visit(Module &);
00112   void visit(Function *);   void visit(Function &);
00113   void visit(BasicBlock *); void visit(BasicBlock &);
00114 
00115   // Provide base case for our instruction visit.
00116   bool visitInstruction(Instruction &I);
00117 
00118   // Our visit overrides.
00119   bool visitAlloca(AllocaInst &I);
00120   bool visitPHI(PHINode &I);
00121   bool visitGetElementPtr(GetElementPtrInst &I);
00122   bool visitBitCast(BitCastInst &I);
00123   bool visitPtrToInt(PtrToIntInst &I);
00124   bool visitIntToPtr(IntToPtrInst &I);
00125   bool visitCastInst(CastInst &I);
00126   bool visitUnaryInstruction(UnaryInstruction &I);
00127   bool visitCmpInst(CmpInst &I);
00128   bool visitSub(BinaryOperator &I);
00129   bool visitBinaryOperator(BinaryOperator &I);
00130   bool visitLoad(LoadInst &I);
00131   bool visitStore(StoreInst &I);
00132   bool visitExtractValue(ExtractValueInst &I);
00133   bool visitInsertValue(InsertValueInst &I);
00134   bool visitCallSite(CallSite CS);
00135   bool visitReturnInst(ReturnInst &RI);
00136   bool visitBranchInst(BranchInst &BI);
00137   bool visitSwitchInst(SwitchInst &SI);
00138   bool visitIndirectBrInst(IndirectBrInst &IBI);
00139   bool visitResumeInst(ResumeInst &RI);
00140   bool visitUnreachableInst(UnreachableInst &I);
00141 
00142 public:
00143   CallAnalyzer(const DataLayout *DL, const TargetTransformInfo &TTI,
00144                Function &Callee, int Threshold)
00145       : DL(DL), TTI(TTI), F(Callee), Threshold(Threshold), Cost(0),
00146         IsCallerRecursive(false), IsRecursiveCall(false),
00147         ExposesReturnsTwice(false), HasDynamicAlloca(false),
00148         ContainsNoDuplicateCall(false), HasReturn(false), HasIndirectBr(false),
00149         AllocatedSize(0), NumInstructions(0), NumVectorInstructions(0),
00150         FiftyPercentVectorBonus(0), TenPercentVectorBonus(0), VectorBonus(0),
00151         NumConstantArgs(0), NumConstantOffsetPtrArgs(0), NumAllocaArgs(0),
00152         NumConstantPtrCmps(0), NumConstantPtrDiffs(0),
00153         NumInstructionsSimplified(0), SROACostSavings(0),
00154         SROACostSavingsLost(0) {}
00155 
00156   bool analyzeCall(CallSite CS);
00157 
00158   int getThreshold() { return Threshold; }
00159   int getCost() { return Cost; }
00160 
00161   // Keep a bunch of stats about the cost savings found so we can print them
00162   // out when debugging.
00163   unsigned NumConstantArgs;
00164   unsigned NumConstantOffsetPtrArgs;
00165   unsigned NumAllocaArgs;
00166   unsigned NumConstantPtrCmps;
00167   unsigned NumConstantPtrDiffs;
00168   unsigned NumInstructionsSimplified;
00169   unsigned SROACostSavings;
00170   unsigned SROACostSavingsLost;
00171 
00172   void dump();
00173 };
00174 
00175 } // namespace
00176 
00177 /// \brief Test whether the given value is an Alloca-derived function argument.
00178 bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
00179   return SROAArgValues.count(V);
00180 }
00181 
00182 /// \brief Lookup the SROA-candidate argument and cost iterator which V maps to.
00183 /// Returns false if V does not map to a SROA-candidate.
00184 bool CallAnalyzer::lookupSROAArgAndCost(
00185     Value *V, Value *&Arg, DenseMap<Value *, int>::iterator &CostIt) {
00186   if (SROAArgValues.empty() || SROAArgCosts.empty())
00187     return false;
00188 
00189   DenseMap<Value *, Value *>::iterator ArgIt = SROAArgValues.find(V);
00190   if (ArgIt == SROAArgValues.end())
00191     return false;
00192 
00193   Arg = ArgIt->second;
00194   CostIt = SROAArgCosts.find(Arg);
00195   return CostIt != SROAArgCosts.end();
00196 }
00197 
00198 /// \brief Disable SROA for the candidate marked by this cost iterator.
00199 ///
00200 /// This marks the candidate as no longer viable for SROA, and adds the cost
00201 /// savings associated with it back into the inline cost measurement.
00202 void CallAnalyzer::disableSROA(DenseMap<Value *, int>::iterator CostIt) {
00203   // If we're no longer able to perform SROA we need to undo its cost savings
00204   // and prevent subsequent analysis.
00205   Cost += CostIt->second;
00206   SROACostSavings -= CostIt->second;
00207   SROACostSavingsLost += CostIt->second;
00208   SROAArgCosts.erase(CostIt);
00209 }
00210 
00211 /// \brief If 'V' maps to a SROA candidate, disable SROA for it.
00212 void CallAnalyzer::disableSROA(Value *V) {
00213   Value *SROAArg;
00214   DenseMap<Value *, int>::iterator CostIt;
00215   if (lookupSROAArgAndCost(V, SROAArg, CostIt))
00216     disableSROA(CostIt);
00217 }
00218 
00219 /// \brief Accumulate the given cost for a particular SROA candidate.
00220 void CallAnalyzer::accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
00221                                       int InstructionCost) {
00222   CostIt->second += InstructionCost;
00223   SROACostSavings += InstructionCost;
00224 }
00225 
00226 /// \brief Check whether a GEP's indices are all constant.
00227 ///
00228 /// Respects any simplified values known during the analysis of this callsite.
00229 bool CallAnalyzer::isGEPOffsetConstant(GetElementPtrInst &GEP) {
00230   for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I)
00231     if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I))
00232       return false;
00233 
00234   return true;
00235 }
00236 
00237 /// \brief Accumulate a constant GEP offset into an APInt if possible.
00238 ///
00239 /// Returns false if unable to compute the offset for any reason. Respects any
00240 /// simplified values known during the analysis of this callsite.
00241 bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
00242   if (!DL)
00243     return false;
00244 
00245   unsigned IntPtrWidth = DL->getPointerSizeInBits();
00246   assert(IntPtrWidth == Offset.getBitWidth());
00247 
00248   for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
00249        GTI != GTE; ++GTI) {
00250     ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
00251     if (!OpC)
00252       if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
00253         OpC = dyn_cast<ConstantInt>(SimpleOp);
00254     if (!OpC)
00255       return false;
00256     if (OpC->isZero()) continue;
00257 
00258     // Handle a struct index, which adds its field offset to the pointer.
00259     if (StructType *STy = dyn_cast<StructType>(*GTI)) {
00260       unsigned ElementIdx = OpC->getZExtValue();
00261       const StructLayout *SL = DL->getStructLayout(STy);
00262       Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
00263       continue;
00264     }
00265 
00266     APInt TypeSize(IntPtrWidth, DL->getTypeAllocSize(GTI.getIndexedType()));
00267     Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
00268   }
00269   return true;
00270 }
00271 
00272 bool CallAnalyzer::visitAlloca(AllocaInst &I) {
00273   // Check whether inlining will turn a dynamic alloca into a static
00274   // alloca, and handle that case.
00275   if (I.isArrayAllocation()) {
00276     if (Constant *Size = SimplifiedValues.lookup(I.getArraySize())) {
00277       ConstantInt *AllocSize = dyn_cast<ConstantInt>(Size);
00278       assert(AllocSize && "Allocation size not a constant int?");
00279       Type *Ty = I.getAllocatedType();
00280       AllocatedSize += Ty->getPrimitiveSizeInBits() * AllocSize->getZExtValue();
00281       return Base::visitAlloca(I);
00282     }
00283   }
00284 
00285   // Accumulate the allocated size.
00286   if (I.isStaticAlloca()) {
00287     Type *Ty = I.getAllocatedType();
00288     AllocatedSize += (DL ? DL->getTypeAllocSize(Ty) :
00289                       Ty->getPrimitiveSizeInBits());
00290   }
00291 
00292   // We will happily inline static alloca instructions.
00293   if (I.isStaticAlloca())
00294     return Base::visitAlloca(I);
00295 
00296   // FIXME: This is overly conservative. Dynamic allocas are inefficient for
00297   // a variety of reasons, and so we would like to not inline them into
00298   // functions which don't currently have a dynamic alloca. This simply
00299   // disables inlining altogether in the presence of a dynamic alloca.
00300   HasDynamicAlloca = true;
00301   return false;
00302 }
00303 
00304 bool CallAnalyzer::visitPHI(PHINode &I) {
00305   // FIXME: We should potentially be tracking values through phi nodes,
00306   // especially when they collapse to a single value due to deleted CFG edges
00307   // during inlining.
00308 
00309   // FIXME: We need to propagate SROA *disabling* through phi nodes, even
00310   // though we don't want to propagate it's bonuses. The idea is to disable
00311   // SROA if it *might* be used in an inappropriate manner.
00312 
00313   // Phi nodes are always zero-cost.
00314   return true;
00315 }
00316 
00317 bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
00318   Value *SROAArg;
00319   DenseMap<Value *, int>::iterator CostIt;
00320   bool SROACandidate = lookupSROAArgAndCost(I.getPointerOperand(),
00321                                             SROAArg, CostIt);
00322 
00323   // Try to fold GEPs of constant-offset call site argument pointers. This
00324   // requires target data and inbounds GEPs.
00325   if (DL && I.isInBounds()) {
00326     // Check if we have a base + offset for the pointer.
00327     Value *Ptr = I.getPointerOperand();
00328     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Ptr);
00329     if (BaseAndOffset.first) {
00330       // Check if the offset of this GEP is constant, and if so accumulate it
00331       // into Offset.
00332       if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)) {
00333         // Non-constant GEPs aren't folded, and disable SROA.
00334         if (SROACandidate)
00335           disableSROA(CostIt);
00336         return false;
00337       }
00338 
00339       // Add the result as a new mapping to Base + Offset.
00340       ConstantOffsetPtrs[&I] = BaseAndOffset;
00341 
00342       // Also handle SROA candidates here, we already know that the GEP is
00343       // all-constant indexed.
00344       if (SROACandidate)
00345         SROAArgValues[&I] = SROAArg;
00346 
00347       return true;
00348     }
00349   }
00350 
00351   if (isGEPOffsetConstant(I)) {
00352     if (SROACandidate)
00353       SROAArgValues[&I] = SROAArg;
00354 
00355     // Constant GEPs are modeled as free.
00356     return true;
00357   }
00358 
00359   // Variable GEPs will require math and will disable SROA.
00360   if (SROACandidate)
00361     disableSROA(CostIt);
00362   return false;
00363 }
00364 
00365 bool CallAnalyzer::visitBitCast(BitCastInst &I) {
00366   // Propagate constants through bitcasts.
00367   Constant *COp = dyn_cast<Constant>(I.getOperand(0));
00368   if (!COp)
00369     COp = SimplifiedValues.lookup(I.getOperand(0));
00370   if (COp)
00371     if (Constant *C = ConstantExpr::getBitCast(COp, I.getType())) {
00372       SimplifiedValues[&I] = C;
00373       return true;
00374     }
00375 
00376   // Track base/offsets through casts
00377   std::pair<Value *, APInt> BaseAndOffset
00378     = ConstantOffsetPtrs.lookup(I.getOperand(0));
00379   // Casts don't change the offset, just wrap it up.
00380   if (BaseAndOffset.first)
00381     ConstantOffsetPtrs[&I] = BaseAndOffset;
00382 
00383   // Also look for SROA candidates here.
00384   Value *SROAArg;
00385   DenseMap<Value *, int>::iterator CostIt;
00386   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
00387     SROAArgValues[&I] = SROAArg;
00388 
00389   // Bitcasts are always zero cost.
00390   return true;
00391 }
00392 
00393 bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
00394   const DataLayout *DL = I.getDataLayout();
00395   // Propagate constants through ptrtoint.
00396   Constant *COp = dyn_cast<Constant>(I.getOperand(0));
00397   if (!COp)
00398     COp = SimplifiedValues.lookup(I.getOperand(0));
00399   if (COp)
00400     if (Constant *C = ConstantExpr::getPtrToInt(COp, I.getType())) {
00401       SimplifiedValues[&I] = C;
00402       return true;
00403     }
00404 
00405   // Track base/offset pairs when converted to a plain integer provided the
00406   // integer is large enough to represent the pointer.
00407   unsigned IntegerSize = I.getType()->getScalarSizeInBits();
00408   if (DL && IntegerSize >= DL->getPointerSizeInBits()) {
00409     std::pair<Value *, APInt> BaseAndOffset
00410       = ConstantOffsetPtrs.lookup(I.getOperand(0));
00411     if (BaseAndOffset.first)
00412       ConstantOffsetPtrs[&I] = BaseAndOffset;
00413   }
00414 
00415   // This is really weird. Technically, ptrtoint will disable SROA. However,
00416   // unless that ptrtoint is *used* somewhere in the live basic blocks after
00417   // inlining, it will be nuked, and SROA should proceed. All of the uses which
00418   // would block SROA would also block SROA if applied directly to a pointer,
00419   // and so we can just add the integer in here. The only places where SROA is
00420   // preserved either cannot fire on an integer, or won't in-and-of themselves
00421   // disable SROA (ext) w/o some later use that we would see and disable.
00422   Value *SROAArg;
00423   DenseMap<Value *, int>::iterator CostIt;
00424   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
00425     SROAArgValues[&I] = SROAArg;
00426 
00427   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
00428 }
00429 
00430 bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
00431   const DataLayout *DL = I.getDataLayout();
00432   // Propagate constants through ptrtoint.
00433   Constant *COp = dyn_cast<Constant>(I.getOperand(0));
00434   if (!COp)
00435     COp = SimplifiedValues.lookup(I.getOperand(0));
00436   if (COp)
00437     if (Constant *C = ConstantExpr::getIntToPtr(COp, I.getType())) {
00438       SimplifiedValues[&I] = C;
00439       return true;
00440     }
00441 
00442   // Track base/offset pairs when round-tripped through a pointer without
00443   // modifications provided the integer is not too large.
00444   Value *Op = I.getOperand(0);
00445   unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
00446   if (DL && IntegerSize <= DL->getPointerSizeInBits()) {
00447     std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
00448     if (BaseAndOffset.first)
00449       ConstantOffsetPtrs[&I] = BaseAndOffset;
00450   }
00451 
00452   // "Propagate" SROA here in the same manner as we do for ptrtoint above.
00453   Value *SROAArg;
00454   DenseMap<Value *, int>::iterator CostIt;
00455   if (lookupSROAArgAndCost(Op, SROAArg, CostIt))
00456     SROAArgValues[&I] = SROAArg;
00457 
00458   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
00459 }
00460 
00461 bool CallAnalyzer::visitCastInst(CastInst &I) {
00462   // Propagate constants through ptrtoint.
00463   Constant *COp = dyn_cast<Constant>(I.getOperand(0));
00464   if (!COp)
00465     COp = SimplifiedValues.lookup(I.getOperand(0));
00466   if (COp)
00467     if (Constant *C = ConstantExpr::getCast(I.getOpcode(), COp, I.getType())) {
00468       SimplifiedValues[&I] = C;
00469       return true;
00470     }
00471 
00472   // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere.
00473   disableSROA(I.getOperand(0));
00474 
00475   return TargetTransformInfo::TCC_Free == TTI.getUserCost(&I);
00476 }
00477 
00478 bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) {
00479   Value *Operand = I.getOperand(0);
00480   Constant *COp = dyn_cast<Constant>(Operand);
00481   if (!COp)
00482     COp = SimplifiedValues.lookup(Operand);
00483   if (COp)
00484     if (Constant *C = ConstantFoldInstOperands(I.getOpcode(), I.getType(),
00485                                                COp, DL)) {
00486       SimplifiedValues[&I] = C;
00487       return true;
00488     }
00489 
00490   // Disable any SROA on the argument to arbitrary unary operators.
00491   disableSROA(Operand);
00492 
00493   return false;
00494 }
00495 
00496 bool CallAnalyzer::visitCmpInst(CmpInst &I) {
00497   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
00498   // First try to handle simplified comparisons.
00499   if (!isa<Constant>(LHS))
00500     if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
00501       LHS = SimpleLHS;
00502   if (!isa<Constant>(RHS))
00503     if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
00504       RHS = SimpleRHS;
00505   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
00506     if (Constant *CRHS = dyn_cast<Constant>(RHS))
00507       if (Constant *C = ConstantExpr::getCompare(I.getPredicate(), CLHS, CRHS)) {
00508         SimplifiedValues[&I] = C;
00509         return true;
00510       }
00511   }
00512 
00513   if (I.getOpcode() == Instruction::FCmp)
00514     return false;
00515 
00516   // Otherwise look for a comparison between constant offset pointers with
00517   // a common base.
00518   Value *LHSBase, *RHSBase;
00519   APInt LHSOffset, RHSOffset;
00520   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
00521   if (LHSBase) {
00522     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
00523     if (RHSBase && LHSBase == RHSBase) {
00524       // We have common bases, fold the icmp to a constant based on the
00525       // offsets.
00526       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
00527       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
00528       if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
00529         SimplifiedValues[&I] = C;
00530         ++NumConstantPtrCmps;
00531         return true;
00532       }
00533     }
00534   }
00535 
00536   // If the comparison is an equality comparison with null, we can simplify it
00537   // for any alloca-derived argument.
00538   if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)))
00539     if (isAllocaDerivedArg(I.getOperand(0))) {
00540       // We can actually predict the result of comparisons between an
00541       // alloca-derived value and null. Note that this fires regardless of
00542       // SROA firing.
00543       bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
00544       SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
00545                                         : ConstantInt::getFalse(I.getType());
00546       return true;
00547     }
00548 
00549   // Finally check for SROA candidates in comparisons.
00550   Value *SROAArg;
00551   DenseMap<Value *, int>::iterator CostIt;
00552   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
00553     if (isa<ConstantPointerNull>(I.getOperand(1))) {
00554       accumulateSROACost(CostIt, InlineConstants::InstrCost);
00555       return true;
00556     }
00557 
00558     disableSROA(CostIt);
00559   }
00560 
00561   return false;
00562 }
00563 
00564 bool CallAnalyzer::visitSub(BinaryOperator &I) {
00565   // Try to handle a special case: we can fold computing the difference of two
00566   // constant-related pointers.
00567   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
00568   Value *LHSBase, *RHSBase;
00569   APInt LHSOffset, RHSOffset;
00570   std::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
00571   if (LHSBase) {
00572     std::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
00573     if (RHSBase && LHSBase == RHSBase) {
00574       // We have common bases, fold the subtract to a constant based on the
00575       // offsets.
00576       Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
00577       Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
00578       if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
00579         SimplifiedValues[&I] = C;
00580         ++NumConstantPtrDiffs;
00581         return true;
00582       }
00583     }
00584   }
00585 
00586   // Otherwise, fall back to the generic logic for simplifying and handling
00587   // instructions.
00588   return Base::visitSub(I);
00589 }
00590 
00591 bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
00592   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
00593   if (!isa<Constant>(LHS))
00594     if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
00595       LHS = SimpleLHS;
00596   if (!isa<Constant>(RHS))
00597     if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
00598       RHS = SimpleRHS;
00599   Value *SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, DL);
00600   if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) {
00601     SimplifiedValues[&I] = C;
00602     return true;
00603   }
00604 
00605   // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
00606   disableSROA(LHS);
00607   disableSROA(RHS);
00608 
00609   return false;
00610 }
00611 
00612 bool CallAnalyzer::visitLoad(LoadInst &I) {
00613   Value *SROAArg;
00614   DenseMap<Value *, int>::iterator CostIt;
00615   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
00616     if (I.isSimple()) {
00617       accumulateSROACost(CostIt, InlineConstants::InstrCost);
00618       return true;
00619     }
00620 
00621     disableSROA(CostIt);
00622   }
00623 
00624   return false;
00625 }
00626 
00627 bool CallAnalyzer::visitStore(StoreInst &I) {
00628   Value *SROAArg;
00629   DenseMap<Value *, int>::iterator CostIt;
00630   if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
00631     if (I.isSimple()) {
00632       accumulateSROACost(CostIt, InlineConstants::InstrCost);
00633       return true;
00634     }
00635 
00636     disableSROA(CostIt);
00637   }
00638 
00639   return false;
00640 }
00641 
00642 bool CallAnalyzer::visitExtractValue(ExtractValueInst &I) {
00643   // Constant folding for extract value is trivial.
00644   Constant *C = dyn_cast<Constant>(I.getAggregateOperand());
00645   if (!C)
00646     C = SimplifiedValues.lookup(I.getAggregateOperand());
00647   if (C) {
00648     SimplifiedValues[&I] = ConstantExpr::getExtractValue(C, I.getIndices());
00649     return true;
00650   }
00651 
00652   // SROA can look through these but give them a cost.
00653   return false;
00654 }
00655 
00656 bool CallAnalyzer::visitInsertValue(InsertValueInst &I) {
00657   // Constant folding for insert value is trivial.
00658   Constant *AggC = dyn_cast<Constant>(I.getAggregateOperand());
00659   if (!AggC)
00660     AggC = SimplifiedValues.lookup(I.getAggregateOperand());
00661   Constant *InsertedC = dyn_cast<Constant>(I.getInsertedValueOperand());
00662   if (!InsertedC)
00663     InsertedC = SimplifiedValues.lookup(I.getInsertedValueOperand());
00664   if (AggC && InsertedC) {
00665     SimplifiedValues[&I] = ConstantExpr::getInsertValue(AggC, InsertedC,
00666                                                         I.getIndices());
00667     return true;
00668   }
00669 
00670   // SROA can look through these but give them a cost.
00671   return false;
00672 }
00673 
00674 /// \brief Try to simplify a call site.
00675 ///
00676 /// Takes a concrete function and callsite and tries to actually simplify it by
00677 /// analyzing the arguments and call itself with instsimplify. Returns true if
00678 /// it has simplified the callsite to some other entity (a constant), making it
00679 /// free.
00680 bool CallAnalyzer::simplifyCallSite(Function *F, CallSite CS) {
00681   // FIXME: Using the instsimplify logic directly for this is inefficient
00682   // because we have to continually rebuild the argument list even when no
00683   // simplifications can be performed. Until that is fixed with remapping
00684   // inside of instsimplify, directly constant fold calls here.
00685   if (!canConstantFoldCallTo(F))
00686     return false;
00687 
00688   // Try to re-map the arguments to constants.
00689   SmallVector<Constant *, 4> ConstantArgs;
00690   ConstantArgs.reserve(CS.arg_size());
00691   for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
00692        I != E; ++I) {
00693     Constant *C = dyn_cast<Constant>(*I);
00694     if (!C)
00695       C = dyn_cast_or_null<Constant>(SimplifiedValues.lookup(*I));
00696     if (!C)
00697       return false; // This argument doesn't map to a constant.
00698 
00699     ConstantArgs.push_back(C);
00700   }
00701   if (Constant *C = ConstantFoldCall(F, ConstantArgs)) {
00702     SimplifiedValues[CS.getInstruction()] = C;
00703     return true;
00704   }
00705 
00706   return false;
00707 }
00708 
00709 bool CallAnalyzer::visitCallSite(CallSite CS) {
00710   if (CS.hasFnAttr(Attribute::ReturnsTwice) &&
00711       !F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
00712                                       Attribute::ReturnsTwice)) {
00713     // This aborts the entire analysis.
00714     ExposesReturnsTwice = true;
00715     return false;
00716   }
00717   if (CS.isCall() &&
00718       cast<CallInst>(CS.getInstruction())->cannotDuplicate())
00719     ContainsNoDuplicateCall = true;
00720 
00721   if (Function *F = CS.getCalledFunction()) {
00722     // When we have a concrete function, first try to simplify it directly.
00723     if (simplifyCallSite(F, CS))
00724       return true;
00725 
00726     // Next check if it is an intrinsic we know about.
00727     // FIXME: Lift this into part of the InstVisitor.
00728     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
00729       switch (II->getIntrinsicID()) {
00730       default:
00731         return Base::visitCallSite(CS);
00732 
00733       case Intrinsic::memset:
00734       case Intrinsic::memcpy:
00735       case Intrinsic::memmove:
00736         // SROA can usually chew through these intrinsics, but they aren't free.
00737         return false;
00738       }
00739     }
00740 
00741     if (F == CS.getInstruction()->getParent()->getParent()) {
00742       // This flag will fully abort the analysis, so don't bother with anything
00743       // else.
00744       IsRecursiveCall = true;
00745       return false;
00746     }
00747 
00748     if (TTI.isLoweredToCall(F)) {
00749       // We account for the average 1 instruction per call argument setup
00750       // here.
00751       Cost += CS.arg_size() * InlineConstants::InstrCost;
00752 
00753       // Everything other than inline ASM will also have a significant cost
00754       // merely from making the call.
00755       if (!isa<InlineAsm>(CS.getCalledValue()))
00756         Cost += InlineConstants::CallPenalty;
00757     }
00758 
00759     return Base::visitCallSite(CS);
00760   }
00761 
00762   // Otherwise we're in a very special case -- an indirect function call. See
00763   // if we can be particularly clever about this.
00764   Value *Callee = CS.getCalledValue();
00765 
00766   // First, pay the price of the argument setup. We account for the average
00767   // 1 instruction per call argument setup here.
00768   Cost += CS.arg_size() * InlineConstants::InstrCost;
00769 
00770   // Next, check if this happens to be an indirect function call to a known
00771   // function in this inline context. If not, we've done all we can.
00772   Function *F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
00773   if (!F)
00774     return Base::visitCallSite(CS);
00775 
00776   // If we have a constant that we are calling as a function, we can peer
00777   // through it and see the function target. This happens not infrequently
00778   // during devirtualization and so we want to give it a hefty bonus for
00779   // inlining, but cap that bonus in the event that inlining wouldn't pan
00780   // out. Pretend to inline the function, with a custom threshold.
00781   CallAnalyzer CA(DL, TTI, *F, InlineConstants::IndirectCallThreshold);
00782   if (CA.analyzeCall(CS)) {
00783     // We were able to inline the indirect call! Subtract the cost from the
00784     // bonus we want to apply, but don't go below zero.
00785     Cost -= std::max(0, InlineConstants::IndirectCallThreshold - CA.getCost());
00786   }
00787 
00788   return Base::visitCallSite(CS);
00789 }
00790 
00791 bool CallAnalyzer::visitReturnInst(ReturnInst &RI) {
00792   // At least one return instruction will be free after inlining.
00793   bool Free = !HasReturn;
00794   HasReturn = true;
00795   return Free;
00796 }
00797 
00798 bool CallAnalyzer::visitBranchInst(BranchInst &BI) {
00799   // We model unconditional branches as essentially free -- they really
00800   // shouldn't exist at all, but handling them makes the behavior of the
00801   // inliner more regular and predictable. Interestingly, conditional branches
00802   // which will fold away are also free.
00803   return BI.isUnconditional() || isa<ConstantInt>(BI.getCondition()) ||
00804          dyn_cast_or_null<ConstantInt>(
00805              SimplifiedValues.lookup(BI.getCondition()));
00806 }
00807 
00808 bool CallAnalyzer::visitSwitchInst(SwitchInst &SI) {
00809   // We model unconditional switches as free, see the comments on handling
00810   // branches.
00811   return isa<ConstantInt>(SI.getCondition()) ||
00812          dyn_cast_or_null<ConstantInt>(
00813              SimplifiedValues.lookup(SI.getCondition()));
00814 }
00815 
00816 bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) {
00817   // We never want to inline functions that contain an indirectbr.  This is
00818   // incorrect because all the blockaddress's (in static global initializers
00819   // for example) would be referring to the original function, and this
00820   // indirect jump would jump from the inlined copy of the function into the
00821   // original function which is extremely undefined behavior.
00822   // FIXME: This logic isn't really right; we can safely inline functions with
00823   // indirectbr's as long as no other function or global references the
00824   // blockaddress of a block within the current function.  And as a QOI issue,
00825   // if someone is using a blockaddress without an indirectbr, and that
00826   // reference somehow ends up in another function or global, we probably don't
00827   // want to inline this function.
00828   HasIndirectBr = true;
00829   return false;
00830 }
00831 
00832 bool CallAnalyzer::visitResumeInst(ResumeInst &RI) {
00833   // FIXME: It's not clear that a single instruction is an accurate model for
00834   // the inline cost of a resume instruction.
00835   return false;
00836 }
00837 
00838 bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) {
00839   // FIXME: It might be reasonably to discount the cost of instructions leading
00840   // to unreachable as they have the lowest possible impact on both runtime and
00841   // code size.
00842   return true; // No actual code is needed for unreachable.
00843 }
00844 
00845 bool CallAnalyzer::visitInstruction(Instruction &I) {
00846   // Some instructions are free. All of the free intrinsics can also be
00847   // handled by SROA, etc.
00848   if (TargetTransformInfo::TCC_Free == TTI.getUserCost(&I))
00849     return true;
00850 
00851   // We found something we don't understand or can't handle. Mark any SROA-able
00852   // values in the operand list as no longer viable.
00853   for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI)
00854     disableSROA(*OI);
00855 
00856   return false;
00857 }
00858 
00859 
00860 /// \brief Analyze a basic block for its contribution to the inline cost.
00861 ///
00862 /// This method walks the analyzer over every instruction in the given basic
00863 /// block and accounts for their cost during inlining at this callsite. It
00864 /// aborts early if the threshold has been exceeded or an impossible to inline
00865 /// construct has been detected. It returns false if inlining is no longer
00866 /// viable, and true if inlining remains viable.
00867 bool CallAnalyzer::analyzeBlock(BasicBlock *BB) {
00868   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
00869     // FIXME: Currently, the number of instructions in a function regardless of
00870     // our ability to simplify them during inline to constants or dead code,
00871     // are actually used by the vector bonus heuristic. As long as that's true,
00872     // we have to special case debug intrinsics here to prevent differences in
00873     // inlining due to debug symbols. Eventually, the number of unsimplified
00874     // instructions shouldn't factor into the cost computation, but until then,
00875     // hack around it here.
00876     if (isa<DbgInfoIntrinsic>(I))
00877       continue;
00878 
00879     ++NumInstructions;
00880     if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy())
00881       ++NumVectorInstructions;
00882 
00883     // If the instruction simplified to a constant, there is no cost to this
00884     // instruction. Visit the instructions using our InstVisitor to account for
00885     // all of the per-instruction logic. The visit tree returns true if we
00886     // consumed the instruction in any way, and false if the instruction's base
00887     // cost should count against inlining.
00888     if (Base::visit(I))
00889       ++NumInstructionsSimplified;
00890     else
00891       Cost += InlineConstants::InstrCost;
00892 
00893     // If the visit this instruction detected an uninlinable pattern, abort.
00894     if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca ||
00895         HasIndirectBr)
00896       return false;
00897 
00898     // If the caller is a recursive function then we don't want to inline
00899     // functions which allocate a lot of stack space because it would increase
00900     // the caller stack usage dramatically.
00901     if (IsCallerRecursive &&
00902         AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
00903       return false;
00904 
00905     if (NumVectorInstructions > NumInstructions/2)
00906       VectorBonus = FiftyPercentVectorBonus;
00907     else if (NumVectorInstructions > NumInstructions/10)
00908       VectorBonus = TenPercentVectorBonus;
00909     else
00910       VectorBonus = 0;
00911 
00912     // Check if we've past the threshold so we don't spin in huge basic
00913     // blocks that will never inline.
00914     if (Cost > (Threshold + VectorBonus))
00915       return false;
00916   }
00917 
00918   return true;
00919 }
00920 
00921 /// \brief Compute the base pointer and cumulative constant offsets for V.
00922 ///
00923 /// This strips all constant offsets off of V, leaving it the base pointer, and
00924 /// accumulates the total constant offset applied in the returned constant. It
00925 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
00926 /// no constant offsets applied.
00927 ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
00928   if (!DL || !V->getType()->isPointerTy())
00929     return nullptr;
00930 
00931   unsigned IntPtrWidth = DL->getPointerSizeInBits();
00932   APInt Offset = APInt::getNullValue(IntPtrWidth);
00933 
00934   // Even though we don't look through PHI nodes, we could be called on an
00935   // instruction in an unreachable block, which may be on a cycle.
00936   SmallPtrSet<Value *, 4> Visited;
00937   Visited.insert(V);
00938   do {
00939     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
00940       if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
00941         return nullptr;
00942       V = GEP->getPointerOperand();
00943     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
00944       V = cast<Operator>(V)->getOperand(0);
00945     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
00946       if (GA->mayBeOverridden())
00947         break;
00948       V = GA->getAliasee();
00949     } else {
00950       break;
00951     }
00952     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
00953   } while (Visited.insert(V));
00954 
00955   Type *IntPtrTy = DL->getIntPtrType(V->getContext());
00956   return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset));
00957 }
00958 
00959 /// \brief Analyze a call site for potential inlining.
00960 ///
00961 /// Returns true if inlining this call is viable, and false if it is not
00962 /// viable. It computes the cost and adjusts the threshold based on numerous
00963 /// factors and heuristics. If this method returns false but the computed cost
00964 /// is below the computed threshold, then inlining was forcibly disabled by
00965 /// some artifact of the routine.
00966 bool CallAnalyzer::analyzeCall(CallSite CS) {
00967   ++NumCallsAnalyzed;
00968 
00969   // Track whether the post-inlining function would have more than one basic
00970   // block. A single basic block is often intended for inlining. Balloon the
00971   // threshold by 50% until we pass the single-BB phase.
00972   bool SingleBB = true;
00973   int SingleBBBonus = Threshold / 2;
00974   Threshold += SingleBBBonus;
00975 
00976   // Perform some tweaks to the cost and threshold based on the direct
00977   // callsite information.
00978 
00979   // We want to more aggressively inline vector-dense kernels, so up the
00980   // threshold, and we'll lower it if the % of vector instructions gets too
00981   // low.
00982   assert(NumInstructions == 0);
00983   assert(NumVectorInstructions == 0);
00984   FiftyPercentVectorBonus = Threshold;
00985   TenPercentVectorBonus = Threshold / 2;
00986 
00987   // Give out bonuses per argument, as the instructions setting them up will
00988   // be gone after inlining.
00989   for (unsigned I = 0, E = CS.arg_size(); I != E; ++I) {
00990     if (DL && CS.isByValArgument(I)) {
00991       // We approximate the number of loads and stores needed by dividing the
00992       // size of the byval type by the target's pointer size.
00993       PointerType *PTy = cast<PointerType>(CS.getArgument(I)->getType());
00994       unsigned TypeSize = DL->getTypeSizeInBits(PTy->getElementType());
00995       unsigned PointerSize = DL->getPointerSizeInBits();
00996       // Ceiling division.
00997       unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
00998 
00999       // If it generates more than 8 stores it is likely to be expanded as an
01000       // inline memcpy so we take that as an upper bound. Otherwise we assume
01001       // one load and one store per word copied.
01002       // FIXME: The maxStoresPerMemcpy setting from the target should be used
01003       // here instead of a magic number of 8, but it's not available via
01004       // DataLayout.
01005       NumStores = std::min(NumStores, 8U);
01006 
01007       Cost -= 2 * NumStores * InlineConstants::InstrCost;
01008     } else {
01009       // For non-byval arguments subtract off one instruction per call
01010       // argument.
01011       Cost -= InlineConstants::InstrCost;
01012     }
01013   }
01014 
01015   // If there is only one call of the function, and it has internal linkage,
01016   // the cost of inlining it drops dramatically.
01017   bool OnlyOneCallAndLocalLinkage = F.hasLocalLinkage() && F.hasOneUse() &&
01018     &F == CS.getCalledFunction();
01019   if (OnlyOneCallAndLocalLinkage)
01020     Cost += InlineConstants::LastCallToStaticBonus;
01021 
01022   // If the instruction after the call, or if the normal destination of the
01023   // invoke is an unreachable instruction, the function is noreturn. As such,
01024   // there is little point in inlining this unless there is literally zero
01025   // cost.
01026   Instruction *Instr = CS.getInstruction();
01027   if (InvokeInst *II = dyn_cast<InvokeInst>(Instr)) {
01028     if (isa<UnreachableInst>(II->getNormalDest()->begin()))
01029       Threshold = 1;
01030   } else if (isa<UnreachableInst>(++BasicBlock::iterator(Instr)))
01031     Threshold = 1;
01032 
01033   // If this function uses the coldcc calling convention, prefer not to inline
01034   // it.
01035   if (F.getCallingConv() == CallingConv::Cold)
01036     Cost += InlineConstants::ColdccPenalty;
01037 
01038   // Check if we're done. This can happen due to bonuses and penalties.
01039   if (Cost > Threshold)
01040     return false;
01041 
01042   if (F.empty())
01043     return true;
01044 
01045   Function *Caller = CS.getInstruction()->getParent()->getParent();
01046   // Check if the caller function is recursive itself.
01047   for (User *U : Caller->users()) {
01048     CallSite Site(U);
01049     if (!Site)
01050       continue;
01051     Instruction *I = Site.getInstruction();
01052     if (I->getParent()->getParent() == Caller) {
01053       IsCallerRecursive = true;
01054       break;
01055     }
01056   }
01057 
01058   // Populate our simplified values by mapping from function arguments to call
01059   // arguments with known important simplifications.
01060   CallSite::arg_iterator CAI = CS.arg_begin();
01061   for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end();
01062        FAI != FAE; ++FAI, ++CAI) {
01063     assert(CAI != CS.arg_end());
01064     if (Constant *C = dyn_cast<Constant>(CAI))
01065       SimplifiedValues[FAI] = C;
01066 
01067     Value *PtrArg = *CAI;
01068     if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
01069       ConstantOffsetPtrs[FAI] = std::make_pair(PtrArg, C->getValue());
01070 
01071       // We can SROA any pointer arguments derived from alloca instructions.
01072       if (isa<AllocaInst>(PtrArg)) {
01073         SROAArgValues[FAI] = PtrArg;
01074         SROAArgCosts[PtrArg] = 0;
01075       }
01076     }
01077   }
01078   NumConstantArgs = SimplifiedValues.size();
01079   NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
01080   NumAllocaArgs = SROAArgValues.size();
01081 
01082   // The worklist of live basic blocks in the callee *after* inlining. We avoid
01083   // adding basic blocks of the callee which can be proven to be dead for this
01084   // particular call site in order to get more accurate cost estimates. This
01085   // requires a somewhat heavyweight iteration pattern: we need to walk the
01086   // basic blocks in a breadth-first order as we insert live successors. To
01087   // accomplish this, prioritizing for small iterations because we exit after
01088   // crossing our threshold, we use a small-size optimized SetVector.
01089   typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
01090                                   SmallPtrSet<BasicBlock *, 16> > BBSetVector;
01091   BBSetVector BBWorklist;
01092   BBWorklist.insert(&F.getEntryBlock());
01093   // Note that we *must not* cache the size, this loop grows the worklist.
01094   for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
01095     // Bail out the moment we cross the threshold. This means we'll under-count
01096     // the cost, but only when undercounting doesn't matter.
01097     if (Cost > (Threshold + VectorBonus))
01098       break;
01099 
01100     BasicBlock *BB = BBWorklist[Idx];
01101     if (BB->empty())
01102       continue;
01103 
01104     // Analyze the cost of this block. If we blow through the threshold, this
01105     // returns false, and we can bail on out.
01106     if (!analyzeBlock(BB)) {
01107       if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca ||
01108           HasIndirectBr)
01109         return false;
01110 
01111       // If the caller is a recursive function then we don't want to inline
01112       // functions which allocate a lot of stack space because it would increase
01113       // the caller stack usage dramatically.
01114       if (IsCallerRecursive &&
01115           AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
01116         return false;
01117 
01118       break;
01119     }
01120 
01121     TerminatorInst *TI = BB->getTerminator();
01122 
01123     // Add in the live successors by first checking whether we have terminator
01124     // that may be simplified based on the values simplified by this call.
01125     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
01126       if (BI->isConditional()) {
01127         Value *Cond = BI->getCondition();
01128         if (ConstantInt *SimpleCond
01129               = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
01130           BBWorklist.insert(BI->getSuccessor(SimpleCond->isZero() ? 1 : 0));
01131           continue;
01132         }
01133       }
01134     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
01135       Value *Cond = SI->getCondition();
01136       if (ConstantInt *SimpleCond
01137             = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
01138         BBWorklist.insert(SI->findCaseValue(SimpleCond).getCaseSuccessor());
01139         continue;
01140       }
01141     }
01142 
01143     // If we're unable to select a particular successor, just count all of
01144     // them.
01145     for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
01146          ++TIdx)
01147       BBWorklist.insert(TI->getSuccessor(TIdx));
01148 
01149     // If we had any successors at this point, than post-inlining is likely to
01150     // have them as well. Note that we assume any basic blocks which existed
01151     // due to branches or switches which folded above will also fold after
01152     // inlining.
01153     if (SingleBB && TI->getNumSuccessors() > 1) {
01154       // Take off the bonus we applied to the threshold.
01155       Threshold -= SingleBBBonus;
01156       SingleBB = false;
01157     }
01158   }
01159 
01160   // If this is a noduplicate call, we can still inline as long as
01161   // inlining this would cause the removal of the caller (so the instruction
01162   // is not actually duplicated, just moved).
01163   if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall)
01164     return false;
01165 
01166   Threshold += VectorBonus;
01167 
01168   return Cost < Threshold;
01169 }
01170 
01171 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
01172 /// \brief Dump stats about this call's analysis.
01173 void CallAnalyzer::dump() {
01174 #define DEBUG_PRINT_STAT(x) dbgs() << "      " #x ": " << x << "\n"
01175   DEBUG_PRINT_STAT(NumConstantArgs);
01176   DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
01177   DEBUG_PRINT_STAT(NumAllocaArgs);
01178   DEBUG_PRINT_STAT(NumConstantPtrCmps);
01179   DEBUG_PRINT_STAT(NumConstantPtrDiffs);
01180   DEBUG_PRINT_STAT(NumInstructionsSimplified);
01181   DEBUG_PRINT_STAT(SROACostSavings);
01182   DEBUG_PRINT_STAT(SROACostSavingsLost);
01183   DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
01184   DEBUG_PRINT_STAT(Cost);
01185   DEBUG_PRINT_STAT(Threshold);
01186   DEBUG_PRINT_STAT(VectorBonus);
01187 #undef DEBUG_PRINT_STAT
01188 }
01189 #endif
01190 
01191 INITIALIZE_PASS_BEGIN(InlineCostAnalysis, "inline-cost", "Inline Cost Analysis",
01192                       true, true)
01193 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
01194 INITIALIZE_PASS_END(InlineCostAnalysis, "inline-cost", "Inline Cost Analysis",
01195                     true, true)
01196 
01197 char InlineCostAnalysis::ID = 0;
01198 
01199 InlineCostAnalysis::InlineCostAnalysis() : CallGraphSCCPass(ID) {}
01200 
01201 InlineCostAnalysis::~InlineCostAnalysis() {}
01202 
01203 void InlineCostAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
01204   AU.setPreservesAll();
01205   AU.addRequired<TargetTransformInfo>();
01206   CallGraphSCCPass::getAnalysisUsage(AU);
01207 }
01208 
01209 bool InlineCostAnalysis::runOnSCC(CallGraphSCC &SCC) {
01210   TTI = &getAnalysis<TargetTransformInfo>();
01211   return false;
01212 }
01213 
01214 InlineCost InlineCostAnalysis::getInlineCost(CallSite CS, int Threshold) {
01215   return getInlineCost(CS, CS.getCalledFunction(), Threshold);
01216 }
01217 
01218 /// \brief Test that two functions either have or have not the given attribute
01219 ///        at the same time.
01220 static bool attributeMatches(Function *F1, Function *F2,
01221                              Attribute::AttrKind Attr) {
01222   return F1->hasFnAttribute(Attr) == F2->hasFnAttribute(Attr);
01223 }
01224 
01225 /// \brief Test that there are no attribute conflicts between Caller and Callee
01226 ///        that prevent inlining.
01227 static bool functionsHaveCompatibleAttributes(Function *Caller,
01228                                               Function *Callee) {
01229   return attributeMatches(Caller, Callee, Attribute::SanitizeAddress) &&
01230          attributeMatches(Caller, Callee, Attribute::SanitizeMemory) &&
01231          attributeMatches(Caller, Callee, Attribute::SanitizeThread);
01232 }
01233 
01234 InlineCost InlineCostAnalysis::getInlineCost(CallSite CS, Function *Callee,
01235                                              int Threshold) {
01236   // Cannot inline indirect calls.
01237   if (!Callee)
01238     return llvm::InlineCost::getNever();
01239 
01240   // Calls to functions with always-inline attributes should be inlined
01241   // whenever possible.
01242   if (Callee->hasFnAttribute(Attribute::AlwaysInline)) {
01243     if (isInlineViable(*Callee))
01244       return llvm::InlineCost::getAlways();
01245     return llvm::InlineCost::getNever();
01246   }
01247 
01248   // Never inline functions with conflicting attributes (unless callee has
01249   // always-inline attribute).
01250   if (!functionsHaveCompatibleAttributes(CS.getCaller(), Callee))
01251     return llvm::InlineCost::getNever();
01252 
01253   // Don't inline this call if the caller has the optnone attribute.
01254   if (CS.getCaller()->hasFnAttribute(Attribute::OptimizeNone))
01255     return llvm::InlineCost::getNever();
01256 
01257   // Don't inline functions which can be redefined at link-time to mean
01258   // something else.  Don't inline functions marked noinline or call sites
01259   // marked noinline.
01260   if (Callee->mayBeOverridden() ||
01261       Callee->hasFnAttribute(Attribute::NoInline) || CS.isNoInline())
01262     return llvm::InlineCost::getNever();
01263 
01264   DEBUG(llvm::dbgs() << "      Analyzing call of " << Callee->getName()
01265         << "...\n");
01266 
01267   CallAnalyzer CA(Callee->getDataLayout(), *TTI, *Callee, Threshold);
01268   bool ShouldInline = CA.analyzeCall(CS);
01269 
01270   DEBUG(CA.dump());
01271 
01272   // Check if there was a reason to force inlining or no inlining.
01273   if (!ShouldInline && CA.getCost() < CA.getThreshold())
01274     return InlineCost::getNever();
01275   if (ShouldInline && CA.getCost() >= CA.getThreshold())
01276     return InlineCost::getAlways();
01277 
01278   return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());
01279 }
01280 
01281 bool InlineCostAnalysis::isInlineViable(Function &F) {
01282   bool ReturnsTwice =
01283     F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
01284                                    Attribute::ReturnsTwice);
01285   for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
01286     // Disallow inlining of functions which contain an indirect branch.
01287     if (isa<IndirectBrInst>(BI->getTerminator()))
01288       return false;
01289 
01290     for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE;
01291          ++II) {
01292       CallSite CS(II);
01293       if (!CS)
01294         continue;
01295 
01296       // Disallow recursive calls.
01297       if (&F == CS.getCalledFunction())
01298         return false;
01299 
01300       // Disallow calls which expose returns-twice to a function not previously
01301       // attributed as such.
01302       if (!ReturnsTwice && CS.isCall() &&
01303           cast<CallInst>(CS.getInstruction())->canReturnTwice())
01304         return false;
01305     }
01306   }
01307 
01308   return true;
01309 }