Formating fixes.
[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/CallingConv.h"
16 #include "llvm/Instructions.h"
17 #include "llvm/IntrinsicInst.h"
18 #include "llvm/Module.h"
19 #include "llvm/Type.h"
20 #include "llvm/Analysis/CallGraph.h"
21 #include "llvm/Support/CallSite.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/Transforms/IPO.h"
24 #include <set>
25
26 using namespace llvm;
27
28 namespace {
29   struct VISIBILITY_HIDDEN ArgInfo {
30     unsigned ConstantWeight;
31     unsigned AllocaWeight;
32
33     ArgInfo(unsigned CWeight, unsigned AWeight)
34       : ConstantWeight(CWeight), AllocaWeight(AWeight) {}
35   };
36
37   // FunctionInfo - For each function, calculate the size of it in blocks and
38   // instructions.
39   struct VISIBILITY_HIDDEN FunctionInfo {
40     // NumInsts, NumBlocks - Keep track of how large each function is, which is
41     // used to estimate the code size cost of inlining it.
42     unsigned NumInsts, NumBlocks;
43
44     // ArgumentWeights - Each formal argument of the function is inspected to
45     // see if it is used in any contexts where making it a constant or alloca
46     // would reduce the code size.  If so, we add some value to the argument
47     // entry here.
48     std::vector<ArgInfo> ArgumentWeights;
49
50     FunctionInfo() : NumInsts(0), NumBlocks(0) {}
51
52     /// analyzeFunction - Fill in the current structure with information gleaned
53     /// from the specified function.
54     void analyzeFunction(Function *F);
55   };
56
57   class VISIBILITY_HIDDEN SimpleInliner : public Inliner {
58     std::map<const Function*, FunctionInfo> CachedFunctionInfo;
59     std::set<const Function*> NeverInline; // Functions that are never inlined
60   public:
61     SimpleInliner() : Inliner(&ID) {}
62     static char ID; // Pass identification, replacement for typeid
63     int getInlineCost(CallSite CS);
64     virtual bool doInitialization(CallGraph &CG);
65   };
66   char SimpleInliner::ID = 0;
67   RegisterPass<SimpleInliner> X("inline", "Function Integration/Inlining");
68 }
69
70 Pass *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)) continue;  // Debug intrinsics don't count.
152       
153       // Noop casts, including ptr <-> int,  don't count.
154       if (const CastInst *CI = dyn_cast<CastInst>(II)) {
155         if (CI->isLosslessCast() || isa<IntToPtrInst>(CI) || 
156             isa<PtrToIntInst>(CI))
157           continue;
158       } else if (const GetElementPtrInst *GEPI =
159                          dyn_cast<GetElementPtrInst>(II)) {
160         // If a GEP has all constant indices, it will probably be folded with
161         // a load/store.
162         bool AllConstant = true;
163         for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
164           if (!isa<ConstantInt>(GEPI->getOperand(i))) {
165             AllConstant = false;
166             break;
167           }
168         if (AllConstant) continue;
169       }
170       
171       ++NumInsts;
172     }
173
174     ++NumBlocks;
175   }
176
177   this->NumBlocks = NumBlocks;
178   this->NumInsts  = NumInsts;
179
180   // Check out all of the arguments to the function, figuring out how much
181   // code can be eliminated if one of the arguments is a constant.
182   for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
183     ArgumentWeights.push_back(ArgInfo(CountCodeReductionForConstant(I),
184                                       CountCodeReductionForAlloca(I)));
185 }
186
187
188 // getInlineCost - The heuristic used to determine if we should inline the
189 // function call or not.
190 //
191 int SimpleInliner::getInlineCost(CallSite CS) {
192   Instruction *TheCall = CS.getInstruction();
193   Function *Callee = CS.getCalledFunction();
194   const Function *Caller = TheCall->getParent()->getParent();
195
196   // Don't inline a directly recursive call.
197   if (Caller == Callee) return 2000000000;
198
199   // Don't inline functions marked noinline
200   if (NeverInline.count(Callee)) return 2000000000;
201   
202   // InlineCost - This value measures how good of an inline candidate this call
203   // site is to inline.  A lower inline cost make is more likely for the call to
204   // be inlined.  This value may go negative.
205   //
206   int InlineCost = 0;
207
208   // If there is only one call of the function, and it has internal linkage,
209   // make it almost guaranteed to be inlined.
210   //
211   if (Callee->hasInternalLinkage() && Callee->hasOneUse())
212     InlineCost -= 30000;
213
214   // If this function uses the coldcc calling convention, prefer not to inline
215   // it.
216   if (Callee->getCallingConv() == CallingConv::Cold)
217     InlineCost += 2000;
218
219   // If the instruction after the call, or if the normal destination of the
220   // invoke is an unreachable instruction, the function is noreturn.  As such,
221   // there is little point in inlining this.
222   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
223     if (isa<UnreachableInst>(II->getNormalDest()->begin()))
224       InlineCost += 10000;
225   } else if (isa<UnreachableInst>(++BasicBlock::iterator(TheCall)))
226     InlineCost += 10000;
227
228   // Get information about the callee...
229   FunctionInfo &CalleeFI = CachedFunctionInfo[Callee];
230
231   // If we haven't calculated this information yet, do so now.
232   if (CalleeFI.NumBlocks == 0)
233     CalleeFI.analyzeFunction(Callee);
234
235   // Add to the inline quality for properties that make the call valuable to
236   // inline.  This includes factors that indicate that the result of inlining
237   // the function will be optimizable.  Currently this just looks at arguments
238   // passed into the function.
239   //
240   unsigned ArgNo = 0;
241   for (CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
242        I != E; ++I, ++ArgNo) {
243     // Each argument passed in has a cost at both the caller and the callee
244     // sides.  This favors functions that take many arguments over functions
245     // that take few arguments.
246     InlineCost -= 20;
247
248     // If this is a function being passed in, it is very likely that we will be
249     // able to turn an indirect function call into a direct function call.
250     if (isa<Function>(I))
251       InlineCost -= 100;
252
253     // If an alloca is passed in, inlining this function is likely to allow
254     // significant future optimization possibilities (like scalar promotion, and
255     // scalarization), so encourage the inlining of the function.
256     //
257     else if (isa<AllocaInst>(I)) {
258       if (ArgNo < CalleeFI.ArgumentWeights.size())
259         InlineCost -= CalleeFI.ArgumentWeights[ArgNo].AllocaWeight;
260
261     // If this is a constant being passed into the function, use the argument
262     // weights calculated for the callee to determine how much will be folded
263     // away with this information.
264     } else if (isa<Constant>(I)) {
265       if (ArgNo < CalleeFI.ArgumentWeights.size())
266         InlineCost -= CalleeFI.ArgumentWeights[ArgNo].ConstantWeight;
267     }
268   }
269
270   // Now that we have considered all of the factors that make the call site more
271   // likely to be inlined, look at factors that make us not want to inline it.
272
273   // Don't inline into something too big, which would make it bigger.  Here, we
274   // count each basic block as a single unit.
275   //
276   InlineCost += Caller->size()/20;
277
278
279   // Look at the size of the callee.  Each basic block counts as 20 units, and
280   // each instruction counts as 5.
281   InlineCost += CalleeFI.NumInsts*5 + CalleeFI.NumBlocks*20;
282   return InlineCost;
283 }
284
285 // doInitialization - Initializes the vector of functions that have been
286 // annotated with the noinline attribute.
287 bool SimpleInliner::doInitialization(CallGraph &CG) {
288   
289   Module &M = CG.getModule();
290   
291   // Get llvm.noinline
292   GlobalVariable *GV = M.getNamedGlobal("llvm.noinline");
293   
294   if (GV == 0)
295     return false;
296
297   const ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
298   
299   if (InitList == 0)
300     return false;
301
302   // Iterate over each element and add to the NeverInline set
303   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
304         
305     // Get Source
306     const Constant *Elt = InitList->getOperand(i);
307         
308     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Elt))
309       if (CE->getOpcode() == Instruction::BitCast) 
310         Elt = CE->getOperand(0);
311     
312     // Insert into set of functions to never inline
313     if (const Function *F = dyn_cast<Function>(Elt))
314       NeverInline.insert(F);
315   }
316   
317   return false;
318 }