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