blob: a0fc9bf1cff128169fba0ebb35408afcc6c133ce [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
14// into malloc/free pairs! Or perhaps it should refuse to inline them!
15//
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 Lattnerca398dc2003-05-29 15:11:31 +000026
Brian Gaeked0fde302003-11-11 22:41:34 +000027namespace llvm {
28
Chris Lattner80a38d22003-08-24 06:59:16 +000029bool InlineFunction(CallInst *CI) { return InlineFunction(CallSite(CI)); }
30bool InlineFunction(InvokeInst *II) { return InlineFunction(CallSite(II)); }
31
Chris Lattnerca398dc2003-05-29 15:11:31 +000032// InlineFunction - This function inlines the called function into the basic
33// block of the caller. This returns false if it is not possible to inline this
34// call. The program is still in a well defined state if this occurs though.
35//
36// Note that this only does one level of inlining. For example, if the
37// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
38// exists in the instruction stream. Similiarly this will inline a recursive
39// function by one level.
40//
Chris Lattner80a38d22003-08-24 06:59:16 +000041bool InlineFunction(CallSite CS) {
42 Instruction *TheCall = CS.getInstruction();
43 assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
44 "Instruction not in function!");
Chris Lattnerca398dc2003-05-29 15:11:31 +000045
Chris Lattner80a38d22003-08-24 06:59:16 +000046 const Function *CalledFunc = CS.getCalledFunction();
Chris Lattnerca398dc2003-05-29 15:11:31 +000047 if (CalledFunc == 0 || // Can't inline external function or indirect
48 CalledFunc->isExternal() || // call, or call to a vararg function!
49 CalledFunc->getFunctionType()->isVarArg()) return false;
50
Chris Lattner80a38d22003-08-24 06:59:16 +000051 BasicBlock *OrigBB = TheCall->getParent();
Chris Lattnerca398dc2003-05-29 15:11:31 +000052 Function *Caller = OrigBB->getParent();
53
Chris Lattner80a38d22003-08-24 06:59:16 +000054 // We want to clone the entire callee function into the whole between the
55 // "starter" and "ender" blocks. How we accomplish this depends on whether
56 // this is an invoke instruction or a call instruction.
Chris Lattnerca398dc2003-05-29 15:11:31 +000057
Chris Lattner80a38d22003-08-24 06:59:16 +000058 BasicBlock *InvokeDest = 0; // Exception handling destination
Chris Lattner51d68162003-09-22 21:59:27 +000059 std::vector<Value*> InvokeDestPHIValues; // Values for PHI nodes in InvokeDest
Chris Lattner80a38d22003-08-24 06:59:16 +000060 BasicBlock *AfterCallBB;
Chris Lattner51d68162003-09-22 21:59:27 +000061
Chris Lattner80a38d22003-08-24 06:59:16 +000062 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
Chris Lattner80a38d22003-08-24 06:59:16 +000063 InvokeDest = II->getExceptionalDest();
64
Chris Lattner198f4502003-10-27 05:33:09 +000065 // If there are PHI nodes in the exceptional destination block, we need to
66 // keep track of which values came into them from this invoke, then remove
67 // the entry for this block.
68 for (BasicBlock::iterator I = InvokeDest->begin();
69 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
70 // Save the value to use for this edge...
71 InvokeDestPHIValues.push_back(PN->getIncomingValueForBlock(OrigBB));
72 }
73
Chris Lattner80a38d22003-08-24 06:59:16 +000074 // Add an unconditional branch to make this look like the CallInst case...
Chris Lattnerf98a0842003-09-22 22:35:39 +000075 BranchInst *NewBr = new BranchInst(II->getNormalDest(), TheCall);
76
77 // Split the basic block. This guarantees that no PHI nodes will have to be
78 // updated due to new incoming edges, and make the invoke case more
79 // symmetric to the call case.
80 AfterCallBB = OrigBB->splitBasicBlock(NewBr,
81 CalledFunc->getName()+".entry");
Chris Lattner80a38d22003-08-24 06:59:16 +000082
83 // Remove (unlink) the InvokeInst from the function...
84 OrigBB->getInstList().remove(TheCall);
Chris Lattner51d68162003-09-22 21:59:27 +000085
Chris Lattner80a38d22003-08-24 06:59:16 +000086 } else { // It's a call
87 // If this is a call instruction, we need to split the basic block that the
88 // call lives in.
89 //
90 AfterCallBB = OrigBB->splitBasicBlock(TheCall,
91 CalledFunc->getName()+".entry");
92 // Remove (unlink) the CallInst from the function...
93 AfterCallBB->getInstList().remove(TheCall);
94 }
Chris Lattnerca398dc2003-05-29 15:11:31 +000095
96 // If we have a return value generated by this call, convert it into a PHI
97 // node that gets values from each of the old RET instructions in the original
98 // function.
99 //
100 PHINode *PHI = 0;
Chris Lattner80a38d22003-08-24 06:59:16 +0000101 if (!TheCall->use_empty()) {
Chris Lattnerca398dc2003-05-29 15:11:31 +0000102 // The PHI node should go at the front of the new basic block to merge all
103 // possible incoming values.
104 //
Chris Lattner80a38d22003-08-24 06:59:16 +0000105 PHI = new PHINode(CalledFunc->getReturnType(), TheCall->getName(),
106 AfterCallBB->begin());
Chris Lattnerca398dc2003-05-29 15:11:31 +0000107
108 // Anything that used the result of the function call should now use the PHI
109 // node as their operand.
110 //
Chris Lattner80a38d22003-08-24 06:59:16 +0000111 TheCall->replaceAllUsesWith(PHI);
Chris Lattnerca398dc2003-05-29 15:11:31 +0000112 }
113
114 // Get an iterator to the last basic block in the function, which will have
115 // the new function inlined after it.
116 //
117 Function::iterator LastBlock = &Caller->back();
118
119 // Calculate the vector of arguments to pass into the function cloner...
120 std::map<const Value*, Value*> ValueMap;
Chris Lattner80a38d22003-08-24 06:59:16 +0000121 assert(std::distance(CalledFunc->abegin(), CalledFunc->aend()) ==
122 std::distance(CS.arg_begin(), CS.arg_end()) &&
123 "No varargs calls can be inlined!");
Chris Lattnerca398dc2003-05-29 15:11:31 +0000124
Chris Lattner80a38d22003-08-24 06:59:16 +0000125 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattnerca398dc2003-05-29 15:11:31 +0000126 for (Function::const_aiterator I = CalledFunc->abegin(), E=CalledFunc->aend();
Chris Lattner80a38d22003-08-24 06:59:16 +0000127 I != E; ++I, ++AI)
128 ValueMap[I] = *AI;
Chris Lattnerca398dc2003-05-29 15:11:31 +0000129
Chris Lattner80a38d22003-08-24 06:59:16 +0000130 // Since we are now done with the Call/Invoke, we can delete it.
131 delete TheCall;
Chris Lattnerca398dc2003-05-29 15:11:31 +0000132
133 // Make a vector to capture the return instructions in the cloned function...
134 std::vector<ReturnInst*> Returns;
135
Chris Lattnerca398dc2003-05-29 15:11:31 +0000136 // Do all of the hard part of cloning the callee into the caller...
137 CloneFunctionInto(Caller, CalledFunc, ValueMap, Returns, ".i");
138
139 // Loop over all of the return instructions, turning them into unconditional
140 // branches to the merge point now...
141 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
142 ReturnInst *RI = Returns[i];
143 BasicBlock *BB = RI->getParent();
144
Chris Lattner80a38d22003-08-24 06:59:16 +0000145 // Add a branch to the merge point where the PHI node lives if it exists.
146 new BranchInst(AfterCallBB, RI);
Chris Lattnerca398dc2003-05-29 15:11:31 +0000147
148 if (PHI) { // The PHI node should include this value!
149 assert(RI->getReturnValue() && "Ret should have value!");
150 assert(RI->getReturnValue()->getType() == PHI->getType() &&
151 "Ret value not consistent in function!");
152 PHI->addIncoming(RI->getReturnValue(), BB);
153 }
154
155 // Delete the return instruction now
156 BB->getInstList().erase(RI);
157 }
158
159 // Check to see if the PHI node only has one argument. This is a common
160 // case resulting from there only being a single return instruction in the
161 // function call. Because this is so common, eliminate the PHI node.
162 //
163 if (PHI && PHI->getNumIncomingValues() == 1) {
164 PHI->replaceAllUsesWith(PHI->getIncomingValue(0));
165 PHI->getParent()->getInstList().erase(PHI);
166 }
167
Chris Lattner80a38d22003-08-24 06:59:16 +0000168 // Change the branch that used to go to AfterCallBB to branch to the first
169 // basic block of the inlined function.
Chris Lattnerca398dc2003-05-29 15:11:31 +0000170 //
171 TerminatorInst *Br = OrigBB->getTerminator();
172 assert(Br && Br->getOpcode() == Instruction::Br &&
173 "splitBasicBlock broken!");
174 Br->setOperand(0, ++LastBlock);
175
176 // If there are any alloca instructions in the block that used to be the entry
177 // block for the callee, move them to the entry block of the caller. First
178 // calculate which instruction they should be inserted before. We insert the
179 // instructions at the end of the current alloca list.
180 //
Chris Lattner80a38d22003-08-24 06:59:16 +0000181 if (isa<AllocaInst>(LastBlock->begin())) {
182 BasicBlock::iterator InsertPoint = Caller->begin()->begin();
183 while (isa<AllocaInst>(InsertPoint)) ++InsertPoint;
184
185 for (BasicBlock::iterator I = LastBlock->begin(), E = LastBlock->end();
186 I != E; )
Chris Lattnerf775f952003-10-14 01:11:07 +0000187 if (AllocaInst *AI = dyn_cast<AllocaInst>(I++))
188 if (isa<Constant>(AI->getArraySize())) {
189 LastBlock->getInstList().remove(AI);
190 Caller->front().getInstList().insert(InsertPoint, AI);
191 }
Chris Lattner80a38d22003-08-24 06:59:16 +0000192 }
Chris Lattnerca398dc2003-05-29 15:11:31 +0000193
Chris Lattner80a38d22003-08-24 06:59:16 +0000194 // If we just inlined a call due to an invoke instruction, scan the inlined
195 // function checking for function calls that should now be made into invoke
Chris Lattneree5457c2003-09-08 19:44:26 +0000196 // instructions, and for unwind's which should be turned into branches.
Chris Lattner51d68162003-09-22 21:59:27 +0000197 if (InvokeDest) {
Chris Lattneree5457c2003-09-08 19:44:26 +0000198 for (Function::iterator BB = LastBlock, E = Caller->end(); BB != E; ++BB) {
Chris Lattner80a38d22003-08-24 06:59:16 +0000199 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
200 // We only need to check for function calls: inlined invoke instructions
201 // require no special handling...
202 if (CallInst *CI = dyn_cast<CallInst>(I)) {
Chris Lattnere4d90962003-09-08 19:00:30 +0000203 // Convert this function call into an invoke instruction...
Chris Lattner80a38d22003-08-24 06:59:16 +0000204
Chris Lattnere4d90962003-09-08 19:00:30 +0000205 // First, split the basic block...
206 BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
207
208 // Next, create the new invoke instruction, inserting it at the end
209 // of the old basic block.
Chris Lattnere07007c2003-09-15 02:10:16 +0000210 InvokeInst *II =
211 new InvokeInst(CI->getCalledValue(), Split, InvokeDest,
212 std::vector<Value*>(CI->op_begin()+1, CI->op_end()),
213 CI->getName(), BB->getTerminator());
214
215 // Make sure that anything using the call now uses the invoke!
216 CI->replaceAllUsesWith(II);
217
Chris Lattnere4d90962003-09-08 19:00:30 +0000218 // Delete the unconditional branch inserted by splitBasicBlock
219 BB->getInstList().pop_back();
220 Split->getInstList().pop_front(); // Delete the original call
221
Chris Lattner51d68162003-09-22 21:59:27 +0000222 // Update any PHI nodes in the exceptional block to indicate that
223 // there is now a new entry in them.
224 unsigned i = 0;
225 for (BasicBlock::iterator I = InvokeDest->begin();
226 PHINode *PN = dyn_cast<PHINode>(I); ++I, ++i)
227 PN->addIncoming(InvokeDestPHIValues[i], BB);
228
Chris Lattnere4d90962003-09-08 19:00:30 +0000229 // This basic block is now complete, start scanning the next one.
230 break;
Chris Lattner80a38d22003-08-24 06:59:16 +0000231 } else {
232 ++I;
233 }
234 }
Chris Lattnerca398dc2003-05-29 15:11:31 +0000235
Chris Lattneree5457c2003-09-08 19:44:26 +0000236 if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
237 // An UnwindInst requires special handling when it gets inlined into an
238 // invoke site. Once this happens, we know that the unwind would cause
239 // a control transfer to the invoke exception destination, so we can
240 // transform it into a direct branch to the exception destination.
Chris Lattnerf8485c62003-11-20 18:25:24 +0000241 new BranchInst(InvokeDest, UI);
Chris Lattneree5457c2003-09-08 19:44:26 +0000242
243 // Delete the unwind instruction!
244 UI->getParent()->getInstList().pop_back();
Chris Lattner198f4502003-10-27 05:33:09 +0000245
246 // Update any PHI nodes in the exceptional block to indicate that
247 // there is now a new entry in them.
248 unsigned i = 0;
249 for (BasicBlock::iterator I = InvokeDest->begin();
250 PHINode *PN = dyn_cast<PHINode>(I); ++I, ++i)
251 PN->addIncoming(InvokeDestPHIValues[i], BB);
Chris Lattneree5457c2003-09-08 19:44:26 +0000252 }
253 }
254
Chris Lattner51d68162003-09-22 21:59:27 +0000255 // Now that everything is happy, we have one final detail. The PHI nodes in
256 // the exception destination block still have entries due to the original
257 // invoke instruction. Eliminate these entries (which might even delete the
258 // PHI node) now.
259 for (BasicBlock::iterator I = InvokeDest->begin();
260 PHINode *PN = dyn_cast<PHINode>(I); ++I)
Chris Lattnerdd7036d2003-09-22 23:30:59 +0000261 PN->removeIncomingValue(AfterCallBB);
Chris Lattner51d68162003-09-22 21:59:27 +0000262 }
Chris Lattnerca398dc2003-05-29 15:11:31 +0000263 // Now that the function is correct, make it a little bit nicer. In
264 // particular, move the basic blocks inserted from the end of the function
265 // into the space made by splitting the source basic block.
266 //
Chris Lattner80a38d22003-08-24 06:59:16 +0000267 Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
Chris Lattnerca398dc2003-05-29 15:11:31 +0000268 LastBlock, Caller->end());
269
Chris Lattner7152c232003-08-24 04:06:56 +0000270 // We should always be able to fold the entry block of the function into the
271 // single predecessor of the block...
272 assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
273 BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
274 SimplifyCFG(CalleeEntry);
275
276 // Okay, continue the CFG cleanup. It's often the case that there is only a
277 // single return instruction in the callee function. If this is the case,
Chris Lattner80a38d22003-08-24 06:59:16 +0000278 // then we have an unconditional branch from the return block to the
279 // 'AfterCallBB'. Check for this case, and eliminate the branch is possible.
280 SimplifyCFG(AfterCallBB);
Chris Lattnerca398dc2003-05-29 15:11:31 +0000281 return true;
282}
Brian Gaeked0fde302003-11-11 22:41:34 +0000283
284} // End llvm namespace