Change the callgraph representation to store the callsite along with the
[oota-llvm.git] / lib / Transforms / Utils / InlineFunction.cpp
1 //===- InlineFunction.cpp - Code to perform 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 inlining of a function into a call site, resolving
11 // parameters and the return value as appropriate.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Transforms/Utils/Cloning.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Module.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Intrinsics.h"
21 #include "llvm/Analysis/CallGraph.h"
22 #include "llvm/Support/CallSite.h"
23 using namespace llvm;
24
25 bool llvm::InlineFunction(CallInst *CI, CallGraph *CG) {
26   return InlineFunction(CallSite(CI), CG);
27 }
28 bool llvm::InlineFunction(InvokeInst *II, CallGraph *CG) {
29   return InlineFunction(CallSite(II), CG);
30 }
31
32 /// HandleInlinedInvoke - If we inlined an invoke site, we need to convert calls
33 /// in the body of the inlined function into invokes and turn unwind
34 /// instructions into branches to the invoke unwind dest.
35 ///
36 /// II is the invoke instruction begin inlined.  FirstNewBlock is the first
37 /// block of the inlined code (the last block is the end of the function),
38 /// and InlineCodeInfo is information about the code that got inlined.
39 static void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
40                                 ClonedCodeInfo &InlinedCodeInfo) {
41   BasicBlock *InvokeDest = II->getUnwindDest();
42   std::vector<Value*> InvokeDestPHIValues;
43
44   // If there are PHI nodes in the unwind destination block, we need to
45   // keep track of which values came into them from this invoke, then remove
46   // the entry for this block.
47   BasicBlock *InvokeBlock = II->getParent();
48   for (BasicBlock::iterator I = InvokeDest->begin(); isa<PHINode>(I); ++I) {
49     PHINode *PN = cast<PHINode>(I);
50     // Save the value to use for this edge.
51     InvokeDestPHIValues.push_back(PN->getIncomingValueForBlock(InvokeBlock));
52   }
53
54   Function *Caller = FirstNewBlock->getParent();
55   
56   // The inlined code is currently at the end of the function, scan from the
57   // start of the inlined code to its end, checking for stuff we need to
58   // rewrite.
59   if (InlinedCodeInfo.ContainsCalls || InlinedCodeInfo.ContainsUnwinds) {
60     for (Function::iterator BB = FirstNewBlock, E = Caller->end();
61          BB != E; ++BB) {
62       if (InlinedCodeInfo.ContainsCalls) {
63         for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ){
64           Instruction *I = BBI++;
65           
66           // We only need to check for function calls: inlined invoke
67           // instructions require no special handling.
68           if (!isa<CallInst>(I)) continue;
69           CallInst *CI = cast<CallInst>(I);
70
71           // If this is an intrinsic function call, don't convert it to an
72           // invoke.
73           if (CI->getCalledFunction() &&
74               CI->getCalledFunction()->getIntrinsicID())
75             continue;
76           
77           // Convert this function call into an invoke instruction.
78           // First, split the basic block.
79           BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
80           
81           // Next, create the new invoke instruction, inserting it at the end
82           // of the old basic block.
83           InvokeInst *II =
84             new InvokeInst(CI->getCalledValue(), Split, InvokeDest,
85                            std::vector<Value*>(CI->op_begin()+1, CI->op_end()),
86                            CI->getName(), BB->getTerminator());
87           II->setCallingConv(CI->getCallingConv());
88           
89           // Make sure that anything using the call now uses the invoke!
90           CI->replaceAllUsesWith(II);
91           
92           // Delete the unconditional branch inserted by splitBasicBlock
93           BB->getInstList().pop_back();
94           Split->getInstList().pop_front();  // Delete the original call
95           
96           // Update any PHI nodes in the exceptional block to indicate that
97           // there is now a new entry in them.
98           unsigned i = 0;
99           for (BasicBlock::iterator I = InvokeDest->begin();
100                isa<PHINode>(I); ++I, ++i) {
101             PHINode *PN = cast<PHINode>(I);
102             PN->addIncoming(InvokeDestPHIValues[i], BB);
103           }
104             
105           // This basic block is now complete, start scanning the next one.
106           break;
107         }
108       }
109       
110       if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
111         // An UnwindInst requires special handling when it gets inlined into an
112         // invoke site.  Once this happens, we know that the unwind would cause
113         // a control transfer to the invoke exception destination, so we can
114         // transform it into a direct branch to the exception destination.
115         new BranchInst(InvokeDest, UI);
116         
117         // Delete the unwind instruction!
118         UI->getParent()->getInstList().pop_back();
119         
120         // Update any PHI nodes in the exceptional block to indicate that
121         // there is now a new entry in them.
122         unsigned i = 0;
123         for (BasicBlock::iterator I = InvokeDest->begin();
124              isa<PHINode>(I); ++I, ++i) {
125           PHINode *PN = cast<PHINode>(I);
126           PN->addIncoming(InvokeDestPHIValues[i], BB);
127         }
128       }
129     }
130   }
131
132   // Now that everything is happy, we have one final detail.  The PHI nodes in
133   // the exception destination block still have entries due to the original
134   // invoke instruction.  Eliminate these entries (which might even delete the
135   // PHI node) now.
136   InvokeDest->removePredecessor(II->getParent());
137 }
138
139 /// UpdateCallGraphAfterInlining - Once we have cloned code over from a callee
140 /// into the caller, update the specified callgraph to reflect the changes we
141 /// made.  Note that it's possible that not all code was copied over, so only
142 /// some edges of the callgraph will be remain.
143 static void UpdateCallGraphAfterInlining(const Function *Caller,
144                                          const Function *Callee,
145                                          Function::iterator FirstNewBlock,
146                                        std::map<const Value*, Value*> &ValueMap,
147                                          CallGraph &CG) {
148   // Update the call graph by deleting the edge from Callee to Caller
149   CallGraphNode *CalleeNode = CG[Callee];
150   CallGraphNode *CallerNode = CG[Caller];
151   CallerNode->removeCallEdgeTo(CalleeNode);
152   
153   // Since we inlined some uninlined call sites in the callee into the caller,
154   // add edges from the caller to all of the callees of the callee.
155   for (CallGraphNode::iterator I = CalleeNode->begin(),
156        E = CalleeNode->end(); I != E; ++I) {
157     const Instruction *OrigCall = I->first.getInstruction();
158     
159     std::map<const Value*, Value*>::iterator VMI = ValueMap.find(OrigCall);
160     if (VMI != ValueMap.end()) { // Only copy the edge if the call was inlined!
161       Instruction *NewCall = cast<Instruction>(VMI->second);
162       CallerNode->addCalledFunction(CallSite::get(NewCall), I->second);
163     }
164   }
165 }
166
167
168 // InlineFunction - This function inlines the called function into the basic
169 // block of the caller.  This returns false if it is not possible to inline this
170 // call.  The program is still in a well defined state if this occurs though.
171 //
172 // Note that this only does one level of inlining.  For example, if the
173 // instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
174 // exists in the instruction stream.  Similiarly this will inline a recursive
175 // function by one level.
176 //
177 bool llvm::InlineFunction(CallSite CS, CallGraph *CG) {
178   Instruction *TheCall = CS.getInstruction();
179   assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
180          "Instruction not in function!");
181
182   const Function *CalledFunc = CS.getCalledFunction();
183   if (CalledFunc == 0 ||          // Can't inline external function or indirect
184       CalledFunc->isExternal() || // call, or call to a vararg function!
185       CalledFunc->getFunctionType()->isVarArg()) return false;
186
187
188   // If the call to the callee is a non-tail call, we must clear the 'tail'
189   // flags on any calls that we inline.
190   bool MustClearTailCallFlags =
191     isa<CallInst>(TheCall) && !cast<CallInst>(TheCall)->isTailCall();
192
193   BasicBlock *OrigBB = TheCall->getParent();
194   Function *Caller = OrigBB->getParent();
195
196   // Get an iterator to the last basic block in the function, which will have
197   // the new function inlined after it.
198   //
199   Function::iterator LastBlock = &Caller->back();
200
201   // Make sure to capture all of the return instructions from the cloned
202   // function.
203   std::vector<ReturnInst*> Returns;
204   ClonedCodeInfo InlinedFunctionInfo;
205   Function::iterator FirstNewBlock;
206   
207   { // Scope to destroy ValueMap after cloning.
208     std::map<const Value*, Value*> ValueMap;
209
210     // Calculate the vector of arguments to pass into the function cloner, which
211     // matches up the formal to the actual argument values.
212     assert(std::distance(CalledFunc->arg_begin(), CalledFunc->arg_end()) ==
213            std::distance(CS.arg_begin(), CS.arg_end()) &&
214            "No varargs calls can be inlined!");
215     CallSite::arg_iterator AI = CS.arg_begin();
216     for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
217            E = CalledFunc->arg_end(); I != E; ++I, ++AI)
218       ValueMap[I] = *AI;
219
220     // We want the inliner to prune the code as it copies.  We would LOVE to
221     // have no dead or constant instructions leftover after inlining occurs
222     // (which can happen, e.g., because an argument was constant), but we'll be
223     // happy with whatever the cloner can do.
224     CloneAndPruneFunctionInto(Caller, CalledFunc, ValueMap, Returns, ".i",
225                               &InlinedFunctionInfo);
226     
227     // Remember the first block that is newly cloned over.
228     FirstNewBlock = LastBlock; ++FirstNewBlock;
229     
230     // Update the callgraph if requested.
231     if (CG)
232       UpdateCallGraphAfterInlining(Caller, CalledFunc, FirstNewBlock, ValueMap,
233                                    *CG);
234   }
235  
236   // If there are any alloca instructions in the block that used to be the entry
237   // block for the callee, move them to the entry block of the caller.  First
238   // calculate which instruction they should be inserted before.  We insert the
239   // instructions at the end of the current alloca list.
240   //
241   {
242     BasicBlock::iterator InsertPoint = Caller->begin()->begin();
243     for (BasicBlock::iterator I = FirstNewBlock->begin(),
244            E = FirstNewBlock->end(); I != E; )
245       if (AllocaInst *AI = dyn_cast<AllocaInst>(I++))
246         if (isa<Constant>(AI->getArraySize())) {
247           // Scan for the block of allocas that we can move over, and move them
248           // all at once.
249           while (isa<AllocaInst>(I) &&
250                  isa<Constant>(cast<AllocaInst>(I)->getArraySize()))
251             ++I;
252
253           // Transfer all of the allocas over in a block.  Using splice means
254           // that they instructions aren't removed from the symbol table, then
255           // reinserted.
256           Caller->front().getInstList().splice(InsertPoint,
257                                                FirstNewBlock->getInstList(),
258                                                AI, I);
259         }
260   }
261
262   // If the inlined code contained dynamic alloca instructions, wrap the inlined
263   // code with llvm.stacksave/llvm.stackrestore intrinsics.
264   if (InlinedFunctionInfo.ContainsDynamicAllocas) {
265     Module *M = Caller->getParent();
266     const Type *SBytePtr = PointerType::get(Type::SByteTy);
267     // Get the two intrinsics we care about.
268     Function *StackSave, *StackRestore;
269     StackSave    = M->getOrInsertFunction("llvm.stacksave", SBytePtr, NULL);
270     StackRestore = M->getOrInsertFunction("llvm.stackrestore", Type::VoidTy,
271                                           SBytePtr, NULL);
272
273     // If we are preserving the callgraph, add edges to the stacksave/restore
274     // functions for the calls we insert.
275     CallGraphNode *StackSaveCGN, *StackRestoreCGN, *CallerNode;
276     if (CG) {
277       StackSaveCGN    = CG->getOrInsertFunction(StackSave);
278       StackRestoreCGN = CG->getOrInsertFunction(StackRestore);
279       CallerNode = (*CG)[Caller];
280     }
281       
282     // Insert the llvm.stacksave.
283     CallInst *SavedPtr = new CallInst(StackSave, "savedstack", 
284                                       FirstNewBlock->begin());
285     if (CG) CallerNode->addCalledFunction(SavedPtr, StackSaveCGN);
286       
287     // Insert a call to llvm.stackrestore before any return instructions in the
288     // inlined function.
289     for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
290       CallInst *CI = new CallInst(StackRestore, SavedPtr, "", Returns[i]);
291       if (CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
292     }
293
294     // Count the number of StackRestore calls we insert.
295     unsigned NumStackRestores = Returns.size();
296     
297     // If we are inlining an invoke instruction, insert restores before each
298     // unwind.  These unwinds will be rewritten into branches later.
299     if (InlinedFunctionInfo.ContainsUnwinds && isa<InvokeInst>(TheCall)) {
300       for (Function::iterator BB = FirstNewBlock, E = Caller->end();
301            BB != E; ++BB)
302         if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
303           new CallInst(StackRestore, SavedPtr, "", UI);
304           ++NumStackRestores;
305         }
306     }
307   }
308
309   // If we are inlining tail call instruction through a call site that isn't 
310   // marked 'tail', we must remove the tail marker for any calls in the inlined
311   // code.
312   if (MustClearTailCallFlags && InlinedFunctionInfo.ContainsCalls) {
313     for (Function::iterator BB = FirstNewBlock, E = Caller->end();
314          BB != E; ++BB)
315       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
316         if (CallInst *CI = dyn_cast<CallInst>(I))
317           CI->setTailCall(false);
318   }
319
320   // If we are inlining for an invoke instruction, we must make sure to rewrite
321   // any inlined 'unwind' instructions into branches to the invoke exception
322   // destination, and call instructions into invoke instructions.
323   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
324     HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
325
326   // If we cloned in _exactly one_ basic block, and if that block ends in a
327   // return instruction, we splice the body of the inlined callee directly into
328   // the calling basic block.
329   if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
330     // Move all of the instructions right before the call.
331     OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
332                                  FirstNewBlock->begin(), FirstNewBlock->end());
333     // Remove the cloned basic block.
334     Caller->getBasicBlockList().pop_back();
335
336     // If the call site was an invoke instruction, add a branch to the normal
337     // destination.
338     if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
339       new BranchInst(II->getNormalDest(), TheCall);
340
341     // If the return instruction returned a value, replace uses of the call with
342     // uses of the returned value.
343     if (!TheCall->use_empty())
344       TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
345
346     // Since we are now done with the Call/Invoke, we can delete it.
347     TheCall->getParent()->getInstList().erase(TheCall);
348
349     // Since we are now done with the return instruction, delete it also.
350     Returns[0]->getParent()->getInstList().erase(Returns[0]);
351
352     // We are now done with the inlining.
353     return true;
354   }
355
356   // Otherwise, we have the normal case, of more than one block to inline or
357   // multiple return sites.
358
359   // We want to clone the entire callee function into the hole between the
360   // "starter" and "ender" blocks.  How we accomplish this depends on whether
361   // this is an invoke instruction or a call instruction.
362   BasicBlock *AfterCallBB;
363   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
364
365     // Add an unconditional branch to make this look like the CallInst case...
366     BranchInst *NewBr = new BranchInst(II->getNormalDest(), TheCall);
367
368     // Split the basic block.  This guarantees that no PHI nodes will have to be
369     // updated due to new incoming edges, and make the invoke case more
370     // symmetric to the call case.
371     AfterCallBB = OrigBB->splitBasicBlock(NewBr,
372                                           CalledFunc->getName()+".exit");
373
374   } else {  // It's a call
375     // If this is a call instruction, we need to split the basic block that
376     // the call lives in.
377     //
378     AfterCallBB = OrigBB->splitBasicBlock(TheCall,
379                                           CalledFunc->getName()+".exit");
380   }
381
382   // Change the branch that used to go to AfterCallBB to branch to the first
383   // basic block of the inlined function.
384   //
385   TerminatorInst *Br = OrigBB->getTerminator();
386   assert(Br && Br->getOpcode() == Instruction::Br &&
387          "splitBasicBlock broken!");
388   Br->setOperand(0, FirstNewBlock);
389
390
391   // Now that the function is correct, make it a little bit nicer.  In
392   // particular, move the basic blocks inserted from the end of the function
393   // into the space made by splitting the source basic block.
394   //
395   Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
396                                      FirstNewBlock, Caller->end());
397
398   // Handle all of the return instructions that we just cloned in, and eliminate
399   // any users of the original call/invoke instruction.
400   if (Returns.size() > 1) {
401     // The PHI node should go at the front of the new basic block to merge all
402     // possible incoming values.
403     //
404     PHINode *PHI = 0;
405     if (!TheCall->use_empty()) {
406       PHI = new PHINode(CalledFunc->getReturnType(),
407                         TheCall->getName(), AfterCallBB->begin());
408
409       // Anything that used the result of the function call should now use the
410       // PHI node as their operand.
411       //
412       TheCall->replaceAllUsesWith(PHI);
413     }
414
415     // Loop over all of the return instructions, turning them into unconditional
416     // branches to the merge point now, and adding entries to the PHI node as
417     // appropriate.
418     for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
419       ReturnInst *RI = Returns[i];
420
421       if (PHI) {
422         assert(RI->getReturnValue() && "Ret should have value!");
423         assert(RI->getReturnValue()->getType() == PHI->getType() &&
424                "Ret value not consistent in function!");
425         PHI->addIncoming(RI->getReturnValue(), RI->getParent());
426       }
427
428       // Add a branch to the merge point where the PHI node lives if it exists.
429       new BranchInst(AfterCallBB, RI);
430
431       // Delete the return instruction now
432       RI->getParent()->getInstList().erase(RI);
433     }
434
435   } else if (!Returns.empty()) {
436     // Otherwise, if there is exactly one return value, just replace anything
437     // using the return value of the call with the computed value.
438     if (!TheCall->use_empty())
439       TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
440
441     // Splice the code from the return block into the block that it will return
442     // to, which contains the code that was after the call.
443     BasicBlock *ReturnBB = Returns[0]->getParent();
444     AfterCallBB->getInstList().splice(AfterCallBB->begin(),
445                                       ReturnBB->getInstList());
446
447     // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
448     ReturnBB->replaceAllUsesWith(AfterCallBB);
449
450     // Delete the return instruction now and empty ReturnBB now.
451     Returns[0]->eraseFromParent();
452     ReturnBB->eraseFromParent();
453   } else if (!TheCall->use_empty()) {
454     // No returns, but something is using the return value of the call.  Just
455     // nuke the result.
456     TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
457   }
458
459   // Since we are now done with the Call/Invoke, we can delete it.
460   TheCall->eraseFromParent();
461
462   // We should always be able to fold the entry block of the function into the
463   // single predecessor of the block...
464   assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
465   BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
466
467   // Splice the code entry block into calling block, right before the
468   // unconditional branch.
469   OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
470   CalleeEntry->replaceAllUsesWith(OrigBB);  // Update PHI nodes
471
472   // Remove the unconditional branch.
473   OrigBB->getInstList().erase(Br);
474
475   // Now we can remove the CalleeEntry block, which is now empty.
476   Caller->getBasicBlockList().erase(CalleeEntry);
477   
478   return true;
479 }