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