Fix a bug I noticed by inspection: if the first instruction in the inlined
[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/Support/CallSite.h"
22 using namespace llvm;
23
24 bool llvm::InlineFunction(CallInst *CI) { return InlineFunction(CallSite(CI)); }
25 bool llvm::InlineFunction(InvokeInst *II) {return InlineFunction(CallSite(II));}
26
27 // InlineFunction - This function inlines the called function into the basic
28 // block of the caller.  This returns false if it is not possible to inline this
29 // call.  The program is still in a well defined state if this occurs though.
30 //
31 // Note that this only does one level of inlining.  For example, if the
32 // instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
33 // exists in the instruction stream.  Similiarly this will inline a recursive
34 // function by one level.
35 //
36 bool llvm::InlineFunction(CallSite CS) {
37   Instruction *TheCall = CS.getInstruction();
38   assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
39          "Instruction not in function!");
40
41   const Function *CalledFunc = CS.getCalledFunction();
42   if (CalledFunc == 0 ||          // Can't inline external function or indirect
43       CalledFunc->isExternal() || // call, or call to a vararg function!
44       CalledFunc->getFunctionType()->isVarArg()) return false;
45
46
47   // If the call to the callee is a non-tail call, we must clear the 'tail'
48   // flags on any calls that we inline.
49   bool MustClearTailCallFlags =
50     isa<CallInst>(TheCall) && !cast<CallInst>(TheCall)->isTailCall();
51
52   BasicBlock *OrigBB = TheCall->getParent();
53   Function *Caller = OrigBB->getParent();
54
55   // Get an iterator to the last basic block in the function, which will have
56   // the new function inlined after it.
57   //
58   Function::iterator LastBlock = &Caller->back();
59
60   // Make sure to capture all of the return instructions from the cloned
61   // function.
62   std::vector<ReturnInst*> Returns;
63   { // Scope to destroy ValueMap after cloning.
64     // Calculate the vector of arguments to pass into the function cloner...
65     std::map<const Value*, Value*> ValueMap;
66     assert(std::distance(CalledFunc->arg_begin(), CalledFunc->arg_end()) ==
67            std::distance(CS.arg_begin(), CS.arg_end()) &&
68            "No varargs calls can be inlined!");
69
70     CallSite::arg_iterator AI = CS.arg_begin();
71     for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
72            E = CalledFunc->arg_end(); I != E; ++I, ++AI)
73       ValueMap[I] = *AI;
74
75     // Clone the entire body of the callee into the caller.
76     CloneFunctionInto(Caller, CalledFunc, ValueMap, Returns, ".i");
77   }
78
79   // Remember the first block that is newly cloned over.
80   Function::iterator FirstNewBlock = LastBlock; ++FirstNewBlock;
81
82   // If there are any alloca instructions in the block that used to be the entry
83   // block for the callee, move them to the entry block of the caller.  First
84   // calculate which instruction they should be inserted before.  We insert the
85   // instructions at the end of the current alloca list.
86   //
87   {
88     BasicBlock::iterator InsertPoint = Caller->begin()->begin();
89     for (BasicBlock::iterator I = FirstNewBlock->begin(),
90            E = FirstNewBlock->end(); I != E; )
91       if (AllocaInst *AI = dyn_cast<AllocaInst>(I++))
92         if (isa<Constant>(AI->getArraySize())) {
93           // Scan for the block of allocas that we can move over, and move them
94           // all at once.
95           while (isa<AllocaInst>(I) &&
96                  isa<Constant>(cast<AllocaInst>(I)->getArraySize()))
97             ++I;
98
99           // Transfer all of the allocas over in a block.  Using splice means
100           // that they instructions aren't removed from the symbol table, then
101           // reinserted.
102           Caller->front().getInstList().splice(InsertPoint,
103                                                FirstNewBlock->getInstList(),
104                                                AI, I);
105         }
106   }
107
108   // If we are inlining tail call instruction through an invoke or
109   if (MustClearTailCallFlags) {
110     for (Function::iterator BB = FirstNewBlock, E = Caller->end();
111          BB != E; ++BB)
112       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
113         if (CallInst *CI = dyn_cast<CallInst>(I))
114           CI->setTailCall(false);
115   }
116
117   // If we are inlining for an invoke instruction, we must make sure to rewrite
118   // any inlined 'unwind' instructions into branches to the invoke exception
119   // destination, and call instructions into invoke instructions.
120   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
121     BasicBlock *InvokeDest = II->getUnwindDest();
122     std::vector<Value*> InvokeDestPHIValues;
123
124     // If there are PHI nodes in the exceptional destination block, we need to
125     // keep track of which values came into them from this invoke, then remove
126     // the entry for this block.
127     for (BasicBlock::iterator I = InvokeDest->begin(); isa<PHINode>(I); ++I) {
128       PHINode *PN = cast<PHINode>(I);
129       // Save the value to use for this edge...
130       InvokeDestPHIValues.push_back(PN->getIncomingValueForBlock(OrigBB));
131     }
132
133     for (Function::iterator BB = FirstNewBlock, E = Caller->end();
134          BB != E; ++BB) {
135       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
136         // We only need to check for function calls: inlined invoke instructions
137         // require no special handling...
138         if (CallInst *CI = dyn_cast<CallInst>(I)) {
139           // Convert this function call into an invoke instruction... if it's
140           // not an intrinsic function call (which are known to not unwind).
141           if (CI->getCalledFunction() &&
142               CI->getCalledFunction()->getIntrinsicID()) {
143             ++I;
144           } else {
145             // First, split the basic block...
146             BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
147
148             // Next, create the new invoke instruction, inserting it at the end
149             // of the old basic block.
150             InvokeInst *II =
151               new InvokeInst(CI->getCalledValue(), Split, InvokeDest,
152                             std::vector<Value*>(CI->op_begin()+1, CI->op_end()),
153                              CI->getName(), BB->getTerminator());
154             II->setCallingConv(CI->getCallingConv());
155
156             // Make sure that anything using the call now uses the invoke!
157             CI->replaceAllUsesWith(II);
158
159             // Delete the unconditional branch inserted by splitBasicBlock
160             BB->getInstList().pop_back();
161             Split->getInstList().pop_front();  // Delete the original call
162
163             // Update any PHI nodes in the exceptional block to indicate that
164             // there is now a new entry in them.
165             unsigned i = 0;
166             for (BasicBlock::iterator I = InvokeDest->begin();
167                  isa<PHINode>(I); ++I, ++i) {
168               PHINode *PN = cast<PHINode>(I);
169               PN->addIncoming(InvokeDestPHIValues[i], BB);
170             }
171
172             // This basic block is now complete, start scanning the next one.
173             break;
174           }
175         } else {
176           ++I;
177         }
178       }
179
180       if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
181         // An UnwindInst requires special handling when it gets inlined into an
182         // invoke site.  Once this happens, we know that the unwind would cause
183         // a control transfer to the invoke exception destination, so we can
184         // transform it into a direct branch to the exception destination.
185         new BranchInst(InvokeDest, UI);
186
187         // Delete the unwind instruction!
188         UI->getParent()->getInstList().pop_back();
189
190         // Update any PHI nodes in the exceptional block to indicate that
191         // there is now a new entry in them.
192         unsigned i = 0;
193         for (BasicBlock::iterator I = InvokeDest->begin();
194              isa<PHINode>(I); ++I, ++i) {
195           PHINode *PN = cast<PHINode>(I);
196           PN->addIncoming(InvokeDestPHIValues[i], BB);
197         }
198       }
199     }
200
201     // Now that everything is happy, we have one final detail.  The PHI nodes in
202     // the exception destination block still have entries due to the original
203     // invoke instruction.  Eliminate these entries (which might even delete the
204     // PHI node) now.
205     InvokeDest->removePredecessor(II->getParent());
206   }
207
208   // If we cloned in _exactly one_ basic block, and if that block ends in a
209   // return instruction, we splice the body of the inlined callee directly into
210   // the calling basic block.
211   if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
212     // Move all of the instructions right before the call.
213     OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
214                                  FirstNewBlock->begin(), FirstNewBlock->end());
215     // Remove the cloned basic block.
216     Caller->getBasicBlockList().pop_back();
217
218     // If the call site was an invoke instruction, add a branch to the normal
219     // destination.
220     if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
221       new BranchInst(II->getNormalDest(), TheCall);
222
223     // If the return instruction returned a value, replace uses of the call with
224     // uses of the returned value.
225     if (!TheCall->use_empty())
226       TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
227
228     // Since we are now done with the Call/Invoke, we can delete it.
229     TheCall->getParent()->getInstList().erase(TheCall);
230
231     // Since we are now done with the return instruction, delete it also.
232     Returns[0]->getParent()->getInstList().erase(Returns[0]);
233
234     // We are now done with the inlining.
235     return true;
236   }
237
238   // Otherwise, we have the normal case, of more than one block to inline or
239   // multiple return sites.
240
241   // We want to clone the entire callee function into the hole between the
242   // "starter" and "ender" blocks.  How we accomplish this depends on whether
243   // this is an invoke instruction or a call instruction.
244   BasicBlock *AfterCallBB;
245   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
246
247     // Add an unconditional branch to make this look like the CallInst case...
248     BranchInst *NewBr = new BranchInst(II->getNormalDest(), TheCall);
249
250     // Split the basic block.  This guarantees that no PHI nodes will have to be
251     // updated due to new incoming edges, and make the invoke case more
252     // symmetric to the call case.
253     AfterCallBB = OrigBB->splitBasicBlock(NewBr,
254                                           CalledFunc->getName()+".exit");
255
256   } else {  // It's a call
257     // If this is a call instruction, we need to split the basic block that
258     // the call lives in.
259     //
260     AfterCallBB = OrigBB->splitBasicBlock(TheCall,
261                                           CalledFunc->getName()+".exit");
262   }
263
264   // Change the branch that used to go to AfterCallBB to branch to the first
265   // basic block of the inlined function.
266   //
267   TerminatorInst *Br = OrigBB->getTerminator();
268   assert(Br && Br->getOpcode() == Instruction::Br &&
269          "splitBasicBlock broken!");
270   Br->setOperand(0, FirstNewBlock);
271
272
273   // Now that the function is correct, make it a little bit nicer.  In
274   // particular, move the basic blocks inserted from the end of the function
275   // into the space made by splitting the source basic block.
276   //
277   Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
278                                      FirstNewBlock, Caller->end());
279
280   // Handle all of the return instructions that we just cloned in, and eliminate
281   // any users of the original call/invoke instruction.
282   if (Returns.size() > 1) {
283     // The PHI node should go at the front of the new basic block to merge all
284     // possible incoming values.
285     //
286     PHINode *PHI = 0;
287     if (!TheCall->use_empty()) {
288       PHI = new PHINode(CalledFunc->getReturnType(),
289                         TheCall->getName(), AfterCallBB->begin());
290
291       // Anything that used the result of the function call should now use the
292       // PHI node as their operand.
293       //
294       TheCall->replaceAllUsesWith(PHI);
295     }
296
297     // Loop over all of the return instructions, turning them into unconditional
298     // branches to the merge point now, and adding entries to the PHI node as
299     // appropriate.
300     for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
301       ReturnInst *RI = Returns[i];
302
303       if (PHI) {
304         assert(RI->getReturnValue() && "Ret should have value!");
305         assert(RI->getReturnValue()->getType() == PHI->getType() &&
306                "Ret value not consistent in function!");
307         PHI->addIncoming(RI->getReturnValue(), RI->getParent());
308       }
309
310       // Add a branch to the merge point where the PHI node lives if it exists.
311       new BranchInst(AfterCallBB, RI);
312
313       // Delete the return instruction now
314       RI->getParent()->getInstList().erase(RI);
315     }
316
317   } else if (!Returns.empty()) {
318     // Otherwise, if there is exactly one return value, just replace anything
319     // using the return value of the call with the computed value.
320     if (!TheCall->use_empty())
321       TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
322
323     // Splice the code from the return block into the block that it will return
324     // to, which contains the code that was after the call.
325     BasicBlock *ReturnBB = Returns[0]->getParent();
326     AfterCallBB->getInstList().splice(AfterCallBB->begin(),
327                                       ReturnBB->getInstList());
328
329     // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
330     ReturnBB->replaceAllUsesWith(AfterCallBB);
331
332     // Delete the return instruction now and empty ReturnBB now.
333     Returns[0]->eraseFromParent();
334     ReturnBB->eraseFromParent();
335   } else if (!TheCall->use_empty()) {
336     // No returns, but something is using the return value of the call.  Just
337     // nuke the result.
338     TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
339   }
340
341   // Since we are now done with the Call/Invoke, we can delete it.
342   TheCall->eraseFromParent();
343
344   // We should always be able to fold the entry block of the function into the
345   // single predecessor of the block...
346   assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
347   BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
348
349   // Splice the code entry block into calling block, right before the
350   // unconditional branch.
351   OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
352   CalleeEntry->replaceAllUsesWith(OrigBB);  // Update PHI nodes
353
354   // Remove the unconditional branch.
355   OrigBB->getInstList().erase(Br);
356
357   // Now we can remove the CalleeEntry block, which is now empty.
358   Caller->getBasicBlockList().erase(CalleeEntry);
359   return true;
360 }