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   if (isa<ConstantInt>(SI.getCondition()))
00812     return true;
00813   if (Value *V = SimplifiedValues.lookup(SI.getCondition()))
00814     if (isa<ConstantInt>(V))
00815       return true;
00816 
00817   // Otherwise, we need to accumulate a cost proportional to the number of
00818   // distinct successor blocks. This fan-out in the CFG cannot be represented
00819   // for free even if we can represent the core switch as a jumptable that
00820   // takes a single instruction.
00821   //
00822   // NB: We convert large switches which are just used to initialize large phi
00823   // nodes to lookup tables instead in simplify-cfg, so this shouldn't prevent
00824   // inlining those. It will prevent inlining in cases where the optimization
00825   // does not (yet) fire.
00826   SmallPtrSet<BasicBlock *, 8> SuccessorBlocks;
00827   SuccessorBlocks.insert(SI.getDefaultDest());
00828   for (auto I = SI.case_begin(), E = SI.case_end(); I != E; ++I)
00829     SuccessorBlocks.insert(I.getCaseSuccessor());
00830   // Add cost corresponding to the number of distinct destinations. The first
00831   // we model as free because of fallthrough.
00832   Cost += (SuccessorBlocks.size() - 1) * InlineConstants::InstrCost;
00833   return false;
00834 }
00835 
00836 bool CallAnalyzer::visitIndirectBrInst(IndirectBrInst &IBI) {
00837   // We never want to inline functions that contain an indirectbr.  This is
00838   // incorrect because all the blockaddress's (in static global initializers
00839   // for example) would be referring to the original function, and this
00840   // indirect jump would jump from the inlined copy of the function into the
00841   // original function which is extremely undefined behavior.
00842   // FIXME: This logic isn't really right; we can safely inline functions with
00843   // indirectbr's as long as no other function or global references the
00844   // blockaddress of a block within the current function.
00845   HasIndirectBr = true;
00846   return false;
00847 }
00848 
00849 bool CallAnalyzer::visitResumeInst(ResumeInst &RI) {
00850   // FIXME: It's not clear that a single instruction is an accurate model for
00851   // the inline cost of a resume instruction.
00852   return false;
00853 }
00854 
00855 bool CallAnalyzer::visitUnreachableInst(UnreachableInst &I) {
00856   // FIXME: It might be reasonably to discount the cost of instructions leading
00857   // to unreachable as they have the lowest possible impact on both runtime and
00858   // code size.
00859   return true; // No actual code is needed for unreachable.
00860 }
00861 
00862 bool CallAnalyzer::visitInstruction(Instruction &I) {
00863   // Some instructions are free. All of the free intrinsics can also be
00864   // handled by SROA, etc.
00865   if (TargetTransformInfo::TCC_Free == TTI.getUserCost(&I))
00866     return true;
00867 
00868   // We found something we don't understand or can't handle. Mark any SROA-able
00869   // values in the operand list as no longer viable.
00870   for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI)
00871     disableSROA(*OI);
00872 
00873   return false;
00874 }
00875 
00876 
00877 /// \brief Analyze a basic block for its contribution to the inline cost.
00878 ///
00879 /// This method walks the analyzer over every instruction in the given basic
00880 /// block and accounts for their cost during inlining at this callsite. It
00881 /// aborts early if the threshold has been exceeded or an impossible to inline
00882 /// construct has been detected. It returns false if inlining is no longer
00883 /// viable, and true if inlining remains viable.
00884 bool CallAnalyzer::analyzeBlock(BasicBlock *BB) {
00885   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
00886     // FIXME: Currently, the number of instructions in a function regardless of
00887     // our ability to simplify them during inline to constants or dead code,
00888     // are actually used by the vector bonus heuristic. As long as that's true,
00889     // we have to special case debug intrinsics here to prevent differences in
00890     // inlining due to debug symbols. Eventually, the number of unsimplified
00891     // instructions shouldn't factor into the cost computation, but until then,
00892     // hack around it here.
00893     if (isa<DbgInfoIntrinsic>(I))
00894       continue;
00895 
00896     ++NumInstructions;
00897     if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy())
00898       ++NumVectorInstructions;
00899 
00900     // If the instruction simplified to a constant, there is no cost to this
00901     // instruction. Visit the instructions using our InstVisitor to account for
00902     // all of the per-instruction logic. The visit tree returns true if we
00903     // consumed the instruction in any way, and false if the instruction's base
00904     // cost should count against inlining.
00905     if (Base::visit(I))
00906       ++NumInstructionsSimplified;
00907     else
00908       Cost += InlineConstants::InstrCost;
00909 
00910     // If the visit this instruction detected an uninlinable pattern, abort.
00911     if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca ||
00912         HasIndirectBr)
00913       return false;
00914 
00915     // If the caller is a recursive function then we don't want to inline
00916     // functions which allocate a lot of stack space because it would increase
00917     // the caller stack usage dramatically.
00918     if (IsCallerRecursive &&
00919         AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
00920       return false;
00921 
00922     if (NumVectorInstructions > NumInstructions/2)
00923       VectorBonus = FiftyPercentVectorBonus;
00924     else if (NumVectorInstructions > NumInstructions/10)
00925       VectorBonus = TenPercentVectorBonus;
00926     else
00927       VectorBonus = 0;
00928 
00929     // Check if we've past the threshold so we don't spin in huge basic
00930     // blocks that will never inline.
00931     if (Cost > (Threshold + VectorBonus))
00932       return false;
00933   }
00934 
00935   return true;
00936 }
00937 
00938 /// \brief Compute the base pointer and cumulative constant offsets for V.
00939 ///
00940 /// This strips all constant offsets off of V, leaving it the base pointer, and
00941 /// accumulates the total constant offset applied in the returned constant. It
00942 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
00943 /// no constant offsets applied.
00944 ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
00945   if (!DL || !V->getType()->isPointerTy())
00946     return nullptr;
00947 
00948   unsigned IntPtrWidth = DL->getPointerSizeInBits();
00949   APInt Offset = APInt::getNullValue(IntPtrWidth);
00950 
00951   // Even though we don't look through PHI nodes, we could be called on an
00952   // instruction in an unreachable block, which may be on a cycle.
00953   SmallPtrSet<Value *, 4> Visited;
00954   Visited.insert(V);
00955   do {
00956     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
00957       if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
00958         return nullptr;
00959       V = GEP->getPointerOperand();
00960     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
00961       V = cast<Operator>(V)->getOperand(0);
00962     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
00963       if (GA->mayBeOverridden())
00964         break;
00965       V = GA->getAliasee();
00966     } else {
00967       break;
00968     }
00969     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
00970   } while (Visited.insert(V));
00971 
00972   Type *IntPtrTy = DL->getIntPtrType(V->getContext());
00973   return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset));
00974 }
00975 
00976 /// \brief Analyze a call site for potential inlining.
00977 ///
00978 /// Returns true if inlining this call is viable, and false if it is not
00979 /// viable. It computes the cost and adjusts the threshold based on numerous
00980 /// factors and heuristics. If this method returns false but the computed cost
00981 /// is below the computed threshold, then inlining was forcibly disabled by
00982 /// some artifact of the routine.
00983 bool CallAnalyzer::analyzeCall(CallSite CS) {
00984   ++NumCallsAnalyzed;
00985 
00986   // Track whether the post-inlining function would have more than one basic
00987   // block. A single basic block is often intended for inlining. Balloon the
00988   // threshold by 50% until we pass the single-BB phase.
00989   bool SingleBB = true;
00990   int SingleBBBonus = Threshold / 2;
00991   Threshold += SingleBBBonus;
00992 
00993   // Perform some tweaks to the cost and threshold based on the direct
00994   // callsite information.
00995 
00996   // We want to more aggressively inline vector-dense kernels, so up the
00997   // threshold, and we'll lower it if the % of vector instructions gets too
00998   // low.
00999   assert(NumInstructions == 0);
01000   assert(NumVectorInstructions == 0);
01001   FiftyPercentVectorBonus = Threshold;
01002   TenPercentVectorBonus = Threshold / 2;
01003 
01004   // Give out bonuses per argument, as the instructions setting them up will
01005   // be gone after inlining.
01006   for (unsigned I = 0, E = CS.arg_size(); I != E; ++I) {
01007     if (DL && CS.isByValArgument(I)) {
01008       // We approximate the number of loads and stores needed by dividing the
01009       // size of the byval type by the target's pointer size.
01010       PointerType *PTy = cast<PointerType>(CS.getArgument(I)->getType());
01011       unsigned TypeSize = DL->getTypeSizeInBits(PTy->getElementType());
01012       unsigned PointerSize = DL->getPointerSizeInBits();
01013       // Ceiling division.
01014       unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
01015 
01016       // If it generates more than 8 stores it is likely to be expanded as an
01017       // inline memcpy so we take that as an upper bound. Otherwise we assume
01018       // one load and one store per word copied.
01019       // FIXME: The maxStoresPerMemcpy setting from the target should be used
01020       // here instead of a magic number of 8, but it's not available via
01021       // DataLayout.
01022       NumStores = std::min(NumStores, 8U);
01023 
01024       Cost -= 2 * NumStores * InlineConstants::InstrCost;
01025     } else {
01026       // For non-byval arguments subtract off one instruction per call
01027       // argument.
01028       Cost -= InlineConstants::InstrCost;
01029     }
01030   }
01031 
01032   // If there is only one call of the function, and it has internal linkage,
01033   // the cost of inlining it drops dramatically.
01034   bool OnlyOneCallAndLocalLinkage = F.hasLocalLinkage() && F.hasOneUse() &&
01035     &F == CS.getCalledFunction();
01036   if (OnlyOneCallAndLocalLinkage)
01037     Cost += InlineConstants::LastCallToStaticBonus;
01038 
01039   // If the instruction after the call, or if the normal destination of the
01040   // invoke is an unreachable instruction, the function is noreturn. As such,
01041   // there is little point in inlining this unless there is literally zero
01042   // cost.
01043   Instruction *Instr = CS.getInstruction();
01044   if (InvokeInst *II = dyn_cast<InvokeInst>(Instr)) {
01045     if (isa<UnreachableInst>(II->getNormalDest()->begin()))
01046       Threshold = 1;
01047   } else if (isa<UnreachableInst>(++BasicBlock::iterator(Instr)))
01048     Threshold = 1;
01049 
01050   // If this function uses the coldcc calling convention, prefer not to inline
01051   // it.
01052   if (F.getCallingConv() == CallingConv::Cold)
01053     Cost += InlineConstants::ColdccPenalty;
01054 
01055   // Check if we're done. This can happen due to bonuses and penalties.
01056   if (Cost > Threshold)
01057     return false;
01058 
01059   if (F.empty())
01060     return true;
01061 
01062   Function *Caller = CS.getInstruction()->getParent()->getParent();
01063   // Check if the caller function is recursive itself.
01064   for (User *U : Caller->users()) {
01065     CallSite Site(U);
01066     if (!Site)
01067       continue;
01068     Instruction *I = Site.getInstruction();
01069     if (I->getParent()->getParent() == Caller) {
01070       IsCallerRecursive = true;
01071       break;
01072     }
01073   }
01074 
01075   // Populate our simplified values by mapping from function arguments to call
01076   // arguments with known important simplifications.
01077   CallSite::arg_iterator CAI = CS.arg_begin();
01078   for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end();
01079        FAI != FAE; ++FAI, ++CAI) {
01080     assert(CAI != CS.arg_end());
01081     if (Constant *C = dyn_cast<Constant>(CAI))
01082       SimplifiedValues[FAI] = C;
01083 
01084     Value *PtrArg = *CAI;
01085     if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
01086       ConstantOffsetPtrs[FAI] = std::make_pair(PtrArg, C->getValue());
01087 
01088       // We can SROA any pointer arguments derived from alloca instructions.
01089       if (isa<AllocaInst>(PtrArg)) {
01090         SROAArgValues[FAI] = PtrArg;
01091         SROAArgCosts[PtrArg] = 0;
01092       }
01093     }
01094   }
01095   NumConstantArgs = SimplifiedValues.size();
01096   NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
01097   NumAllocaArgs = SROAArgValues.size();
01098 
01099   // The worklist of live basic blocks in the callee *after* inlining. We avoid
01100   // adding basic blocks of the callee which can be proven to be dead for this
01101   // particular call site in order to get more accurate cost estimates. This
01102   // requires a somewhat heavyweight iteration pattern: we need to walk the
01103   // basic blocks in a breadth-first order as we insert live successors. To
01104   // accomplish this, prioritizing for small iterations because we exit after
01105   // crossing our threshold, we use a small-size optimized SetVector.
01106   typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
01107                                   SmallPtrSet<BasicBlock *, 16> > BBSetVector;
01108   BBSetVector BBWorklist;
01109   BBWorklist.insert(&F.getEntryBlock());
01110   // Note that we *must not* cache the size, this loop grows the worklist.
01111   for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
01112     // Bail out the moment we cross the threshold. This means we'll under-count
01113     // the cost, but only when undercounting doesn't matter.
01114     if (Cost > (Threshold + VectorBonus))
01115       break;
01116 
01117     BasicBlock *BB = BBWorklist[Idx];
01118     if (BB->empty())
01119       continue;
01120 
01121     // Disallow inlining a blockaddress. A blockaddress only has defined
01122     // behavior for an indirect branch in the same function, and we do not
01123     // currently support inlining indirect branches. But, the inliner may not
01124     // see an indirect branch that ends up being dead code at a particular call
01125     // site. If the blockaddress escapes the function, e.g., via a global
01126     // variable, inlining may lead to an invalid cross-function reference.
01127     if (BB->hasAddressTaken())
01128       return false;
01129 
01130     // Analyze the cost of this block. If we blow through the threshold, this
01131     // returns false, and we can bail on out.
01132     if (!analyzeBlock(BB)) {
01133       if (IsRecursiveCall || ExposesReturnsTwice || HasDynamicAlloca ||
01134           HasIndirectBr)
01135         return false;
01136 
01137       // If the caller is a recursive function then we don't want to inline
01138       // functions which allocate a lot of stack space because it would increase
01139       // the caller stack usage dramatically.
01140       if (IsCallerRecursive &&
01141           AllocatedSize > InlineConstants::TotalAllocaSizeRecursiveCaller)
01142         return false;
01143 
01144       break;
01145     }
01146 
01147     TerminatorInst *TI = BB->getTerminator();
01148 
01149     // Add in the live successors by first checking whether we have terminator
01150     // that may be simplified based on the values simplified by this call.
01151     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
01152       if (BI->isConditional()) {
01153         Value *Cond = BI->getCondition();
01154         if (ConstantInt *SimpleCond
01155               = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
01156           BBWorklist.insert(BI->getSuccessor(SimpleCond->isZero() ? 1 : 0));
01157           continue;
01158         }
01159       }
01160     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
01161       Value *Cond = SI->getCondition();
01162       if (ConstantInt *SimpleCond
01163             = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
01164         BBWorklist.insert(SI->findCaseValue(SimpleCond).getCaseSuccessor());
01165         continue;
01166       }
01167     }
01168 
01169     // If we're unable to select a particular successor, just count all of
01170     // them.
01171     for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize;
01172          ++TIdx)
01173       BBWorklist.insert(TI->getSuccessor(TIdx));
01174 
01175     // If we had any successors at this point, than post-inlining is likely to
01176     // have them as well. Note that we assume any basic blocks which existed
01177     // due to branches or switches which folded above will also fold after
01178     // inlining.
01179     if (SingleBB && TI->getNumSuccessors() > 1) {
01180       // Take off the bonus we applied to the threshold.
01181       Threshold -= SingleBBBonus;
01182       SingleBB = false;
01183     }
01184   }
01185 
01186   // If this is a noduplicate call, we can still inline as long as
01187   // inlining this would cause the removal of the caller (so the instruction
01188   // is not actually duplicated, just moved).
01189   if (!OnlyOneCallAndLocalLinkage && ContainsNoDuplicateCall)
01190     return false;
01191 
01192   Threshold += VectorBonus;
01193 
01194   return Cost < Threshold;
01195 }
01196 
01197 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
01198 /// \brief Dump stats about this call's analysis.
01199 void CallAnalyzer::dump() {
01200 #define DEBUG_PRINT_STAT(x) dbgs() << "      " #x ": " << x << "\n"
01201   DEBUG_PRINT_STAT(NumConstantArgs);
01202   DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
01203   DEBUG_PRINT_STAT(NumAllocaArgs);
01204   DEBUG_PRINT_STAT(NumConstantPtrCmps);
01205   DEBUG_PRINT_STAT(NumConstantPtrDiffs);
01206   DEBUG_PRINT_STAT(NumInstructionsSimplified);
01207   DEBUG_PRINT_STAT(SROACostSavings);
01208   DEBUG_PRINT_STAT(SROACostSavingsLost);
01209   DEBUG_PRINT_STAT(ContainsNoDuplicateCall);
01210   DEBUG_PRINT_STAT(Cost);
01211   DEBUG_PRINT_STAT(Threshold);
01212   DEBUG_PRINT_STAT(VectorBonus);
01213 #undef DEBUG_PRINT_STAT
01214 }
01215 #endif
01216 
01217 INITIALIZE_PASS_BEGIN(InlineCostAnalysis, "inline-cost", "Inline Cost Analysis",
01218                       true, true)
01219 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
01220 INITIALIZE_PASS_END(InlineCostAnalysis, "inline-cost", "Inline Cost Analysis",
01221                     true, true)
01222 
01223 char InlineCostAnalysis::ID = 0;
01224 
01225 InlineCostAnalysis::InlineCostAnalysis() : CallGraphSCCPass(ID) {}
01226 
01227 InlineCostAnalysis::~InlineCostAnalysis() {}
01228 
01229 void InlineCostAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
01230   AU.setPreservesAll();
01231   AU.addRequired<TargetTransformInfo>();
01232   CallGraphSCCPass::getAnalysisUsage(AU);
01233 }
01234 
01235 bool InlineCostAnalysis::runOnSCC(CallGraphSCC &SCC) {
01236   TTI = &getAnalysis<TargetTransformInfo>();
01237   return false;
01238 }
01239 
01240 InlineCost InlineCostAnalysis::getInlineCost(CallSite CS, int Threshold) {
01241   return getInlineCost(CS, CS.getCalledFunction(), Threshold);
01242 }
01243 
01244 /// \brief Test that two functions either have or have not the given attribute
01245 ///        at the same time.
01246 static bool attributeMatches(Function *F1, Function *F2,
01247                              Attribute::AttrKind Attr) {
01248   return F1->hasFnAttribute(Attr) == F2->hasFnAttribute(Attr);
01249 }
01250 
01251 /// \brief Test that there are no attribute conflicts between Caller and Callee
01252 ///        that prevent inlining.
01253 static bool functionsHaveCompatibleAttributes(Function *Caller,
01254                                               Function *Callee) {
01255   return attributeMatches(Caller, Callee, Attribute::SanitizeAddress) &&
01256          attributeMatches(Caller, Callee, Attribute::SanitizeMemory) &&
01257          attributeMatches(Caller, Callee, Attribute::SanitizeThread);
01258 }
01259 
01260 InlineCost InlineCostAnalysis::getInlineCost(CallSite CS, Function *Callee,
01261                                              int Threshold) {
01262   // Cannot inline indirect calls.
01263   if (!Callee)
01264     return llvm::InlineCost::getNever();
01265 
01266   // Calls to functions with always-inline attributes should be inlined
01267   // whenever possible.
01268   if (CS.hasFnAttr(Attribute::AlwaysInline)) {
01269     if (isInlineViable(*Callee))
01270       return llvm::InlineCost::getAlways();
01271     return llvm::InlineCost::getNever();
01272   }
01273 
01274   // Never inline functions with conflicting attributes (unless callee has
01275   // always-inline attribute).
01276   if (!functionsHaveCompatibleAttributes(CS.getCaller(), Callee))
01277     return llvm::InlineCost::getNever();
01278 
01279   // Don't inline this call if the caller has the optnone attribute.
01280   if (CS.getCaller()->hasFnAttribute(Attribute::OptimizeNone))
01281     return llvm::InlineCost::getNever();
01282 
01283   // Don't inline functions which can be redefined at link-time to mean
01284   // something else.  Don't inline functions marked noinline or call sites
01285   // marked noinline.
01286   if (Callee->mayBeOverridden() ||
01287       Callee->hasFnAttribute(Attribute::NoInline) || CS.isNoInline())
01288     return llvm::InlineCost::getNever();
01289 
01290   DEBUG(llvm::dbgs() << "      Analyzing call of " << Callee->getName()
01291         << "...\n");
01292 
01293   CallAnalyzer CA(Callee->getDataLayout(), *TTI, *Callee, Threshold);
01294   bool ShouldInline = CA.analyzeCall(CS);
01295 
01296   DEBUG(CA.dump());
01297 
01298   // Check if there was a reason to force inlining or no inlining.
01299   if (!ShouldInline && CA.getCost() < CA.getThreshold())
01300     return InlineCost::getNever();
01301   if (ShouldInline && CA.getCost() >= CA.getThreshold())
01302     return InlineCost::getAlways();
01303 
01304   return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());
01305 }
01306 
01307 bool InlineCostAnalysis::isInlineViable(Function &F) {
01308   bool ReturnsTwice =
01309     F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
01310                                    Attribute::ReturnsTwice);
01311   for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
01312     // Disallow inlining of functions which contain indirect branches or
01313     // blockaddresses.
01314     if (isa<IndirectBrInst>(BI->getTerminator()) || BI->hasAddressTaken())
01315       return false;
01316 
01317     for (BasicBlock::iterator II = BI->begin(), IE = BI->end(); II != IE;
01318          ++II) {
01319       CallSite CS(II);
01320       if (!CS)
01321         continue;
01322 
01323       // Disallow recursive calls.
01324       if (&F == CS.getCalledFunction())
01325         return false;
01326 
01327       // Disallow calls which expose returns-twice to a function not previously
01328       // attributed as such.
01329       if (!ReturnsTwice && CS.isCall() &&
01330           cast<CallInst>(CS.getInstruction())->canReturnTwice())
01331         return false;
01332     }
01333   }
01334 
01335   return true;
01336 }