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