Start removing the use of an ad-hoc 'never inline' set and instead
[oota-llvm.git] / lib / Analysis / InlineCost.cpp
1 //===- InlineCost.cpp - Cost analysis for inliner -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements inline cost analysis.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Analysis/InlineCost.h"
15 #include "llvm/Support/CallSite.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/IntrinsicInst.h"
18 #include "llvm/Target/TargetData.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20
21 using namespace llvm;
22
23 unsigned InlineCostAnalyzer::FunctionInfo::countCodeReductionForConstant(
24     const CodeMetrics &Metrics, Value *V) {
25   unsigned Reduction = 0;
26   SmallVector<Value *, 4> Worklist;
27   Worklist.push_back(V);
28   do {
29     Value *V = Worklist.pop_back_val();
30     for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
31       User *U = *UI;
32       if (isa<BranchInst>(U) || isa<SwitchInst>(U)) {
33         // We will be able to eliminate all but one of the successors.
34         const TerminatorInst &TI = cast<TerminatorInst>(*U);
35         const unsigned NumSucc = TI.getNumSuccessors();
36         unsigned Instrs = 0;
37         for (unsigned I = 0; I != NumSucc; ++I)
38           Instrs += Metrics.NumBBInsts.lookup(TI.getSuccessor(I));
39         // We don't know which blocks will be eliminated, so use the average size.
40         Reduction += InlineConstants::InstrCost*Instrs*(NumSucc-1)/NumSucc;
41         continue;
42       }
43
44       // Figure out if this instruction will be removed due to simple constant
45       // propagation.
46       Instruction &Inst = cast<Instruction>(*U);
47
48       // We can't constant propagate instructions which have effects or
49       // read memory.
50       //
51       // FIXME: It would be nice to capture the fact that a load from a
52       // pointer-to-constant-global is actually a *really* good thing to zap.
53       // Unfortunately, we don't know the pointer that may get propagated here,
54       // so we can't make this decision.
55       if (Inst.mayReadFromMemory() || Inst.mayHaveSideEffects() ||
56           isa<AllocaInst>(Inst))
57         continue;
58
59       bool AllOperandsConstant = true;
60       for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i)
61         if (!isa<Constant>(Inst.getOperand(i)) && Inst.getOperand(i) != V) {
62           AllOperandsConstant = false;
63           break;
64         }
65       if (!AllOperandsConstant)
66         continue;
67
68       // We will get to remove this instruction...
69       Reduction += InlineConstants::InstrCost;
70
71       // And any other instructions that use it which become constants
72       // themselves.
73       Worklist.push_back(&Inst);
74     }
75   } while (!Worklist.empty());
76   return Reduction;
77 }
78
79 static unsigned countCodeReductionForAllocaICmp(const CodeMetrics &Metrics,
80                                                 ICmpInst *ICI) {
81   unsigned Reduction = 0;
82
83   // Bail if this is comparing against a non-constant; there is nothing we can
84   // do there.
85   if (!isa<Constant>(ICI->getOperand(1)))
86     return Reduction;
87
88   // An icmp pred (alloca, C) becomes true if the predicate is true when
89   // equal and false otherwise.
90   bool Result = ICI->isTrueWhenEqual();
91
92   SmallVector<Instruction *, 4> Worklist;
93   Worklist.push_back(ICI);
94   do {
95     Instruction *U = Worklist.pop_back_val();
96     Reduction += InlineConstants::InstrCost;
97     for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
98          UI != UE; ++UI) {
99       Instruction *I = dyn_cast<Instruction>(*UI);
100       if (!I || I->mayHaveSideEffects()) continue;
101       if (I->getNumOperands() == 1)
102         Worklist.push_back(I);
103       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
104         // If BO produces the same value as U, then the other operand is
105         // irrelevant and we can put it into the Worklist to continue
106         // deleting dead instructions. If BO produces the same value as the
107         // other operand, we can delete BO but that's it.
108         if (Result == true) {
109           if (BO->getOpcode() == Instruction::Or)
110             Worklist.push_back(I);
111           if (BO->getOpcode() == Instruction::And)
112             Reduction += InlineConstants::InstrCost;
113         } else {
114           if (BO->getOpcode() == Instruction::Or ||
115               BO->getOpcode() == Instruction::Xor)
116             Reduction += InlineConstants::InstrCost;
117           if (BO->getOpcode() == Instruction::And)
118             Worklist.push_back(I);
119         }
120       }
121       if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
122         BasicBlock *BB = BI->getSuccessor(Result ? 0 : 1);
123         if (BB->getSinglePredecessor())
124           Reduction
125             += InlineConstants::InstrCost * Metrics.NumBBInsts.lookup(BB);
126       }
127     }
128   } while (!Worklist.empty());
129
130   return Reduction;
131 }
132
133 /// \brief Compute the reduction possible for a given instruction if we are able
134 /// to SROA an alloca.
135 ///
136 /// The reduction for this instruction is added to the SROAReduction output
137 /// parameter. Returns false if this instruction is expected to defeat SROA in
138 /// general.
139 static bool countCodeReductionForSROAInst(Instruction *I,
140                                           SmallVectorImpl<Value *> &Worklist,
141                                           unsigned &SROAReduction) {
142   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
143     if (!LI->isSimple())
144       return false;
145     SROAReduction += InlineConstants::InstrCost;
146     return true;
147   }
148
149   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
150     if (!SI->isSimple())
151       return false;
152     SROAReduction += InlineConstants::InstrCost;
153     return true;
154   }
155
156   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
157     // If the GEP has variable indices, we won't be able to do much with it.
158     if (!GEP->hasAllConstantIndices())
159       return false;
160     // A non-zero GEP will likely become a mask operation after SROA.
161     if (GEP->hasAllZeroIndices())
162       SROAReduction += InlineConstants::InstrCost;
163     Worklist.push_back(GEP);
164     return true;
165   }
166
167   if (BitCastInst *BCI = dyn_cast<BitCastInst>(I)) {
168     // Track pointer through bitcasts.
169     Worklist.push_back(BCI);
170     SROAReduction += InlineConstants::InstrCost;
171     return true;
172   }
173
174   // We just look for non-constant operands to ICmp instructions as those will
175   // defeat SROA. The actual reduction for these happens even without SROA.
176   if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
177     return isa<Constant>(ICI->getOperand(1));
178
179   if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
180     // SROA can handle a select of alloca iff all uses of the alloca are
181     // loads, and dereferenceable. We assume it's dereferenceable since
182     // we're told the input is an alloca.
183     for (Value::use_iterator UI = SI->use_begin(), UE = SI->use_end();
184          UI != UE; ++UI) {
185       LoadInst *LI = dyn_cast<LoadInst>(*UI);
186       if (LI == 0 || !LI->isSimple())
187         return false;
188     }
189     // We don't know whether we'll be deleting the rest of the chain of
190     // instructions from the SelectInst on, because we don't know whether
191     // the other side of the select is also an alloca or not.
192     return true;
193   }
194
195   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
196     switch (II->getIntrinsicID()) {
197     default:
198       return false;
199     case Intrinsic::memset:
200     case Intrinsic::memcpy:
201     case Intrinsic::memmove:
202     case Intrinsic::lifetime_start:
203     case Intrinsic::lifetime_end:
204       // SROA can usually chew through these intrinsics.
205       SROAReduction += InlineConstants::InstrCost;
206       return true;
207     }
208   }
209
210   // If there is some other strange instruction, we're not going to be
211   // able to do much if we inline this.
212   return false;
213 }
214
215 unsigned InlineCostAnalyzer::FunctionInfo::countCodeReductionForAlloca(
216     const CodeMetrics &Metrics, Value *V) {
217   if (!V->getType()->isPointerTy()) return 0;  // Not a pointer
218   unsigned Reduction = 0;
219   unsigned SROAReduction = 0;
220   bool CanSROAAlloca = true;
221
222   SmallVector<Value *, 4> Worklist;
223   Worklist.push_back(V);
224   do {
225     Value *V = Worklist.pop_back_val();
226     for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
227          UI != E; ++UI){
228       Instruction *I = cast<Instruction>(*UI);
229
230       if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
231         Reduction += countCodeReductionForAllocaICmp(Metrics, ICI);
232
233       if (CanSROAAlloca)
234         CanSROAAlloca = countCodeReductionForSROAInst(I, Worklist,
235                                                       SROAReduction);
236     }
237   } while (!Worklist.empty());
238
239   return Reduction + (CanSROAAlloca ? SROAReduction : 0);
240 }
241
242 void InlineCostAnalyzer::FunctionInfo::countCodeReductionForPointerPair(
243     const CodeMetrics &Metrics, DenseMap<Value *, unsigned> &PointerArgs,
244     Value *V, unsigned ArgIdx) {
245   SmallVector<Value *, 4> Worklist;
246   Worklist.push_back(V);
247   do {
248     Value *V = Worklist.pop_back_val();
249     for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
250          UI != E; ++UI){
251       Instruction *I = cast<Instruction>(*UI);
252
253       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
254         // If the GEP has variable indices, we won't be able to do much with it.
255         if (!GEP->hasAllConstantIndices())
256           continue;
257         // Unless the GEP is in-bounds, some comparisons will be non-constant.
258         // Fortunately, the real-world cases where this occurs uses in-bounds
259         // GEPs, and so we restrict the optimization to them here.
260         if (!GEP->isInBounds())
261           continue;
262
263         // Constant indices just change the constant offset. Add the resulting
264         // value both to our worklist for this argument, and to the set of
265         // viable paired values with future arguments.
266         PointerArgs[GEP] = ArgIdx;
267         Worklist.push_back(GEP);
268         continue;
269       }
270
271       // Track pointer through casts. Even when the result is not a pointer, it
272       // remains a constant relative to constants derived from other constant
273       // pointers.
274       if (CastInst *CI = dyn_cast<CastInst>(I)) {
275         PointerArgs[CI] = ArgIdx;
276         Worklist.push_back(CI);
277         continue;
278       }
279
280       // There are two instructions which produce a strict constant value when
281       // applied to two related pointer values. Ignore everything else.
282       if (!isa<ICmpInst>(I) && I->getOpcode() != Instruction::Sub)
283         continue;
284       assert(I->getNumOperands() == 2);
285
286       // Ensure that the two operands are in our set of potentially paired
287       // pointers (or are derived from them).
288       Value *OtherArg = I->getOperand(0);
289       if (OtherArg == V)
290         OtherArg = I->getOperand(1);
291       DenseMap<Value *, unsigned>::const_iterator ArgIt
292         = PointerArgs.find(OtherArg);
293       if (ArgIt == PointerArgs.end())
294         continue;
295       std::pair<unsigned, unsigned> ArgPair(ArgIt->second, ArgIdx);
296       if (ArgPair.first > ArgPair.second)
297         std::swap(ArgPair.first, ArgPair.second);
298
299       PointerArgPairWeights[ArgPair]
300         += countCodeReductionForConstant(Metrics, I);
301     }
302   } while (!Worklist.empty());
303 }
304
305 /// analyzeFunction - Fill in the current structure with information gleaned
306 /// from the specified function.
307 void InlineCostAnalyzer::FunctionInfo::analyzeFunction(Function *F,
308                                                        const TargetData *TD) {
309   Metrics.analyzeFunction(F, TD);
310
311   // A function with exactly one return has it removed during the inlining
312   // process (see InlineFunction), so don't count it.
313   // FIXME: This knowledge should really be encoded outside of FunctionInfo.
314   if (Metrics.NumRets==1)
315     --Metrics.NumInsts;
316
317   ArgumentWeights.reserve(F->arg_size());
318   DenseMap<Value *, unsigned> PointerArgs;
319   unsigned ArgIdx = 0;
320   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E;
321        ++I, ++ArgIdx) {
322     // Count how much code can be eliminated if one of the arguments is
323     // a constant or an alloca.
324     ArgumentWeights.push_back(ArgInfo(countCodeReductionForConstant(Metrics, I),
325                                       countCodeReductionForAlloca(Metrics, I)));
326
327     // If the argument is a pointer, also check for pairs of pointers where
328     // knowing a fixed offset between them allows simplification. This pattern
329     // arises mostly due to STL algorithm patterns where pointers are used as
330     // random access iterators.
331     if (!I->getType()->isPointerTy())
332       continue;
333     PointerArgs[I] = ArgIdx;
334     countCodeReductionForPointerPair(Metrics, PointerArgs, I, ArgIdx);
335   }
336 }
337
338 /// NeverInline - returns true if the function should never be inlined into
339 /// any caller
340 bool InlineCostAnalyzer::FunctionInfo::NeverInline() {
341   return (Metrics.exposesReturnsTwice || Metrics.isRecursive ||
342           Metrics.containsIndirectBr);
343 }
344
345 // ConstantFunctionBonus - Figure out how much of a bonus we can get for
346 // possibly devirtualizing a function. We'll subtract the size of the function
347 // we may wish to inline from the indirect call bonus providing a limit on
348 // growth. Leave an upper limit of 0 for the bonus - we don't want to penalize
349 // inlining because we decide we don't want to give a bonus for
350 // devirtualizing.
351 int InlineCostAnalyzer::ConstantFunctionBonus(CallSite CS, Constant *C) {
352
353   // This could just be NULL.
354   if (!C) return 0;
355
356   Function *F = dyn_cast<Function>(C);
357   if (!F) return 0;
358
359   int Bonus = InlineConstants::IndirectCallBonus + getInlineSize(CS, F);
360   return (Bonus > 0) ? 0 : Bonus;
361 }
362
363 // CountBonusForConstant - Figure out an approximation for how much per-call
364 // performance boost we can expect if the specified value is constant.
365 int InlineCostAnalyzer::CountBonusForConstant(Value *V, Constant *C) {
366   unsigned Bonus = 0;
367   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
368     User *U = *UI;
369     if (CallInst *CI = dyn_cast<CallInst>(U)) {
370       // Turning an indirect call into a direct call is a BIG win
371       if (CI->getCalledValue() == V)
372         Bonus += ConstantFunctionBonus(CallSite(CI), C);
373     } else if (InvokeInst *II = dyn_cast<InvokeInst>(U)) {
374       // Turning an indirect call into a direct call is a BIG win
375       if (II->getCalledValue() == V)
376         Bonus += ConstantFunctionBonus(CallSite(II), C);
377     }
378     // FIXME: Eliminating conditional branches and switches should
379     // also yield a per-call performance boost.
380     else {
381       // Figure out the bonuses that wll accrue due to simple constant
382       // propagation.
383       Instruction &Inst = cast<Instruction>(*U);
384
385       // We can't constant propagate instructions which have effects or
386       // read memory.
387       //
388       // FIXME: It would be nice to capture the fact that a load from a
389       // pointer-to-constant-global is actually a *really* good thing to zap.
390       // Unfortunately, we don't know the pointer that may get propagated here,
391       // so we can't make this decision.
392       if (Inst.mayReadFromMemory() || Inst.mayHaveSideEffects() ||
393           isa<AllocaInst>(Inst))
394         continue;
395
396       bool AllOperandsConstant = true;
397       for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i)
398         if (!isa<Constant>(Inst.getOperand(i)) && Inst.getOperand(i) != V) {
399           AllOperandsConstant = false;
400           break;
401         }
402
403       if (AllOperandsConstant)
404         Bonus += CountBonusForConstant(&Inst);
405     }
406   }
407
408   return Bonus;
409 }
410
411 int InlineCostAnalyzer::getInlineSize(CallSite CS, Function *Callee) {
412   // Get information about the callee.
413   FunctionInfo *CalleeFI = &CachedFunctionInfo[Callee];
414
415   // If we haven't calculated this information yet, do so now.
416   if (CalleeFI->Metrics.NumBlocks == 0)
417     CalleeFI->analyzeFunction(Callee, TD);
418
419   // InlineCost - This value measures how good of an inline candidate this call
420   // site is to inline.  A lower inline cost make is more likely for the call to
421   // be inlined.  This value may go negative.
422   //
423   int InlineCost = 0;
424
425   // Compute any size reductions we can expect due to arguments being passed into
426   // the function.
427   //
428   unsigned ArgNo = 0;
429   CallSite::arg_iterator I = CS.arg_begin();
430   for (Function::arg_iterator FI = Callee->arg_begin(), FE = Callee->arg_end();
431        FI != FE; ++I, ++FI, ++ArgNo) {
432
433     // If an alloca is passed in, inlining this function is likely to allow
434     // significant future optimization possibilities (like scalar promotion, and
435     // scalarization), so encourage the inlining of the function.
436     //
437     if (isa<AllocaInst>(I))
438       InlineCost -= CalleeFI->ArgumentWeights[ArgNo].AllocaWeight;
439
440     // If this is a constant being passed into the function, use the argument
441     // weights calculated for the callee to determine how much will be folded
442     // away with this information.
443     else if (isa<Constant>(I))
444       InlineCost -= CalleeFI->ArgumentWeights[ArgNo].ConstantWeight;
445   }
446
447   const DenseMap<std::pair<unsigned, unsigned>, unsigned> &ArgPairWeights
448     = CalleeFI->PointerArgPairWeights;
449   for (DenseMap<std::pair<unsigned, unsigned>, unsigned>::const_iterator I
450          = ArgPairWeights.begin(), E = ArgPairWeights.end();
451        I != E; ++I)
452     if (CS.getArgument(I->first.first)->stripInBoundsConstantOffsets() ==
453         CS.getArgument(I->first.second)->stripInBoundsConstantOffsets())
454       InlineCost -= I->second;
455
456   // Each argument passed in has a cost at both the caller and the callee
457   // sides.  Measurements show that each argument costs about the same as an
458   // instruction.
459   InlineCost -= (CS.arg_size() * InlineConstants::InstrCost);
460
461   // Now that we have considered all of the factors that make the call site more
462   // likely to be inlined, look at factors that make us not want to inline it.
463
464   // Calls usually take a long time, so they make the inlining gain smaller.
465   InlineCost += CalleeFI->Metrics.NumCalls * InlineConstants::CallPenalty;
466
467   // Look at the size of the callee. Each instruction counts as 5.
468   InlineCost += CalleeFI->Metrics.NumInsts * InlineConstants::InstrCost;
469
470   return InlineCost;
471 }
472
473 int InlineCostAnalyzer::getInlineBonuses(CallSite CS, Function *Callee) {
474   // Get information about the callee.
475   FunctionInfo *CalleeFI = &CachedFunctionInfo[Callee];
476
477   // If we haven't calculated this information yet, do so now.
478   if (CalleeFI->Metrics.NumBlocks == 0)
479     CalleeFI->analyzeFunction(Callee, TD);
480
481   bool isDirectCall = CS.getCalledFunction() == Callee;
482   Instruction *TheCall = CS.getInstruction();
483   int Bonus = 0;
484
485   // If there is only one call of the function, and it has internal linkage,
486   // make it almost guaranteed to be inlined.
487   //
488   if (Callee->hasLocalLinkage() && Callee->hasOneUse() && isDirectCall)
489     Bonus += InlineConstants::LastCallToStaticBonus;
490
491   // If the instruction after the call, or if the normal destination of the
492   // invoke is an unreachable instruction, the function is noreturn.  As such,
493   // there is little point in inlining this.
494   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
495     if (isa<UnreachableInst>(II->getNormalDest()->begin()))
496       Bonus += InlineConstants::NoreturnPenalty;
497   } else if (isa<UnreachableInst>(++BasicBlock::iterator(TheCall)))
498     Bonus += InlineConstants::NoreturnPenalty;
499
500   // If this function uses the coldcc calling convention, prefer not to inline
501   // it.
502   if (Callee->getCallingConv() == CallingConv::Cold)
503     Bonus += InlineConstants::ColdccPenalty;
504
505   // Add to the inline quality for properties that make the call valuable to
506   // inline.  This includes factors that indicate that the result of inlining
507   // the function will be optimizable.  Currently this just looks at arguments
508   // passed into the function.
509   //
510   CallSite::arg_iterator I = CS.arg_begin();
511   for (Function::arg_iterator FI = Callee->arg_begin(), FE = Callee->arg_end();
512        FI != FE; ++I, ++FI)
513     // Compute any constant bonus due to inlining we want to give here.
514     if (isa<Constant>(I))
515       Bonus += CountBonusForConstant(FI, cast<Constant>(I));
516
517   return Bonus;
518 }
519
520 // getInlineCost - The heuristic used to determine if we should inline the
521 // function call or not.
522 //
523 InlineCost InlineCostAnalyzer::getInlineCost(CallSite CS) {
524   return getInlineCost(CS, CS.getCalledFunction());
525 }
526
527 InlineCost InlineCostAnalyzer::getInlineCost(CallSite CS, Function *Callee) {
528   Instruction *TheCall = CS.getInstruction();
529   Function *Caller = TheCall->getParent()->getParent();
530
531   // Don't inline functions which can be redefined at link-time to mean
532   // something else.  Don't inline functions marked noinline or call sites
533   // marked noinline.
534   if (Callee->mayBeOverridden() || Callee->hasFnAttr(Attribute::NoInline) ||
535       CS.isNoInline())
536     return llvm::InlineCost::getNever();
537
538   // Get information about the callee.
539   FunctionInfo *CalleeFI = &CachedFunctionInfo[Callee];
540
541   // If we haven't calculated this information yet, do so now.
542   if (CalleeFI->Metrics.NumBlocks == 0)
543     CalleeFI->analyzeFunction(Callee, TD);
544
545   // If we should never inline this, return a huge cost.
546   if (CalleeFI->NeverInline())
547     return InlineCost::getNever();
548
549   // FIXME: It would be nice to kill off CalleeFI->NeverInline. Then we
550   // could move this up and avoid computing the FunctionInfo for
551   // things we are going to just return always inline for. This
552   // requires handling setjmp somewhere else, however.
553   if (!Callee->isDeclaration() && Callee->hasFnAttr(Attribute::AlwaysInline))
554     return InlineCost::getAlways();
555
556   if (CalleeFI->Metrics.usesDynamicAlloca) {
557     // Get information about the caller.
558     FunctionInfo &CallerFI = CachedFunctionInfo[Caller];
559
560     // If we haven't calculated this information yet, do so now.
561     if (CallerFI.Metrics.NumBlocks == 0) {
562       CallerFI.analyzeFunction(Caller, TD);
563
564       // Recompute the CalleeFI pointer, getting Caller could have invalidated
565       // it.
566       CalleeFI = &CachedFunctionInfo[Callee];
567     }
568
569     // Don't inline a callee with dynamic alloca into a caller without them.
570     // Functions containing dynamic alloca's are inefficient in various ways;
571     // don't create more inefficiency.
572     if (!CallerFI.Metrics.usesDynamicAlloca)
573       return InlineCost::getNever();
574   }
575
576   // InlineCost - This value measures how good of an inline candidate this call
577   // site is to inline.  A lower inline cost make is more likely for the call to
578   // be inlined.  This value may go negative due to the fact that bonuses
579   // are negative numbers.
580   //
581   int InlineCost = getInlineSize(CS, Callee) + getInlineBonuses(CS, Callee);
582   return llvm::InlineCost::get(InlineCost);
583 }
584
585 // getInlineFudgeFactor - Return a > 1.0 factor if the inliner should use a
586 // higher threshold to determine if the function call should be inlined.
587 float InlineCostAnalyzer::getInlineFudgeFactor(CallSite CS) {
588   Function *Callee = CS.getCalledFunction();
589
590   // Get information about the callee.
591   FunctionInfo &CalleeFI = CachedFunctionInfo[Callee];
592
593   // If we haven't calculated this information yet, do so now.
594   if (CalleeFI.Metrics.NumBlocks == 0)
595     CalleeFI.analyzeFunction(Callee, TD);
596
597   float Factor = 1.0f;
598   // Single BB functions are often written to be inlined.
599   if (CalleeFI.Metrics.NumBlocks == 1)
600     Factor += 0.5f;
601
602   // Be more aggressive if the function contains a good chunk (if it mades up
603   // at least 10% of the instructions) of vector instructions.
604   if (CalleeFI.Metrics.NumVectorInsts > CalleeFI.Metrics.NumInsts/2)
605     Factor += 2.0f;
606   else if (CalleeFI.Metrics.NumVectorInsts > CalleeFI.Metrics.NumInsts/10)
607     Factor += 1.5f;
608   return Factor;
609 }
610
611 /// growCachedCostInfo - update the cached cost info for Caller after Callee has
612 /// been inlined.
613 void
614 InlineCostAnalyzer::growCachedCostInfo(Function *Caller, Function *Callee) {
615   CodeMetrics &CallerMetrics = CachedFunctionInfo[Caller].Metrics;
616
617   // For small functions we prefer to recalculate the cost for better accuracy.
618   if (CallerMetrics.NumBlocks < 10 && CallerMetrics.NumInsts < 1000) {
619     resetCachedCostInfo(Caller);
620     return;
621   }
622
623   // For large functions, we can save a lot of computation time by skipping
624   // recalculations.
625   if (CallerMetrics.NumCalls > 0)
626     --CallerMetrics.NumCalls;
627
628   if (Callee == 0) return;
629
630   CodeMetrics &CalleeMetrics = CachedFunctionInfo[Callee].Metrics;
631
632   // If we don't have metrics for the callee, don't recalculate them just to
633   // update an approximation in the caller.  Instead, just recalculate the
634   // caller info from scratch.
635   if (CalleeMetrics.NumBlocks == 0) {
636     resetCachedCostInfo(Caller);
637     return;
638   }
639
640   // Since CalleeMetrics were already calculated, we know that the CallerMetrics
641   // reference isn't invalidated: both were in the DenseMap.
642   CallerMetrics.usesDynamicAlloca |= CalleeMetrics.usesDynamicAlloca;
643
644   // FIXME: If any of these three are true for the callee, the callee was
645   // not inlined into the caller, so I think they're redundant here.
646   CallerMetrics.exposesReturnsTwice |= CalleeMetrics.exposesReturnsTwice;
647   CallerMetrics.isRecursive |= CalleeMetrics.isRecursive;
648   CallerMetrics.containsIndirectBr |= CalleeMetrics.containsIndirectBr;
649
650   CallerMetrics.NumInsts += CalleeMetrics.NumInsts;
651   CallerMetrics.NumBlocks += CalleeMetrics.NumBlocks;
652   CallerMetrics.NumCalls += CalleeMetrics.NumCalls;
653   CallerMetrics.NumVectorInsts += CalleeMetrics.NumVectorInsts;
654   CallerMetrics.NumRets += CalleeMetrics.NumRets;
655
656   // analyzeBasicBlock counts each function argument as an inst.
657   if (CallerMetrics.NumInsts >= Callee->arg_size())
658     CallerMetrics.NumInsts -= Callee->arg_size();
659   else
660     CallerMetrics.NumInsts = 0;
661
662   // We are not updating the argument weights. We have already determined that
663   // Caller is a fairly large function, so we accept the loss of precision.
664 }
665
666 /// clear - empty the cache of inline costs
667 void InlineCostAnalyzer::clear() {
668   CachedFunctionInfo.clear();
669 }