Fix a rather serious bug in previous checkin
[oota-llvm.git] / lib / Transforms / IPO / InlineSimple.cpp
1 //===- InlineSimple.cpp - Code to perform simple function inlining --------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements bottom-up inlining of functions into callees.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "Inliner.h"
15 #include "llvm/Instructions.h"
16 #include "llvm/Function.h"
17 #include "llvm/Type.h"
18 #include "llvm/Support/CallSite.h"
19 #include "llvm/Transforms/IPO.h"
20 using namespace llvm;
21
22 namespace {
23   struct ArgInfo {
24     unsigned ConstantWeight;
25     unsigned AllocaWeight;
26
27     ArgInfo(unsigned CWeight, unsigned AWeight)
28       : ConstantWeight(CWeight), AllocaWeight(AWeight) {}
29   };
30
31   // FunctionInfo - For each function, calculate the size of it in blocks and
32   // instructions.
33   struct FunctionInfo {
34     // NumInsts, NumBlocks - Keep track of how large each function is, which is
35     // used to estimate the code size cost of inlining it.
36     unsigned NumInsts, NumBlocks;
37
38     // ArgumentWeights - Each formal argument of the function is inspected to
39     // see if it is used in any contexts where making it a constant or alloca
40     // would reduce the code size.  If so, we add some value to the argument
41     // entry here.
42     std::vector<ArgInfo> ArgumentWeights;
43
44     FunctionInfo() : NumInsts(0), NumBlocks(0) {}
45   };
46
47   class SimpleInliner : public Inliner {
48     std::map<const Function*, FunctionInfo> CachedFunctionInfo;
49   public:
50     int getInlineCost(CallSite CS);
51   };
52   RegisterOpt<SimpleInliner> X("inline", "Function Integration/Inlining");
53 }
54
55 Pass *llvm::createFunctionInliningPass() { return new SimpleInliner(); }
56
57 // CountCodeReductionForConstant - Figure out an approximation for how many
58 // instructions will be constant folded if the specified value is constant.
59 //
60 static unsigned CountCodeReductionForConstant(Value *V) {
61   unsigned Reduction = 0;
62   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
63     if (isa<BranchInst>(*UI))
64       Reduction += 40;          // Eliminating a conditional branch is a big win
65     else if (SwitchInst *SI = dyn_cast<SwitchInst>(*UI))
66       // Eliminating a switch is a big win, proportional to the number of edges
67       // deleted.
68       Reduction += (SI->getNumSuccessors()-1) * 40;
69     else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
70       // Turning an indirect call into a direct call is a BIG win
71       Reduction += CI->getCalledValue() == V ? 500 : 0;
72     } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
73       // Turning an indirect call into a direct call is a BIG win
74       Reduction += II->getCalledValue() == V ? 500 : 0;
75     } else {
76       // Figure out if this instruction will be removed due to simple constant
77       // propagation.
78       Instruction &Inst = cast<Instruction>(**UI);
79       bool AllOperandsConstant = true;
80       for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i)
81         if (!isa<Constant>(Inst.getOperand(i)) && Inst.getOperand(i) != V) {
82           AllOperandsConstant = false;
83           break;
84         }
85
86       if (AllOperandsConstant) {
87         // We will get to remove this instruction...
88         Reduction += 7;
89         
90         // And any other instructions that use it which become constants
91         // themselves.
92         Reduction += CountCodeReductionForConstant(&Inst);
93       }
94     }
95
96   return Reduction;
97 }
98
99 // CountCodeReductionForAlloca - Figure out an approximation of how much smaller
100 // the function will be if it is inlined into a context where an argument
101 // becomes an alloca.
102 //
103 static unsigned CountCodeReductionForAlloca(Value *V) {
104   if (!isa<PointerType>(V->getType())) return 0;  // Not a pointer
105   unsigned Reduction = 0;
106   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
107     Instruction *I = cast<Instruction>(*UI);
108     if (isa<LoadInst>(I) || isa<StoreInst>(I))
109       Reduction += 10;
110     else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
111       // If the GEP has variable indices, we won't be able to do much with it.
112       for (Instruction::op_iterator I = GEP->op_begin()+1, E = GEP->op_end();
113            I != E; ++I)
114         if (!isa<Constant>(*I)) return 0;
115       Reduction += CountCodeReductionForAlloca(GEP)+15;
116     } else {
117       // If there is some other strange instruction, we're not going to be able
118       // to do much if we inline this.
119       return 0;
120     }
121   }
122
123   return Reduction;
124 }
125
126 // getInlineCost - The heuristic used to determine if we should inline the
127 // function call or not.
128 //
129 int SimpleInliner::getInlineCost(CallSite CS) {
130   Instruction *TheCall = CS.getInstruction();
131   Function *Callee = CS.getCalledFunction();
132   const Function *Caller = TheCall->getParent()->getParent();
133
134   // Don't inline a directly recursive call.
135   if (Caller == Callee) return 2000000000;
136
137   // InlineCost - This value measures how good of an inline candidate this call
138   // site is to inline.  A lower inline cost make is more likely for the call to
139   // be inlined.  This value may go negative.
140   //
141   int InlineCost = 0;
142
143   // If there is only one call of the function, and it has internal linkage,
144   // make it almost guaranteed to be inlined.
145   //
146   if (Callee->hasInternalLinkage() && Callee->hasOneUse())
147     InlineCost -= 30000;
148
149   // Get information about the callee...
150   FunctionInfo &CalleeFI = CachedFunctionInfo[Callee];
151
152   // If we haven't calculated this information yet...
153   if (CalleeFI.NumBlocks == 0) {
154     unsigned NumInsts = 0, NumBlocks = 0;
155
156     // Look at the size of the callee.  Each basic block counts as 20 units, and
157     // each instruction counts as 10.
158     for (Function::const_iterator BB = Callee->begin(), E = Callee->end();
159          BB != E; ++BB) {
160       NumInsts += BB->size();
161       NumBlocks++;
162     }
163
164     CalleeFI.NumBlocks = NumBlocks;
165     CalleeFI.NumInsts  = NumInsts;
166
167     // Check out all of the arguments to the function, figuring out how much
168     // code can be eliminated if one of the arguments is a constant.
169     std::vector<ArgInfo> &ArgWeights = CalleeFI.ArgumentWeights;
170
171     for (Function::aiterator I = Callee->abegin(), E = Callee->aend();
172          I != E; ++I)
173       ArgWeights.push_back(ArgInfo(CountCodeReductionForConstant(I),
174                                    CountCodeReductionForAlloca(I)));
175   }
176
177
178   // Add to the inline quality for properties that make the call valuable to
179   // inline.  This includes factors that indicate that the result of inlining
180   // the function will be optimizable.  Currently this just looks at arguments
181   // passed into the function.
182   //
183   unsigned ArgNo = 0;
184   for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
185        I != E; ++I, ++ArgNo) {
186     // Each argument passed in has a cost at both the caller and the callee
187     // sides.  This favors functions that take many arguments over functions
188     // that take few arguments.
189     InlineCost -= 20;
190
191     // If this is a function being passed in, it is very likely that we will be
192     // able to turn an indirect function call into a direct function call.
193     if (isa<Function>(I))
194       InlineCost -= 100;
195
196     // If an alloca is passed in, inlining this function is likely to allow
197     // significant future optimization possibilities (like scalar promotion, and
198     // scalarization), so encourage the inlining of the function.
199     //
200     else if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
201       if (ArgNo < CalleeFI.ArgumentWeights.size())
202         InlineCost -= CalleeFI.ArgumentWeights[ArgNo].AllocaWeight;
203
204     // If this is a constant being passed into the function, use the argument
205     // weights calculated for the callee to determine how much will be folded
206     // away with this information.
207     } else if (isa<Constant>(I)) {
208       if (ArgNo < CalleeFI.ArgumentWeights.size())
209         InlineCost -= CalleeFI.ArgumentWeights[ArgNo].ConstantWeight;
210     }
211   }
212
213   // Now that we have considered all of the factors that make the call site more
214   // likely to be inlined, look at factors that make us not want to inline it.
215
216   // Don't inline into something too big, which would make it bigger.  Here, we
217   // count each basic block as a single unit.
218   //
219   InlineCost += Caller->size()/20;
220
221
222   // Look at the size of the callee.  Each basic block counts as 20 units, and
223   // each instruction counts as 5.
224   InlineCost += CalleeFI.NumInsts*5 + CalleeFI.NumBlocks*20;
225   return InlineCost;
226 }
227