blob: 8edf9d071b15a97c1cd0c276dc0e7ef510e72b03 [file] [log] [blame]
Chris Lattnerca398dc2003-05-29 15:11:31 +00001//===- InlineFunction.cpp - Code to perform function inlining -------------===//
John Criswellb576c942003-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 Lattnerca398dc2003-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 Lattner5052c912004-02-04 01:41:09 +000014// into alloca/dealloca pairs! Or perhaps it should refuse to inline them!
Chris Lattnerca398dc2003-05-29 15:11:31 +000015//
16//===----------------------------------------------------------------------===//
17
18#include "llvm/Transforms/Utils/Cloning.h"
Chris Lattner80a38d22003-08-24 06:59:16 +000019#include "llvm/Constant.h"
Chris Lattner7152c232003-08-24 04:06:56 +000020#include "llvm/DerivedTypes.h"
Chris Lattnerca398dc2003-05-29 15:11:31 +000021#include "llvm/Module.h"
Chris Lattner80a38d22003-08-24 06:59:16 +000022#include "llvm/Instructions.h"
23#include "llvm/Intrinsics.h"
24#include "llvm/Support/CallSite.h"
Chris Lattner7152c232003-08-24 04:06:56 +000025#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerf7703df2004-01-09 06:12:26 +000026using namespace llvm;
Chris Lattnerca398dc2003-05-29 15:11:31 +000027
Chris Lattnerf7703df2004-01-09 06:12:26 +000028bool llvm::InlineFunction(CallInst *CI) { return InlineFunction(CallSite(CI)); }
29bool llvm::InlineFunction(InvokeInst *II) {return InlineFunction(CallSite(II));}
Chris Lattner80a38d22003-08-24 06:59:16 +000030
Chris Lattnerca398dc2003-05-29 15:11:31 +000031// InlineFunction - This function inlines the called function into the basic
32// block of the caller. This returns false if it is not possible to inline this
33// call. The program is still in a well defined state if this occurs though.
34//
35// Note that this only does one level of inlining. For example, if the
36// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
37// exists in the instruction stream. Similiarly this will inline a recursive
38// function by one level.
39//
Chris Lattnerf7703df2004-01-09 06:12:26 +000040bool llvm::InlineFunction(CallSite CS) {
Chris Lattner80a38d22003-08-24 06:59:16 +000041 Instruction *TheCall = CS.getInstruction();
42 assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
43 "Instruction not in function!");
Chris Lattnerca398dc2003-05-29 15:11:31 +000044
Chris Lattner80a38d22003-08-24 06:59:16 +000045 const Function *CalledFunc = CS.getCalledFunction();
Chris Lattnerca398dc2003-05-29 15:11:31 +000046 if (CalledFunc == 0 || // Can't inline external function or indirect
47 CalledFunc->isExternal() || // call, or call to a vararg function!
48 CalledFunc->getFunctionType()->isVarArg()) return false;
49
Chris Lattner80a38d22003-08-24 06:59:16 +000050 BasicBlock *OrigBB = TheCall->getParent();
Chris Lattnerca398dc2003-05-29 15:11:31 +000051 Function *Caller = OrigBB->getParent();
52
Chris Lattner5052c912004-02-04 01:41:09 +000053 // Get an iterator to the last basic block in the function, which will have
54 // the new function inlined after it.
55 //
56 Function::iterator LastBlock = &Caller->back();
57
Chris Lattner5e923de2004-02-04 02:51:48 +000058 // Make sure to capture all of the return instructions from the cloned
Chris Lattnerca398dc2003-05-29 15:11:31 +000059 // function.
Chris Lattner5e923de2004-02-04 02:51:48 +000060 std::vector<ReturnInst*> Returns;
61 { // Scope to destroy ValueMap after cloning.
62 // Calculate the vector of arguments to pass into the function cloner...
63 std::map<const Value*, Value*> ValueMap;
64 assert(std::distance(CalledFunc->abegin(), CalledFunc->aend()) ==
65 std::distance(CS.arg_begin(), CS.arg_end()) &&
66 "No varargs calls can be inlined!");
67
68 CallSite::arg_iterator AI = CS.arg_begin();
69 for (Function::const_aiterator I = CalledFunc->abegin(),
70 E = CalledFunc->aend(); I != E; ++I, ++AI)
71 ValueMap[I] = *AI;
72
73 // Clone the entire body of the callee into the caller.
74 CloneFunctionInto(Caller, CalledFunc, ValueMap, Returns, ".i");
75 }
Chris Lattnerc1df7e12004-02-04 21:33:42 +000076
Chris Lattner5e923de2004-02-04 02:51:48 +000077 // Remember the first block that is newly cloned over.
78 Function::iterator FirstNewBlock = LastBlock; ++FirstNewBlock;
Chris Lattnerca398dc2003-05-29 15:11:31 +000079
80 // If there are any alloca instructions in the block that used to be the entry
81 // block for the callee, move them to the entry block of the caller. First
82 // calculate which instruction they should be inserted before. We insert the
83 // instructions at the end of the current alloca list.
84 //
Chris Lattner5e923de2004-02-04 02:51:48 +000085 if (isa<AllocaInst>(FirstNewBlock->begin())) {
Chris Lattner80a38d22003-08-24 06:59:16 +000086 BasicBlock::iterator InsertPoint = Caller->begin()->begin();
Chris Lattner5e923de2004-02-04 02:51:48 +000087 for (BasicBlock::iterator I = FirstNewBlock->begin(),
88 E = FirstNewBlock->end(); I != E; )
Chris Lattnerf775f952003-10-14 01:11:07 +000089 if (AllocaInst *AI = dyn_cast<AllocaInst>(I++))
90 if (isa<Constant>(AI->getArraySize())) {
Chris Lattnerc1df7e12004-02-04 21:33:42 +000091 // Scan for the block of allocas that we can move over.
92 while (isa<AllocaInst>(I) &&
93 isa<Constant>(cast<AllocaInst>(I)->getArraySize()))
94 ++I;
95
96 // Transfer all of the allocas over in a block. Using splice means
97 // that they instructions aren't removed from the symbol table, then
98 // reinserted.
99 Caller->front().getInstList().splice(InsertPoint,
100 FirstNewBlock->getInstList(),
101 AI, I);
Chris Lattnerf775f952003-10-14 01:11:07 +0000102 }
Chris Lattner80a38d22003-08-24 06:59:16 +0000103 }
Chris Lattnerca398dc2003-05-29 15:11:31 +0000104
Chris Lattner5e923de2004-02-04 02:51:48 +0000105 // If we are inlining for an invoke instruction, we must make sure to rewrite
106 // any inlined 'unwind' instructions into branches to the invoke exception
107 // destination, and call instructions into invoke instructions.
108 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
109 BasicBlock *InvokeDest = II->getExceptionalDest();
110 std::vector<Value*> InvokeDestPHIValues;
111
112 // If there are PHI nodes in the exceptional destination block, we need to
113 // keep track of which values came into them from this invoke, then remove
114 // the entry for this block.
115 for (BasicBlock::iterator I = InvokeDest->begin();
116 PHINode *PN = dyn_cast<PHINode>(I); ++I)
117 // Save the value to use for this edge...
118 InvokeDestPHIValues.push_back(PN->getIncomingValueForBlock(OrigBB));
119
120 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
121 BB != E; ++BB) {
Chris Lattner80a38d22003-08-24 06:59:16 +0000122 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
123 // We only need to check for function calls: inlined invoke instructions
124 // require no special handling...
125 if (CallInst *CI = dyn_cast<CallInst>(I)) {
Chris Lattnere4d90962003-09-08 19:00:30 +0000126 // Convert this function call into an invoke instruction...
Chris Lattner80a38d22003-08-24 06:59:16 +0000127
Chris Lattnere4d90962003-09-08 19:00:30 +0000128 // First, split the basic block...
129 BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
130
131 // Next, create the new invoke instruction, inserting it at the end
132 // of the old basic block.
Chris Lattnere07007c2003-09-15 02:10:16 +0000133 InvokeInst *II =
134 new InvokeInst(CI->getCalledValue(), Split, InvokeDest,
135 std::vector<Value*>(CI->op_begin()+1, CI->op_end()),
136 CI->getName(), BB->getTerminator());
137
138 // Make sure that anything using the call now uses the invoke!
139 CI->replaceAllUsesWith(II);
140
Chris Lattnere4d90962003-09-08 19:00:30 +0000141 // Delete the unconditional branch inserted by splitBasicBlock
142 BB->getInstList().pop_back();
143 Split->getInstList().pop_front(); // Delete the original call
144
Chris Lattner51d68162003-09-22 21:59:27 +0000145 // Update any PHI nodes in the exceptional block to indicate that
146 // there is now a new entry in them.
147 unsigned i = 0;
148 for (BasicBlock::iterator I = InvokeDest->begin();
149 PHINode *PN = dyn_cast<PHINode>(I); ++I, ++i)
150 PN->addIncoming(InvokeDestPHIValues[i], BB);
151
Chris Lattnere4d90962003-09-08 19:00:30 +0000152 // This basic block is now complete, start scanning the next one.
153 break;
Chris Lattner80a38d22003-08-24 06:59:16 +0000154 } else {
155 ++I;
156 }
157 }
Chris Lattnerca398dc2003-05-29 15:11:31 +0000158
Chris Lattneree5457c2003-09-08 19:44:26 +0000159 if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
160 // An UnwindInst requires special handling when it gets inlined into an
161 // invoke site. Once this happens, we know that the unwind would cause
162 // a control transfer to the invoke exception destination, so we can
163 // transform it into a direct branch to the exception destination.
Chris Lattnerf8485c62003-11-20 18:25:24 +0000164 new BranchInst(InvokeDest, UI);
Chris Lattneree5457c2003-09-08 19:44:26 +0000165
166 // Delete the unwind instruction!
167 UI->getParent()->getInstList().pop_back();
Chris Lattner198f4502003-10-27 05:33:09 +0000168
169 // Update any PHI nodes in the exceptional block to indicate that
170 // there is now a new entry in them.
171 unsigned i = 0;
172 for (BasicBlock::iterator I = InvokeDest->begin();
173 PHINode *PN = dyn_cast<PHINode>(I); ++I, ++i)
174 PN->addIncoming(InvokeDestPHIValues[i], BB);
Chris Lattneree5457c2003-09-08 19:44:26 +0000175 }
176 }
177
Chris Lattner51d68162003-09-22 21:59:27 +0000178 // Now that everything is happy, we have one final detail. The PHI nodes in
179 // the exception destination block still have entries due to the original
180 // invoke instruction. Eliminate these entries (which might even delete the
181 // PHI node) now.
Chris Lattner5e923de2004-02-04 02:51:48 +0000182 InvokeDest->removePredecessor(II->getParent());
Chris Lattner51d68162003-09-22 21:59:27 +0000183 }
Chris Lattner5e923de2004-02-04 02:51:48 +0000184
Chris Lattner44a68072004-02-04 04:17:06 +0000185 // If we cloned in _exactly one_ basic block, and if that block ends in a
186 // return instruction, we splice the body of the inlined callee directly into
187 // the calling basic block.
188 if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
189 // Move all of the instructions right before the call.
190 OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
191 FirstNewBlock->begin(), FirstNewBlock->end());
192 // Remove the cloned basic block.
193 Caller->getBasicBlockList().pop_back();
194
195 // If the call site was an invoke instruction, add a branch to the normal
196 // destination.
197 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
198 new BranchInst(II->getNormalDest(), TheCall);
199
200 // If the return instruction returned a value, replace uses of the call with
201 // uses of the returned value.
202 if (!TheCall->use_empty())
203 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
204
205 // Since we are now done with the Call/Invoke, we can delete it.
206 TheCall->getParent()->getInstList().erase(TheCall);
207
208 // Since we are now done with the return instruction, delete it also.
209 Returns[0]->getParent()->getInstList().erase(Returns[0]);
210
211 // We are now done with the inlining.
212 return true;
213 }
214
215 // Otherwise, we have the normal case, of more than one block to inline or
216 // multiple return sites.
217
Chris Lattner5e923de2004-02-04 02:51:48 +0000218 // We want to clone the entire callee function into the hole between the
219 // "starter" and "ender" blocks. How we accomplish this depends on whether
220 // this is an invoke instruction or a call instruction.
221 BasicBlock *AfterCallBB;
222 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
Chris Lattner44a68072004-02-04 04:17:06 +0000223
Chris Lattner5e923de2004-02-04 02:51:48 +0000224 // Add an unconditional branch to make this look like the CallInst case...
225 BranchInst *NewBr = new BranchInst(II->getNormalDest(), TheCall);
Chris Lattner44a68072004-02-04 04:17:06 +0000226
Chris Lattner5e923de2004-02-04 02:51:48 +0000227 // Split the basic block. This guarantees that no PHI nodes will have to be
228 // updated due to new incoming edges, and make the invoke case more
229 // symmetric to the call case.
230 AfterCallBB = OrigBB->splitBasicBlock(NewBr,
231 CalledFunc->getName()+".entry");
Chris Lattner44a68072004-02-04 04:17:06 +0000232
Chris Lattner5e923de2004-02-04 02:51:48 +0000233 } else { // It's a call
Chris Lattner44a68072004-02-04 04:17:06 +0000234 // If this is a call instruction, we need to split the basic block that
235 // the call lives in.
Chris Lattner5e923de2004-02-04 02:51:48 +0000236 //
237 AfterCallBB = OrigBB->splitBasicBlock(TheCall,
238 CalledFunc->getName()+".entry");
Chris Lattner5e923de2004-02-04 02:51:48 +0000239 }
240
Chris Lattner44a68072004-02-04 04:17:06 +0000241 // Change the branch that used to go to AfterCallBB to branch to the first
242 // basic block of the inlined function.
243 //
244 TerminatorInst *Br = OrigBB->getTerminator();
245 assert(Br && Br->getOpcode() == Instruction::Br &&
246 "splitBasicBlock broken!");
247 Br->setOperand(0, FirstNewBlock);
248
249
250 // Now that the function is correct, make it a little bit nicer. In
251 // particular, move the basic blocks inserted from the end of the function
252 // into the space made by splitting the source basic block.
253 //
254 Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
255 FirstNewBlock, Caller->end());
256
Chris Lattner5e923de2004-02-04 02:51:48 +0000257 // Handle all of the return instructions that we just cloned in, and eliminate
258 // any users of the original call/invoke instruction.
259 if (Returns.size() > 1) {
260 // The PHI node should go at the front of the new basic block to merge all
261 // possible incoming values.
262 //
263 PHINode *PHI = 0;
264 if (!TheCall->use_empty()) {
265 PHI = new PHINode(CalledFunc->getReturnType(),
266 TheCall->getName(), AfterCallBB->begin());
Chris Lattner44a68072004-02-04 04:17:06 +0000267
Chris Lattner5e923de2004-02-04 02:51:48 +0000268 // Anything that used the result of the function call should now use the
269 // PHI node as their operand.
270 //
271 TheCall->replaceAllUsesWith(PHI);
272 }
Chris Lattner44a68072004-02-04 04:17:06 +0000273
Chris Lattner5e923de2004-02-04 02:51:48 +0000274 // Loop over all of the return instructions, turning them into unconditional
275 // branches to the merge point now, and adding entries to the PHI node as
276 // appropriate.
277 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
278 ReturnInst *RI = Returns[i];
Chris Lattner44a68072004-02-04 04:17:06 +0000279
Chris Lattner5e923de2004-02-04 02:51:48 +0000280 if (PHI) {
281 assert(RI->getReturnValue() && "Ret should have value!");
282 assert(RI->getReturnValue()->getType() == PHI->getType() &&
283 "Ret value not consistent in function!");
284 PHI->addIncoming(RI->getReturnValue(), RI->getParent());
285 }
Chris Lattner44a68072004-02-04 04:17:06 +0000286
Chris Lattner5e923de2004-02-04 02:51:48 +0000287 // Add a branch to the merge point where the PHI node lives if it exists.
288 new BranchInst(AfterCallBB, RI);
Chris Lattner44a68072004-02-04 04:17:06 +0000289
Chris Lattner5e923de2004-02-04 02:51:48 +0000290 // Delete the return instruction now
291 RI->getParent()->getInstList().erase(RI);
292 }
Chris Lattner44a68072004-02-04 04:17:06 +0000293
Chris Lattner5e923de2004-02-04 02:51:48 +0000294 } else if (!Returns.empty()) {
295 // Otherwise, if there is exactly one return value, just replace anything
296 // using the return value of the call with the computed value.
297 if (!TheCall->use_empty())
298 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
Chris Lattner44a68072004-02-04 04:17:06 +0000299
Chris Lattner5e923de2004-02-04 02:51:48 +0000300 // Add a branch to the merge point where the PHI node lives if it exists.
301 new BranchInst(AfterCallBB, Returns[0]);
Chris Lattner44a68072004-02-04 04:17:06 +0000302
Chris Lattner5e923de2004-02-04 02:51:48 +0000303 // Delete the return instruction now
304 Returns[0]->getParent()->getInstList().erase(Returns[0]);
305 }
Chris Lattner44a68072004-02-04 04:17:06 +0000306
Chris Lattner5e923de2004-02-04 02:51:48 +0000307 // Since we are now done with the Call/Invoke, we can delete it.
Chris Lattner44a68072004-02-04 04:17:06 +0000308 TheCall->getParent()->getInstList().erase(TheCall);
Chris Lattnerca398dc2003-05-29 15:11:31 +0000309
Chris Lattner7152c232003-08-24 04:06:56 +0000310 // We should always be able to fold the entry block of the function into the
311 // single predecessor of the block...
Chris Lattner44a68072004-02-04 04:17:06 +0000312 assert(cast<BranchInst>(Br)->isUnconditional() &&"splitBasicBlock broken!");
Chris Lattner7152c232003-08-24 04:06:56 +0000313 BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
314 SimplifyCFG(CalleeEntry);
Chris Lattner44a68072004-02-04 04:17:06 +0000315
Chris Lattner7152c232003-08-24 04:06:56 +0000316 // Okay, continue the CFG cleanup. It's often the case that there is only a
317 // single return instruction in the callee function. If this is the case,
Chris Lattner80a38d22003-08-24 06:59:16 +0000318 // then we have an unconditional branch from the return block to the
319 // 'AfterCallBB'. Check for this case, and eliminate the branch is possible.
320 SimplifyCFG(AfterCallBB);
Chris Lattner44a68072004-02-04 04:17:06 +0000321
Chris Lattnerca398dc2003-05-29 15:11:31 +0000322 return true;
323}