blob: 51fbd14ebf161594375b36d0b3c310ad784e0c61 [file] [log] [blame]
Chris Lattner530d4bf2003-05-29 15:11:31 +00001//===- InlineFunction.cpp - Code to perform function inlining -------------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
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//===----------------------------------------------------------------------===//
Chris Lattner530d4bf2003-05-29 15:11:31 +00009//
10// This file implements inlining of a function into a call site, resolving
11// parameters and the return value as appropriate.
12//
13// FIXME: This pass should transform alloca instructions in the called function
Chris Lattner9fc977e2004-02-04 01:41:09 +000014// into alloca/dealloca pairs! Or perhaps it should refuse to inline them!
Chris Lattner530d4bf2003-05-29 15:11:31 +000015//
16//===----------------------------------------------------------------------===//
17
18#include "llvm/Transforms/Utils/Cloning.h"
Chris Lattner0cc265e2003-08-24 06:59:16 +000019#include "llvm/Constant.h"
Chris Lattnerfc3fe5c2003-08-24 04:06:56 +000020#include "llvm/DerivedTypes.h"
Chris Lattner530d4bf2003-05-29 15:11:31 +000021#include "llvm/Module.h"
Chris Lattner0cc265e2003-08-24 06:59:16 +000022#include "llvm/Instructions.h"
23#include "llvm/Intrinsics.h"
24#include "llvm/Support/CallSite.h"
Chris Lattnerdf3c3422004-01-09 06:12:26 +000025using namespace llvm;
Chris Lattner530d4bf2003-05-29 15:11:31 +000026
Chris Lattnerdf3c3422004-01-09 06:12:26 +000027bool llvm::InlineFunction(CallInst *CI) { return InlineFunction(CallSite(CI)); }
28bool llvm::InlineFunction(InvokeInst *II) {return InlineFunction(CallSite(II));}
Chris Lattner0cc265e2003-08-24 06:59:16 +000029
Chris Lattner530d4bf2003-05-29 15:11:31 +000030// InlineFunction - This function inlines the called function into the basic
31// block of the caller. This returns false if it is not possible to inline this
32// call. The program is still in a well defined state if this occurs though.
33//
34// Note that this only does one level of inlining. For example, if the
35// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
36// exists in the instruction stream. Similiarly this will inline a recursive
37// function by one level.
38//
Chris Lattnerdf3c3422004-01-09 06:12:26 +000039bool llvm::InlineFunction(CallSite CS) {
Chris Lattner0cc265e2003-08-24 06:59:16 +000040 Instruction *TheCall = CS.getInstruction();
41 assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
42 "Instruction not in function!");
Chris Lattner530d4bf2003-05-29 15:11:31 +000043
Chris Lattner0cc265e2003-08-24 06:59:16 +000044 const Function *CalledFunc = CS.getCalledFunction();
Chris Lattner530d4bf2003-05-29 15:11:31 +000045 if (CalledFunc == 0 || // Can't inline external function or indirect
46 CalledFunc->isExternal() || // call, or call to a vararg function!
47 CalledFunc->getFunctionType()->isVarArg()) return false;
48
Chris Lattner0cc265e2003-08-24 06:59:16 +000049 BasicBlock *OrigBB = TheCall->getParent();
Chris Lattner530d4bf2003-05-29 15:11:31 +000050 Function *Caller = OrigBB->getParent();
51
Chris Lattner9fc977e2004-02-04 01:41:09 +000052 // Get an iterator to the last basic block in the function, which will have
53 // the new function inlined after it.
54 //
55 Function::iterator LastBlock = &Caller->back();
56
Chris Lattner18ef3fd2004-02-04 02:51:48 +000057 // Make sure to capture all of the return instructions from the cloned
Chris Lattner530d4bf2003-05-29 15:11:31 +000058 // function.
Chris Lattner18ef3fd2004-02-04 02:51:48 +000059 std::vector<ReturnInst*> Returns;
60 { // Scope to destroy ValueMap after cloning.
61 // Calculate the vector of arguments to pass into the function cloner...
62 std::map<const Value*, Value*> ValueMap;
63 assert(std::distance(CalledFunc->abegin(), CalledFunc->aend()) ==
64 std::distance(CS.arg_begin(), CS.arg_end()) &&
65 "No varargs calls can be inlined!");
66
67 CallSite::arg_iterator AI = CS.arg_begin();
68 for (Function::const_aiterator I = CalledFunc->abegin(),
69 E = CalledFunc->aend(); I != E; ++I, ++AI)
70 ValueMap[I] = *AI;
71
72 // Clone the entire body of the callee into the caller.
73 CloneFunctionInto(Caller, CalledFunc, ValueMap, Returns, ".i");
74 }
Chris Lattner6f8865b2004-02-04 21:33:42 +000075
Chris Lattner18ef3fd2004-02-04 02:51:48 +000076 // Remember the first block that is newly cloned over.
77 Function::iterator FirstNewBlock = LastBlock; ++FirstNewBlock;
Chris Lattner530d4bf2003-05-29 15:11:31 +000078
79 // If there are any alloca instructions in the block that used to be the entry
80 // block for the callee, move them to the entry block of the caller. First
81 // calculate which instruction they should be inserted before. We insert the
82 // instructions at the end of the current alloca list.
83 //
Chris Lattner18ef3fd2004-02-04 02:51:48 +000084 if (isa<AllocaInst>(FirstNewBlock->begin())) {
Chris Lattner0cc265e2003-08-24 06:59:16 +000085 BasicBlock::iterator InsertPoint = Caller->begin()->begin();
Chris Lattner18ef3fd2004-02-04 02:51:48 +000086 for (BasicBlock::iterator I = FirstNewBlock->begin(),
87 E = FirstNewBlock->end(); I != E; )
Chris Lattnerb4778c72003-10-14 01:11:07 +000088 if (AllocaInst *AI = dyn_cast<AllocaInst>(I++))
89 if (isa<Constant>(AI->getArraySize())) {
Chris Lattner6f8865b2004-02-04 21:33:42 +000090 // Scan for the block of allocas that we can move over.
91 while (isa<AllocaInst>(I) &&
92 isa<Constant>(cast<AllocaInst>(I)->getArraySize()))
93 ++I;
94
95 // Transfer all of the allocas over in a block. Using splice means
96 // that they instructions aren't removed from the symbol table, then
97 // reinserted.
98 Caller->front().getInstList().splice(InsertPoint,
99 FirstNewBlock->getInstList(),
100 AI, I);
Chris Lattnerb4778c72003-10-14 01:11:07 +0000101 }
Chris Lattner0cc265e2003-08-24 06:59:16 +0000102 }
Chris Lattner530d4bf2003-05-29 15:11:31 +0000103
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000104 // If we are inlining for an invoke instruction, we must make sure to rewrite
105 // any inlined 'unwind' instructions into branches to the invoke exception
106 // destination, and call instructions into invoke instructions.
107 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +0000108 BasicBlock *InvokeDest = II->getUnwindDest();
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000109 std::vector<Value*> InvokeDestPHIValues;
110
111 // If there are PHI nodes in the exceptional destination block, we need to
112 // keep track of which values came into them from this invoke, then remove
113 // the entry for this block.
114 for (BasicBlock::iterator I = InvokeDest->begin();
115 PHINode *PN = dyn_cast<PHINode>(I); ++I)
116 // Save the value to use for this edge...
117 InvokeDestPHIValues.push_back(PN->getIncomingValueForBlock(OrigBB));
118
119 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
120 BB != E; ++BB) {
Chris Lattner0cc265e2003-08-24 06:59:16 +0000121 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
122 // We only need to check for function calls: inlined invoke instructions
123 // require no special handling...
124 if (CallInst *CI = dyn_cast<CallInst>(I)) {
Chris Lattner283ffdf2004-02-13 16:47:35 +0000125 // Convert this function call into an invoke instruction... if it's
126 // not an intrinsic function call (which are known to not throw).
127 if (CI->getCalledFunction() &&
128 CI->getCalledFunction()->getIntrinsicID()) {
129 ++I;
130 } else {
131 // First, split the basic block...
132 BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
133
134 // Next, create the new invoke instruction, inserting it at the end
135 // of the old basic block.
136 InvokeInst *II =
137 new InvokeInst(CI->getCalledValue(), Split, InvokeDest,
138 std::vector<Value*>(CI->op_begin()+1, CI->op_end()),
139 CI->getName(), BB->getTerminator());
Chris Lattner0cc265e2003-08-24 06:59:16 +0000140
Chris Lattner283ffdf2004-02-13 16:47:35 +0000141 // Make sure that anything using the call now uses the invoke!
142 CI->replaceAllUsesWith(II);
143
144 // Delete the unconditional branch inserted by splitBasicBlock
145 BB->getInstList().pop_back();
146 Split->getInstList().pop_front(); // Delete the original call
147
148 // Update any PHI nodes in the exceptional block to indicate that
149 // there is now a new entry in them.
150 unsigned i = 0;
151 for (BasicBlock::iterator I = InvokeDest->begin();
152 PHINode *PN = dyn_cast<PHINode>(I); ++I, ++i)
153 PN->addIncoming(InvokeDestPHIValues[i], BB);
154
155 // This basic block is now complete, start scanning the next one.
156 break;
157 }
Chris Lattner0cc265e2003-08-24 06:59:16 +0000158 } else {
159 ++I;
160 }
161 }
Chris Lattner530d4bf2003-05-29 15:11:31 +0000162
Chris Lattner04ecefe2003-09-08 19:44:26 +0000163 if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
164 // An UnwindInst requires special handling when it gets inlined into an
165 // invoke site. Once this happens, we know that the unwind would cause
166 // a control transfer to the invoke exception destination, so we can
167 // transform it into a direct branch to the exception destination.
Chris Lattner2af51722003-11-20 18:25:24 +0000168 new BranchInst(InvokeDest, UI);
Chris Lattner04ecefe2003-09-08 19:44:26 +0000169
170 // Delete the unwind instruction!
171 UI->getParent()->getInstList().pop_back();
Chris Lattnerd9f4ffd2003-10-27 05:33:09 +0000172
173 // Update any PHI nodes in the exceptional block to indicate that
174 // there is now a new entry in them.
175 unsigned i = 0;
176 for (BasicBlock::iterator I = InvokeDest->begin();
177 PHINode *PN = dyn_cast<PHINode>(I); ++I, ++i)
178 PN->addIncoming(InvokeDestPHIValues[i], BB);
Chris Lattner04ecefe2003-09-08 19:44:26 +0000179 }
180 }
181
Chris Lattner0178d262003-09-22 21:59:27 +0000182 // Now that everything is happy, we have one final detail. The PHI nodes in
183 // the exception destination block still have entries due to the original
184 // invoke instruction. Eliminate these entries (which might even delete the
185 // PHI node) now.
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000186 InvokeDest->removePredecessor(II->getParent());
Chris Lattner0178d262003-09-22 21:59:27 +0000187 }
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000188
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000189 // If we cloned in _exactly one_ basic block, and if that block ends in a
190 // return instruction, we splice the body of the inlined callee directly into
191 // the calling basic block.
192 if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
193 // Move all of the instructions right before the call.
194 OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
195 FirstNewBlock->begin(), FirstNewBlock->end());
196 // Remove the cloned basic block.
197 Caller->getBasicBlockList().pop_back();
198
199 // If the call site was an invoke instruction, add a branch to the normal
200 // destination.
201 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
202 new BranchInst(II->getNormalDest(), TheCall);
203
204 // If the return instruction returned a value, replace uses of the call with
205 // uses of the returned value.
206 if (!TheCall->use_empty())
207 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
208
209 // Since we are now done with the Call/Invoke, we can delete it.
210 TheCall->getParent()->getInstList().erase(TheCall);
211
212 // Since we are now done with the return instruction, delete it also.
213 Returns[0]->getParent()->getInstList().erase(Returns[0]);
214
215 // We are now done with the inlining.
216 return true;
217 }
218
219 // Otherwise, we have the normal case, of more than one block to inline or
220 // multiple return sites.
221
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000222 // We want to clone the entire callee function into the hole between the
223 // "starter" and "ender" blocks. How we accomplish this depends on whether
224 // this is an invoke instruction or a call instruction.
225 BasicBlock *AfterCallBB;
226 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000227
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000228 // Add an unconditional branch to make this look like the CallInst case...
229 BranchInst *NewBr = new BranchInst(II->getNormalDest(), TheCall);
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000230
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000231 // Split the basic block. This guarantees that no PHI nodes will have to be
232 // updated due to new incoming edges, and make the invoke case more
233 // symmetric to the call case.
234 AfterCallBB = OrigBB->splitBasicBlock(NewBr,
235 CalledFunc->getName()+".entry");
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000236
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000237 } else { // It's a call
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000238 // If this is a call instruction, we need to split the basic block that
239 // the call lives in.
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000240 //
241 AfterCallBB = OrigBB->splitBasicBlock(TheCall,
242 CalledFunc->getName()+".entry");
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000243 }
244
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000245 // Change the branch that used to go to AfterCallBB to branch to the first
246 // basic block of the inlined function.
247 //
248 TerminatorInst *Br = OrigBB->getTerminator();
249 assert(Br && Br->getOpcode() == Instruction::Br &&
250 "splitBasicBlock broken!");
251 Br->setOperand(0, FirstNewBlock);
252
253
254 // Now that the function is correct, make it a little bit nicer. In
255 // particular, move the basic blocks inserted from the end of the function
256 // into the space made by splitting the source basic block.
257 //
258 Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
259 FirstNewBlock, Caller->end());
260
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000261 // Handle all of the return instructions that we just cloned in, and eliminate
262 // any users of the original call/invoke instruction.
263 if (Returns.size() > 1) {
264 // The PHI node should go at the front of the new basic block to merge all
265 // possible incoming values.
266 //
267 PHINode *PHI = 0;
268 if (!TheCall->use_empty()) {
269 PHI = new PHINode(CalledFunc->getReturnType(),
270 TheCall->getName(), AfterCallBB->begin());
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000271
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000272 // Anything that used the result of the function call should now use the
273 // PHI node as their operand.
274 //
275 TheCall->replaceAllUsesWith(PHI);
276 }
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000277
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000278 // Loop over all of the return instructions, turning them into unconditional
279 // branches to the merge point now, and adding entries to the PHI node as
280 // appropriate.
281 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
282 ReturnInst *RI = Returns[i];
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000283
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000284 if (PHI) {
285 assert(RI->getReturnValue() && "Ret should have value!");
286 assert(RI->getReturnValue()->getType() == PHI->getType() &&
287 "Ret value not consistent in function!");
288 PHI->addIncoming(RI->getReturnValue(), RI->getParent());
289 }
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000290
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000291 // Add a branch to the merge point where the PHI node lives if it exists.
292 new BranchInst(AfterCallBB, RI);
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000293
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000294 // Delete the return instruction now
295 RI->getParent()->getInstList().erase(RI);
296 }
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000297
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000298 } else if (!Returns.empty()) {
299 // Otherwise, if there is exactly one return value, just replace anything
300 // using the return value of the call with the computed value.
301 if (!TheCall->use_empty())
302 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000303
Chris Lattner0328d752004-04-16 05:17:59 +0000304 // Splice the code from the return block into the block that it will return
305 // to, which contains the code that was after the call.
306 BasicBlock *ReturnBB = Returns[0]->getParent();
Chris Lattner45b50d12004-07-20 05:45:24 +0000307 AfterCallBB->getInstList().splice(AfterCallBB->begin(),
308 ReturnBB->getInstList());
Chris Lattner0328d752004-04-16 05:17:59 +0000309
Chris Lattner45b50d12004-07-20 05:45:24 +0000310 // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
311 ReturnBB->replaceAllUsesWith(AfterCallBB);
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000312
Chris Lattner45b50d12004-07-20 05:45:24 +0000313 // Delete the return instruction now and empty ReturnBB now.
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000314 Returns[0]->getParent()->getInstList().erase(Returns[0]);
Chris Lattner45b50d12004-07-20 05:45:24 +0000315 Caller->getBasicBlockList().erase(ReturnBB);
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000316 }
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000317
Chris Lattner18ef3fd2004-02-04 02:51:48 +0000318 // Since we are now done with the Call/Invoke, we can delete it.
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000319 TheCall->getParent()->getInstList().erase(TheCall);
Chris Lattner530d4bf2003-05-29 15:11:31 +0000320
Chris Lattnerfc3fe5c2003-08-24 04:06:56 +0000321 // We should always be able to fold the entry block of the function into the
322 // single predecessor of the block...
Chris Lattner0328d752004-04-16 05:17:59 +0000323 assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
Chris Lattnerfc3fe5c2003-08-24 04:06:56 +0000324 BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
Chris Lattner0fa8c7c2004-02-04 04:17:06 +0000325
Chris Lattner0328d752004-04-16 05:17:59 +0000326 // Splice the code entry block into calling block, right before the
327 // unconditional branch.
328 OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
329 CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
330
331 // Remove the unconditional branch.
332 OrigBB->getInstList().erase(Br);
333
334 // Now we can remove the CalleeEntry block, which is now empty.
335 Caller->getBasicBlockList().erase(CalleeEntry);
Chris Lattner530d4bf2003-05-29 15:11:31 +0000336 return true;
337}