1 //===- InlineCost.cpp - Cost analysis for inliner -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements inline cost analysis.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "inline-cost"
15 #include "llvm/Analysis/InlineCost.h"
16 #include "llvm/Analysis/ConstantFolding.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/Support/CallSite.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/InstVisitor.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/IntrinsicInst.h"
25 #include "llvm/Operator.h"
26 #include "llvm/GlobalAlias.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SetVector.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/Statistic.h"
36 STATISTIC(NumCallsAnalyzed, "Number of call sites analyzed");
40 class CallAnalyzer : public InstVisitor<CallAnalyzer, bool> {
41 typedef InstVisitor<CallAnalyzer, bool> Base;
42 friend class InstVisitor<CallAnalyzer, bool>;
44 // TargetData if available, or null.
45 const TargetData *const TD;
47 // The called function.
52 const bool AlwaysInline;
55 bool ExposesReturnsTwice;
56 bool HasDynamicAlloca;
57 unsigned NumInstructions, NumVectorInstructions;
58 int FiftyPercentVectorBonus, TenPercentVectorBonus;
61 // While we walk the potentially-inlined instructions, we build up and
62 // maintain a mapping of simplified values specific to this callsite. The
63 // idea is to propagate any special information we have about arguments to
64 // this call through the inlinable section of the function, and account for
65 // likely simplifications post-inlining. The most important aspect we track
66 // is CFG altering simplifications -- when we prove a basic block dead, that
67 // can cause dramatic shifts in the cost of inlining a function.
68 DenseMap<Value *, Constant *> SimplifiedValues;
70 // Keep track of the values which map back (through function arguments) to
71 // allocas on the caller stack which could be simplified through SROA.
72 DenseMap<Value *, Value *> SROAArgValues;
74 // The mapping of caller Alloca values to their accumulated cost savings. If
75 // we have to disable SROA for one of the allocas, this tells us how much
76 // cost must be added.
77 DenseMap<Value *, int> SROAArgCosts;
79 // Keep track of values which map to a pointer base and constant offset.
80 DenseMap<Value *, std::pair<Value *, APInt> > ConstantOffsetPtrs;
82 // Custom simplification helper routines.
83 bool isAllocaDerivedArg(Value *V);
84 bool lookupSROAArgAndCost(Value *V, Value *&Arg,
85 DenseMap<Value *, int>::iterator &CostIt);
86 void disableSROA(DenseMap<Value *, int>::iterator CostIt);
87 void disableSROA(Value *V);
88 void accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
90 bool handleSROACandidate(bool IsSROAValid,
91 DenseMap<Value *, int>::iterator CostIt,
93 bool isGEPOffsetConstant(GetElementPtrInst &GEP);
94 bool accumulateGEPOffset(GEPOperator &GEP, APInt &Offset);
95 ConstantInt *stripAndComputeInBoundsConstantOffsets(Value *&V);
97 // Custom analysis routines.
98 bool analyzeBlock(BasicBlock *BB);
100 // Disable several entry points to the visitor so we don't accidentally use
101 // them by declaring but not defining them here.
102 void visit(Module *); void visit(Module &);
103 void visit(Function *); void visit(Function &);
104 void visit(BasicBlock *); void visit(BasicBlock &);
106 // Provide base case for our instruction visit.
107 bool visitInstruction(Instruction &I);
109 // Our visit overrides.
110 bool visitAlloca(AllocaInst &I);
111 bool visitPHI(PHINode &I);
112 bool visitGetElementPtr(GetElementPtrInst &I);
113 bool visitBitCast(BitCastInst &I);
114 bool visitPtrToInt(PtrToIntInst &I);
115 bool visitIntToPtr(IntToPtrInst &I);
116 bool visitCastInst(CastInst &I);
117 bool visitUnaryInstruction(UnaryInstruction &I);
118 bool visitICmp(ICmpInst &I);
119 bool visitSub(BinaryOperator &I);
120 bool visitBinaryOperator(BinaryOperator &I);
121 bool visitLoad(LoadInst &I);
122 bool visitStore(StoreInst &I);
123 bool visitCallSite(CallSite CS);
126 CallAnalyzer(const TargetData *TD, Function &Callee, int Threshold)
127 : TD(TD), F(Callee), Threshold(Threshold), Cost(0),
128 AlwaysInline(F.hasFnAttr(Attribute::AlwaysInline)),
129 IsRecursive(false), ExposesReturnsTwice(false), HasDynamicAlloca(false),
130 NumInstructions(0), NumVectorInstructions(0),
131 FiftyPercentVectorBonus(0), TenPercentVectorBonus(0), VectorBonus(0),
132 NumConstantArgs(0), NumConstantOffsetPtrArgs(0), NumAllocaArgs(0),
133 NumConstantPtrCmps(0), NumConstantPtrDiffs(0),
134 NumInstructionsSimplified(0), SROACostSavings(0), SROACostSavingsLost(0) {
137 bool analyzeCall(CallSite CS);
139 int getThreshold() { return Threshold; }
140 int getCost() { return Cost; }
141 bool isAlwaysInline() { return AlwaysInline; }
143 // Keep a bunch of stats about the cost savings found so we can print them
144 // out when debugging.
145 unsigned NumConstantArgs;
146 unsigned NumConstantOffsetPtrArgs;
147 unsigned NumAllocaArgs;
148 unsigned NumConstantPtrCmps;
149 unsigned NumConstantPtrDiffs;
150 unsigned NumInstructionsSimplified;
151 unsigned SROACostSavings;
152 unsigned SROACostSavingsLost;
159 /// \brief Test whether the given value is an Alloca-derived function argument.
160 bool CallAnalyzer::isAllocaDerivedArg(Value *V) {
161 return SROAArgValues.count(V);
164 /// \brief Lookup the SROA-candidate argument and cost iterator which V maps to.
165 /// Returns false if V does not map to a SROA-candidate.
166 bool CallAnalyzer::lookupSROAArgAndCost(
167 Value *V, Value *&Arg, DenseMap<Value *, int>::iterator &CostIt) {
168 if (SROAArgValues.empty() || SROAArgCosts.empty())
171 DenseMap<Value *, Value *>::iterator ArgIt = SROAArgValues.find(V);
172 if (ArgIt == SROAArgValues.end())
176 CostIt = SROAArgCosts.find(Arg);
177 return CostIt != SROAArgCosts.end();
180 /// \brief Disable SROA for the candidate marked by this cost iterator.
182 /// This marks the candidate as no longer viable for SROA, and adds the cost
183 /// savings associated with it back into the inline cost measurement.
184 void CallAnalyzer::disableSROA(DenseMap<Value *, int>::iterator CostIt) {
185 // If we're no longer able to perform SROA we need to undo its cost savings
186 // and prevent subsequent analysis.
187 Cost += CostIt->second;
188 SROACostSavings -= CostIt->second;
189 SROACostSavingsLost += CostIt->second;
190 SROAArgCosts.erase(CostIt);
193 /// \brief If 'V' maps to a SROA candidate, disable SROA for it.
194 void CallAnalyzer::disableSROA(Value *V) {
196 DenseMap<Value *, int>::iterator CostIt;
197 if (lookupSROAArgAndCost(V, SROAArg, CostIt))
201 /// \brief Accumulate the given cost for a particular SROA candidate.
202 void CallAnalyzer::accumulateSROACost(DenseMap<Value *, int>::iterator CostIt,
203 int InstructionCost) {
204 CostIt->second += InstructionCost;
205 SROACostSavings += InstructionCost;
208 /// \brief Helper for the common pattern of handling a SROA candidate.
209 /// Either accumulates the cost savings if the SROA remains valid, or disables
210 /// SROA for the candidate.
211 bool CallAnalyzer::handleSROACandidate(bool IsSROAValid,
212 DenseMap<Value *, int>::iterator CostIt,
213 int InstructionCost) {
215 accumulateSROACost(CostIt, InstructionCost);
223 /// \brief Check whether a GEP's indices are all constant.
225 /// Respects any simplified values known during the analysis of this callsite.
226 bool CallAnalyzer::isGEPOffsetConstant(GetElementPtrInst &GEP) {
227 for (User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end(); I != E; ++I)
228 if (!isa<Constant>(*I) && !SimplifiedValues.lookup(*I))
234 /// \brief Accumulate a constant GEP offset into an APInt if possible.
236 /// Returns false if unable to compute the offset for any reason. Respects any
237 /// simplified values known during the analysis of this callsite.
238 bool CallAnalyzer::accumulateGEPOffset(GEPOperator &GEP, APInt &Offset) {
242 unsigned IntPtrWidth = TD->getPointerSizeInBits();
243 assert(IntPtrWidth == Offset.getBitWidth());
245 for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
247 ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
249 if (Constant *SimpleOp = SimplifiedValues.lookup(GTI.getOperand()))
250 OpC = dyn_cast<ConstantInt>(SimpleOp);
253 if (OpC->isZero()) continue;
255 // Handle a struct index, which adds its field offset to the pointer.
256 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
257 unsigned ElementIdx = OpC->getZExtValue();
258 const StructLayout *SL = TD->getStructLayout(STy);
259 Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
263 APInt TypeSize(IntPtrWidth, TD->getTypeAllocSize(GTI.getIndexedType()));
264 Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
269 bool CallAnalyzer::visitAlloca(AllocaInst &I) {
270 // FIXME: Check whether inlining will turn a dynamic alloca into a static
271 // alloca, and handle that case.
273 // We will happily inline static alloca instructions or dynamic alloca
274 // instructions in always-inline situations.
275 if (AlwaysInline || I.isStaticAlloca())
276 return Base::visitAlloca(I);
278 // FIXME: This is overly conservative. Dynamic allocas are inefficient for
279 // a variety of reasons, and so we would like to not inline them into
280 // functions which don't currently have a dynamic alloca. This simply
281 // disables inlining altogether in the presence of a dynamic alloca.
282 HasDynamicAlloca = true;
286 bool CallAnalyzer::visitPHI(PHINode &I) {
287 // FIXME: We should potentially be tracking values through phi nodes,
288 // especially when they collapse to a single value due to deleted CFG edges
291 // FIXME: We need to propagate SROA *disabling* through phi nodes, even
292 // though we don't want to propagate it's bonuses. The idea is to disable
293 // SROA if it *might* be used in an inappropriate manner.
295 // Phi nodes are always zero-cost.
299 bool CallAnalyzer::visitGetElementPtr(GetElementPtrInst &I) {
301 DenseMap<Value *, int>::iterator CostIt;
302 bool SROACandidate = lookupSROAArgAndCost(I.getPointerOperand(),
305 // Try to fold GEPs of constant-offset call site argument pointers. This
306 // requires target data and inbounds GEPs.
307 if (TD && I.isInBounds()) {
308 // Check if we have a base + offset for the pointer.
309 Value *Ptr = I.getPointerOperand();
310 std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Ptr);
311 if (BaseAndOffset.first) {
312 // Check if the offset of this GEP is constant, and if so accumulate it
314 if (!accumulateGEPOffset(cast<GEPOperator>(I), BaseAndOffset.second)) {
315 // Non-constant GEPs aren't folded, and disable SROA.
321 // Add the result as a new mapping to Base + Offset.
322 ConstantOffsetPtrs[&I] = BaseAndOffset;
324 // Also handle SROA candidates here, we already know that the GEP is
325 // all-constant indexed.
327 SROAArgValues[&I] = SROAArg;
333 if (isGEPOffsetConstant(I)) {
335 SROAArgValues[&I] = SROAArg;
337 // Constant GEPs are modeled as free.
341 // Variable GEPs will require math and will disable SROA.
347 bool CallAnalyzer::visitBitCast(BitCastInst &I) {
348 // Propagate constants through bitcasts.
349 if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
350 if (Constant *C = ConstantExpr::getBitCast(COp, I.getType())) {
351 SimplifiedValues[&I] = C;
355 // Track base/offsets through casts
356 std::pair<Value *, APInt> BaseAndOffset
357 = ConstantOffsetPtrs.lookup(I.getOperand(0));
358 // Casts don't change the offset, just wrap it up.
359 if (BaseAndOffset.first)
360 ConstantOffsetPtrs[&I] = BaseAndOffset;
362 // Also look for SROA candidates here.
364 DenseMap<Value *, int>::iterator CostIt;
365 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
366 SROAArgValues[&I] = SROAArg;
368 // Bitcasts are always zero cost.
372 bool CallAnalyzer::visitPtrToInt(PtrToIntInst &I) {
373 // Propagate constants through ptrtoint.
374 if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
375 if (Constant *C = ConstantExpr::getPtrToInt(COp, I.getType())) {
376 SimplifiedValues[&I] = C;
380 // Track base/offset pairs when converted to a plain integer provided the
381 // integer is large enough to represent the pointer.
382 unsigned IntegerSize = I.getType()->getScalarSizeInBits();
383 if (TD && IntegerSize >= TD->getPointerSizeInBits()) {
384 std::pair<Value *, APInt> BaseAndOffset
385 = ConstantOffsetPtrs.lookup(I.getOperand(0));
386 if (BaseAndOffset.first)
387 ConstantOffsetPtrs[&I] = BaseAndOffset;
390 // This is really weird. Technically, ptrtoint will disable SROA. However,
391 // unless that ptrtoint is *used* somewhere in the live basic blocks after
392 // inlining, it will be nuked, and SROA should proceed. All of the uses which
393 // would block SROA would also block SROA if applied directly to a pointer,
394 // and so we can just add the integer in here. The only places where SROA is
395 // preserved either cannot fire on an integer, or won't in-and-of themselves
396 // disable SROA (ext) w/o some later use that we would see and disable.
398 DenseMap<Value *, int>::iterator CostIt;
399 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt))
400 SROAArgValues[&I] = SROAArg;
402 return isInstructionFree(&I, TD);
405 bool CallAnalyzer::visitIntToPtr(IntToPtrInst &I) {
406 // Propagate constants through ptrtoint.
407 if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
408 if (Constant *C = ConstantExpr::getIntToPtr(COp, I.getType())) {
409 SimplifiedValues[&I] = C;
413 // Track base/offset pairs when round-tripped through a pointer without
414 // modifications provided the integer is not too large.
415 Value *Op = I.getOperand(0);
416 unsigned IntegerSize = Op->getType()->getScalarSizeInBits();
417 if (TD && IntegerSize <= TD->getPointerSizeInBits()) {
418 std::pair<Value *, APInt> BaseAndOffset = ConstantOffsetPtrs.lookup(Op);
419 if (BaseAndOffset.first)
420 ConstantOffsetPtrs[&I] = BaseAndOffset;
423 // "Propagate" SROA here in the same manner as we do for ptrtoint above.
425 DenseMap<Value *, int>::iterator CostIt;
426 if (lookupSROAArgAndCost(Op, SROAArg, CostIt))
427 SROAArgValues[&I] = SROAArg;
429 return isInstructionFree(&I, TD);
432 bool CallAnalyzer::visitCastInst(CastInst &I) {
433 // Propagate constants through ptrtoint.
434 if (Constant *COp = dyn_cast<Constant>(I.getOperand(0)))
435 if (Constant *C = ConstantExpr::getCast(I.getOpcode(), COp, I.getType())) {
436 SimplifiedValues[&I] = C;
440 // Disable SROA in the face of arbitrary casts we don't whitelist elsewhere.
441 disableSROA(I.getOperand(0));
443 return isInstructionFree(&I, TD);
446 bool CallAnalyzer::visitUnaryInstruction(UnaryInstruction &I) {
447 Value *Operand = I.getOperand(0);
448 Constant *Ops[1] = { dyn_cast<Constant>(Operand) };
449 if (Ops[0] || (Ops[0] = SimplifiedValues.lookup(Operand)))
450 if (Constant *C = ConstantFoldInstOperands(I.getOpcode(), I.getType(),
452 SimplifiedValues[&I] = C;
456 // Disable any SROA on the argument to arbitrary unary operators.
457 disableSROA(Operand);
462 bool CallAnalyzer::visitICmp(ICmpInst &I) {
463 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
464 // First try to handle simplified comparisons.
465 if (!isa<Constant>(LHS))
466 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
468 if (!isa<Constant>(RHS))
469 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
471 if (Constant *CLHS = dyn_cast<Constant>(LHS))
472 if (Constant *CRHS = dyn_cast<Constant>(RHS))
473 if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
474 SimplifiedValues[&I] = C;
478 // Otherwise look for a comparison between constant offset pointers with
480 Value *LHSBase, *RHSBase;
481 APInt LHSOffset, RHSOffset;
482 llvm::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
484 llvm::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
485 if (RHSBase && LHSBase == RHSBase) {
486 // We have common bases, fold the icmp to a constant based on the
488 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
489 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
490 if (Constant *C = ConstantExpr::getICmp(I.getPredicate(), CLHS, CRHS)) {
491 SimplifiedValues[&I] = C;
492 ++NumConstantPtrCmps;
498 // If the comparison is an equality comparison with null, we can simplify it
499 // for any alloca-derived argument.
500 if (I.isEquality() && isa<ConstantPointerNull>(I.getOperand(1)))
501 if (isAllocaDerivedArg(I.getOperand(0))) {
502 // We can actually predict the result of comparisons between an
503 // alloca-derived value and null. Note that this fires regardless of
505 bool IsNotEqual = I.getPredicate() == CmpInst::ICMP_NE;
506 SimplifiedValues[&I] = IsNotEqual ? ConstantInt::getTrue(I.getType())
507 : ConstantInt::getFalse(I.getType());
511 // Finally check for SROA candidates in comparisons.
513 DenseMap<Value *, int>::iterator CostIt;
514 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
515 if (isa<ConstantPointerNull>(I.getOperand(1))) {
516 accumulateSROACost(CostIt, InlineConstants::InstrCost);
526 bool CallAnalyzer::visitSub(BinaryOperator &I) {
527 // Try to handle a special case: we can fold computing the difference of two
528 // constant-related pointers.
529 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
530 Value *LHSBase, *RHSBase;
531 APInt LHSOffset, RHSOffset;
532 llvm::tie(LHSBase, LHSOffset) = ConstantOffsetPtrs.lookup(LHS);
534 llvm::tie(RHSBase, RHSOffset) = ConstantOffsetPtrs.lookup(RHS);
535 if (RHSBase && LHSBase == RHSBase) {
536 // We have common bases, fold the subtract to a constant based on the
538 Constant *CLHS = ConstantInt::get(LHS->getContext(), LHSOffset);
539 Constant *CRHS = ConstantInt::get(RHS->getContext(), RHSOffset);
540 if (Constant *C = ConstantExpr::getSub(CLHS, CRHS)) {
541 SimplifiedValues[&I] = C;
542 ++NumConstantPtrDiffs;
548 // Otherwise, fall back to the generic logic for simplifying and handling
550 return Base::visitSub(I);
553 bool CallAnalyzer::visitBinaryOperator(BinaryOperator &I) {
554 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
555 if (!isa<Constant>(LHS))
556 if (Constant *SimpleLHS = SimplifiedValues.lookup(LHS))
558 if (!isa<Constant>(RHS))
559 if (Constant *SimpleRHS = SimplifiedValues.lookup(RHS))
561 Value *SimpleV = SimplifyBinOp(I.getOpcode(), LHS, RHS, TD);
562 if (Constant *C = dyn_cast_or_null<Constant>(SimpleV)) {
563 SimplifiedValues[&I] = C;
567 // Disable any SROA on arguments to arbitrary, unsimplified binary operators.
574 bool CallAnalyzer::visitLoad(LoadInst &I) {
576 DenseMap<Value *, int>::iterator CostIt;
577 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
579 accumulateSROACost(CostIt, InlineConstants::InstrCost);
589 bool CallAnalyzer::visitStore(StoreInst &I) {
591 DenseMap<Value *, int>::iterator CostIt;
592 if (lookupSROAArgAndCost(I.getOperand(0), SROAArg, CostIt)) {
594 accumulateSROACost(CostIt, InlineConstants::InstrCost);
604 bool CallAnalyzer::visitCallSite(CallSite CS) {
605 if (CS.isCall() && cast<CallInst>(CS.getInstruction())->canReturnTwice() &&
606 !F.hasFnAttr(Attribute::ReturnsTwice)) {
607 // This aborts the entire analysis.
608 ExposesReturnsTwice = true;
612 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
613 switch (II->getIntrinsicID()) {
615 return Base::visitCallSite(CS);
617 case Intrinsic::memset:
618 case Intrinsic::memcpy:
619 case Intrinsic::memmove:
620 // SROA can usually chew through these intrinsics, but they aren't free.
625 if (Function *F = CS.getCalledFunction()) {
626 if (F == CS.getInstruction()->getParent()->getParent()) {
627 // This flag will fully abort the analysis, so don't bother with anything
633 if (!callIsSmall(CS)) {
634 // We account for the average 1 instruction per call argument setup
636 Cost += CS.arg_size() * InlineConstants::InstrCost;
638 // Everything other than inline ASM will also have a significant cost
639 // merely from making the call.
640 if (!isa<InlineAsm>(CS.getCalledValue()))
641 Cost += InlineConstants::CallPenalty;
644 return Base::visitCallSite(CS);
647 // Otherwise we're in a very special case -- an indirect function call. See
648 // if we can be particularly clever about this.
649 Value *Callee = CS.getCalledValue();
651 // First, pay the price of the argument setup. We account for the average
652 // 1 instruction per call argument setup here.
653 Cost += CS.arg_size() * InlineConstants::InstrCost;
655 // Next, check if this happens to be an indirect function call to a known
656 // function in this inline context. If not, we've done all we can.
657 Function *F = dyn_cast_or_null<Function>(SimplifiedValues.lookup(Callee));
659 return Base::visitCallSite(CS);
661 // If we have a constant that we are calling as a function, we can peer
662 // through it and see the function target. This happens not infrequently
663 // during devirtualization and so we want to give it a hefty bonus for
664 // inlining, but cap that bonus in the event that inlining wouldn't pan
665 // out. Pretend to inline the function, with a custom threshold.
666 CallAnalyzer CA(TD, *F, InlineConstants::IndirectCallThreshold);
667 if (CA.analyzeCall(CS)) {
668 // We were able to inline the indirect call! Subtract the cost from the
669 // bonus we want to apply, but don't go below zero.
670 Cost -= std::max(0, InlineConstants::IndirectCallThreshold - CA.getCost());
673 return Base::visitCallSite(CS);
676 bool CallAnalyzer::visitInstruction(Instruction &I) {
677 // Some instructions are free. All of the free intrinsics can also be
678 // handled by SROA, etc.
679 if (isInstructionFree(&I, TD))
682 // We found something we don't understand or can't handle. Mark any SROA-able
683 // values in the operand list as no longer viable.
684 for (User::op_iterator OI = I.op_begin(), OE = I.op_end(); OI != OE; ++OI)
691 /// \brief Analyze a basic block for its contribution to the inline cost.
693 /// This method walks the analyzer over every instruction in the given basic
694 /// block and accounts for their cost during inlining at this callsite. It
695 /// aborts early if the threshold has been exceeded or an impossible to inline
696 /// construct has been detected. It returns false if inlining is no longer
697 /// viable, and true if inlining remains viable.
698 bool CallAnalyzer::analyzeBlock(BasicBlock *BB) {
699 for (BasicBlock::iterator I = BB->begin(), E = llvm::prior(BB->end());
702 if (isa<ExtractElementInst>(I) || I->getType()->isVectorTy())
703 ++NumVectorInstructions;
705 // If the instruction simplified to a constant, there is no cost to this
706 // instruction. Visit the instructions using our InstVisitor to account for
707 // all of the per-instruction logic. The visit tree returns true if we
708 // consumed the instruction in any way, and false if the instruction's base
709 // cost should count against inlining.
711 ++NumInstructionsSimplified;
713 Cost += InlineConstants::InstrCost;
715 // If the visit this instruction detected an uninlinable pattern, abort.
716 if (IsRecursive || ExposesReturnsTwice || HasDynamicAlloca)
719 if (NumVectorInstructions > NumInstructions/2)
720 VectorBonus = FiftyPercentVectorBonus;
721 else if (NumVectorInstructions > NumInstructions/10)
722 VectorBonus = TenPercentVectorBonus;
726 // Check if we've past the threshold so we don't spin in huge basic
727 // blocks that will never inline.
728 if (!AlwaysInline && Cost > (Threshold + VectorBonus))
735 /// \brief Compute the base pointer and cumulative constant offsets for V.
737 /// This strips all constant offsets off of V, leaving it the base pointer, and
738 /// accumulates the total constant offset applied in the returned constant. It
739 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
740 /// no constant offsets applied.
741 ConstantInt *CallAnalyzer::stripAndComputeInBoundsConstantOffsets(Value *&V) {
742 if (!TD || !V->getType()->isPointerTy())
745 unsigned IntPtrWidth = TD->getPointerSizeInBits();
746 APInt Offset = APInt::getNullValue(IntPtrWidth);
748 // Even though we don't look through PHI nodes, we could be called on an
749 // instruction in an unreachable block, which may be on a cycle.
750 SmallPtrSet<Value *, 4> Visited;
753 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
754 if (!GEP->isInBounds() || !accumulateGEPOffset(*GEP, Offset))
756 V = GEP->getPointerOperand();
757 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
758 V = cast<Operator>(V)->getOperand(0);
759 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
760 if (GA->mayBeOverridden())
762 V = GA->getAliasee();
766 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
767 } while (Visited.insert(V));
769 Type *IntPtrTy = TD->getIntPtrType(V->getContext());
770 return cast<ConstantInt>(ConstantInt::get(IntPtrTy, Offset));
773 /// \brief Analyze a call site for potential inlining.
775 /// Returns true if inlining this call is viable, and false if it is not
776 /// viable. It computes the cost and adjusts the threshold based on numerous
777 /// factors and heuristics. If this method returns false but the computed cost
778 /// is below the computed threshold, then inlining was forcibly disabled by
779 /// some artifact of the rountine.
780 bool CallAnalyzer::analyzeCall(CallSite CS) {
783 // Track whether the post-inlining function would have more than one basic
784 // block. A single basic block is often intended for inlining. Balloon the
785 // threshold by 50% until we pass the single-BB phase.
786 bool SingleBB = true;
787 int SingleBBBonus = Threshold / 2;
788 Threshold += SingleBBBonus;
790 // Unless we are always-inlining, perform some tweaks to the cost and
791 // threshold based on the direct callsite information.
793 // We want to more aggressively inline vector-dense kernels, so up the
794 // threshold, and we'll lower it if the % of vector instructions gets too
796 assert(NumInstructions == 0);
797 assert(NumVectorInstructions == 0);
798 FiftyPercentVectorBonus = Threshold;
799 TenPercentVectorBonus = Threshold / 2;
801 // Give out bonuses per argument, as the instructions setting them up will
802 // be gone after inlining.
803 for (unsigned I = 0, E = CS.arg_size(); I != E; ++I) {
804 if (TD && CS.isByValArgument(I)) {
805 // We approximate the number of loads and stores needed by dividing the
806 // size of the byval type by the target's pointer size.
807 PointerType *PTy = cast<PointerType>(CS.getArgument(I)->getType());
808 unsigned TypeSize = TD->getTypeSizeInBits(PTy->getElementType());
809 unsigned PointerSize = TD->getPointerSizeInBits();
811 unsigned NumStores = (TypeSize + PointerSize - 1) / PointerSize;
813 // If it generates more than 8 stores it is likely to be expanded as an
814 // inline memcpy so we take that as an upper bound. Otherwise we assume
815 // one load and one store per word copied.
816 // FIXME: The maxStoresPerMemcpy setting from the target should be used
817 // here instead of a magic number of 8, but it's not available via
819 NumStores = std::min(NumStores, 8U);
821 Cost -= 2 * NumStores * InlineConstants::InstrCost;
823 // For non-byval arguments subtract off one instruction per call
825 Cost -= InlineConstants::InstrCost;
829 // If there is only one call of the function, and it has internal linkage,
830 // the cost of inlining it drops dramatically.
831 if (F.hasLocalLinkage() && F.hasOneUse() && &F == CS.getCalledFunction())
832 Cost += InlineConstants::LastCallToStaticBonus;
834 // If the instruction after the call, or if the normal destination of the
835 // invoke is an unreachable instruction, the function is noreturn. As such,
836 // there is little point in inlining this unless there is literally zero cost.
837 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
838 if (isa<UnreachableInst>(II->getNormalDest()->begin()))
840 } else if (isa<UnreachableInst>(++BasicBlock::iterator(CS.getInstruction())))
843 // If this function uses the coldcc calling convention, prefer not to inline
845 if (F.getCallingConv() == CallingConv::Cold)
846 Cost += InlineConstants::ColdccPenalty;
848 // Check if we're done. This can happen due to bonuses and penalties.
849 if (Cost > Threshold)
856 // Track whether we've seen a return instruction. The first return
857 // instruction is free, as at least one will usually disappear in inlining.
858 bool HasReturn = false;
860 // Populate our simplified values by mapping from function arguments to call
861 // arguments with known important simplifications.
862 CallSite::arg_iterator CAI = CS.arg_begin();
863 for (Function::arg_iterator FAI = F.arg_begin(), FAE = F.arg_end();
864 FAI != FAE; ++FAI, ++CAI) {
865 assert(CAI != CS.arg_end());
866 if (Constant *C = dyn_cast<Constant>(CAI))
867 SimplifiedValues[FAI] = C;
869 Value *PtrArg = *CAI;
870 if (ConstantInt *C = stripAndComputeInBoundsConstantOffsets(PtrArg)) {
871 ConstantOffsetPtrs[FAI] = std::make_pair(PtrArg, C->getValue());
873 // We can SROA any pointer arguments derived from alloca instructions.
874 if (isa<AllocaInst>(PtrArg)) {
875 SROAArgValues[FAI] = PtrArg;
876 SROAArgCosts[PtrArg] = 0;
880 NumConstantArgs = SimplifiedValues.size();
881 NumConstantOffsetPtrArgs = ConstantOffsetPtrs.size();
882 NumAllocaArgs = SROAArgValues.size();
884 // The worklist of live basic blocks in the callee *after* inlining. We avoid
885 // adding basic blocks of the callee which can be proven to be dead for this
886 // particular call site in order to get more accurate cost estimates. This
887 // requires a somewhat heavyweight iteration pattern: we need to walk the
888 // basic blocks in a breadth-first order as we insert live successors. To
889 // accomplish this, prioritizing for small iterations because we exit after
890 // crossing our threshold, we use a small-size optimized SetVector.
891 typedef SetVector<BasicBlock *, SmallVector<BasicBlock *, 16>,
892 SmallPtrSet<BasicBlock *, 16> > BBSetVector;
893 BBSetVector BBWorklist;
894 BBWorklist.insert(&F.getEntryBlock());
895 // Note that we *must not* cache the size, this loop grows the worklist.
896 for (unsigned Idx = 0; Idx != BBWorklist.size(); ++Idx) {
897 // Bail out the moment we cross the threshold. This means we'll under-count
898 // the cost, but only when undercounting doesn't matter.
899 if (!AlwaysInline && Cost > (Threshold + VectorBonus))
902 BasicBlock *BB = BBWorklist[Idx];
906 // Handle the terminator cost here where we can track returns and other
907 // function-wide constructs.
908 TerminatorInst *TI = BB->getTerminator();
910 // We never want to inline functions that contain an indirectbr. This is
911 // incorrect because all the blockaddress's (in static global initializers
912 // for example) would be referring to the original function, and this indirect
913 // jump would jump from the inlined copy of the function into the original
914 // function which is extremely undefined behavior.
915 // FIXME: This logic isn't really right; we can safely inline functions
916 // with indirectbr's as long as no other function or global references the
917 // blockaddress of a block within the current function. And as a QOI issue,
918 // if someone is using a blockaddress without an indirectbr, and that
919 // reference somehow ends up in another function or global, we probably
920 // don't want to inline this function.
921 if (isa<IndirectBrInst>(TI))
924 if (!HasReturn && isa<ReturnInst>(TI))
927 Cost += InlineConstants::InstrCost;
929 // Analyze the cost of this block. If we blow through the threshold, this
930 // returns false, and we can bail on out.
931 if (!analyzeBlock(BB)) {
932 if (IsRecursive || ExposesReturnsTwice || HasDynamicAlloca)
937 // Add in the live successors by first checking whether we have terminator
938 // that may be simplified based on the values simplified by this call.
939 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
940 if (BI->isConditional()) {
941 Value *Cond = BI->getCondition();
942 if (ConstantInt *SimpleCond
943 = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
944 BBWorklist.insert(BI->getSuccessor(SimpleCond->isZero() ? 1 : 0));
948 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
949 Value *Cond = SI->getCondition();
950 if (ConstantInt *SimpleCond
951 = dyn_cast_or_null<ConstantInt>(SimplifiedValues.lookup(Cond))) {
952 BBWorklist.insert(SI->findCaseValue(SimpleCond).getCaseSuccessor());
957 // If we're unable to select a particular successor, just count all of
959 for (unsigned TIdx = 0, TSize = TI->getNumSuccessors(); TIdx != TSize; ++TIdx)
960 BBWorklist.insert(TI->getSuccessor(TIdx));
962 // If we had any successors at this point, than post-inlining is likely to
963 // have them as well. Note that we assume any basic blocks which existed
964 // due to branches or switches which folded above will also fold after
966 if (SingleBB && TI->getNumSuccessors() > 1) {
967 // Take off the bonus we applied to the threshold.
968 Threshold -= SingleBBBonus;
973 Threshold += VectorBonus;
975 return AlwaysInline || Cost < Threshold;
978 /// \brief Dump stats about this call's analysis.
979 void CallAnalyzer::dump() {
980 #define DEBUG_PRINT_STAT(x) llvm::dbgs() << " " #x ": " << x << "\n"
981 DEBUG_PRINT_STAT(NumConstantArgs);
982 DEBUG_PRINT_STAT(NumConstantOffsetPtrArgs);
983 DEBUG_PRINT_STAT(NumAllocaArgs);
984 DEBUG_PRINT_STAT(NumConstantPtrCmps);
985 DEBUG_PRINT_STAT(NumConstantPtrDiffs);
986 DEBUG_PRINT_STAT(NumInstructionsSimplified);
987 DEBUG_PRINT_STAT(SROACostSavings);
988 DEBUG_PRINT_STAT(SROACostSavingsLost);
989 #undef DEBUG_PRINT_STAT
992 InlineCost InlineCostAnalyzer::getInlineCost(CallSite CS, int Threshold) {
993 return getInlineCost(CS, CS.getCalledFunction(), Threshold);
996 InlineCost InlineCostAnalyzer::getInlineCost(CallSite CS, Function *Callee,
998 // Don't inline functions which can be redefined at link-time to mean
999 // something else. Don't inline functions marked noinline or call sites
1001 if (!Callee || Callee->mayBeOverridden() ||
1002 Callee->hasFnAttr(Attribute::NoInline) || CS.isNoInline())
1003 return llvm::InlineCost::getNever();
1005 DEBUG(llvm::dbgs() << " Analyzing call of " << Callee->getName() << "...\n");
1007 CallAnalyzer CA(TD, *Callee, Threshold);
1008 bool ShouldInline = CA.analyzeCall(CS);
1012 // Check if there was a reason to force inlining or no inlining.
1013 if (!ShouldInline && CA.getCost() < CA.getThreshold())
1014 return InlineCost::getNever();
1015 if (ShouldInline && (CA.isAlwaysInline() ||
1016 CA.getCost() >= CA.getThreshold()))
1017 return InlineCost::getAlways();
1019 return llvm::InlineCost::get(CA.getCost(), CA.getThreshold());