1 //===- InlineFunction.cpp - Code to perform function inlining -------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements inlining of a function into a call site, resolving
11 // parameters and the return value as appropriate.
13 // FIXME: This pass should transform alloca instructions in the called function
14 // into alloca/dealloca pairs! Or perhaps it should refuse to inline them!
16 //===----------------------------------------------------------------------===//
18 #include "llvm/Transforms/Utils/Cloning.h"
19 #include "llvm/Constant.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Module.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Intrinsics.h"
24 #include "llvm/Support/CallSite.h"
25 #include "llvm/Transforms/Utils/Local.h"
28 bool llvm::InlineFunction(CallInst *CI) { return InlineFunction(CallSite(CI)); }
29 bool llvm::InlineFunction(InvokeInst *II) {return InlineFunction(CallSite(II));}
31 // 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.
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.
40 bool llvm::InlineFunction(CallSite CS) {
41 Instruction *TheCall = CS.getInstruction();
42 assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
43 "Instruction not in function!");
45 const Function *CalledFunc = CS.getCalledFunction();
46 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;
50 BasicBlock *OrigBB = TheCall->getParent();
51 Function *Caller = OrigBB->getParent();
53 // Get an iterator to the last basic block in the function, which will have
54 // the new function inlined after it.
56 Function::iterator LastBlock = &Caller->back();
58 // Make sure to capture all of the return instructions from the cloned
60 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!");
68 CallSite::arg_iterator AI = CS.arg_begin();
69 for (Function::const_aiterator I = CalledFunc->abegin(),
70 E = CalledFunc->aend(); I != E; ++I, ++AI)
73 // Clone the entire body of the callee into the caller.
74 CloneFunctionInto(Caller, CalledFunc, ValueMap, Returns, ".i");
77 // Remember the first block that is newly cloned over.
78 Function::iterator FirstNewBlock = LastBlock; ++FirstNewBlock;
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.
85 if (isa<AllocaInst>(FirstNewBlock->begin())) {
86 BasicBlock::iterator InsertPoint = Caller->begin()->begin();
87 while (isa<AllocaInst>(InsertPoint)) ++InsertPoint;
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 FirstNewBlock->getInstList().remove(AI);
94 Caller->front().getInstList().insert(InsertPoint, AI);
98 // If we are inlining for an invoke instruction, we must make sure to rewrite
99 // any inlined 'unwind' instructions into branches to the invoke exception
100 // destination, and call instructions into invoke instructions.
101 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
102 BasicBlock *InvokeDest = II->getExceptionalDest();
103 std::vector<Value*> InvokeDestPHIValues;
105 // If there are PHI nodes in the exceptional destination block, we need to
106 // keep track of which values came into them from this invoke, then remove
107 // the entry for this block.
108 for (BasicBlock::iterator I = InvokeDest->begin();
109 PHINode *PN = dyn_cast<PHINode>(I); ++I)
110 // Save the value to use for this edge...
111 InvokeDestPHIValues.push_back(PN->getIncomingValueForBlock(OrigBB));
113 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
115 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
116 // We only need to check for function calls: inlined invoke instructions
117 // require no special handling...
118 if (CallInst *CI = dyn_cast<CallInst>(I)) {
119 // Convert this function call into an invoke instruction...
121 // First, split the basic block...
122 BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
124 // Next, create the new invoke instruction, inserting it at the end
125 // of the old basic block.
127 new InvokeInst(CI->getCalledValue(), Split, InvokeDest,
128 std::vector<Value*>(CI->op_begin()+1, CI->op_end()),
129 CI->getName(), BB->getTerminator());
131 // Make sure that anything using the call now uses the invoke!
132 CI->replaceAllUsesWith(II);
134 // Delete the unconditional branch inserted by splitBasicBlock
135 BB->getInstList().pop_back();
136 Split->getInstList().pop_front(); // Delete the original call
138 // Update any PHI nodes in the exceptional block to indicate that
139 // there is now a new entry in them.
141 for (BasicBlock::iterator I = InvokeDest->begin();
142 PHINode *PN = dyn_cast<PHINode>(I); ++I, ++i)
143 PN->addIncoming(InvokeDestPHIValues[i], BB);
145 // This basic block is now complete, start scanning the next one.
152 if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
153 // An UnwindInst requires special handling when it gets inlined into an
154 // invoke site. Once this happens, we know that the unwind would cause
155 // a control transfer to the invoke exception destination, so we can
156 // transform it into a direct branch to the exception destination.
157 new BranchInst(InvokeDest, UI);
159 // Delete the unwind instruction!
160 UI->getParent()->getInstList().pop_back();
162 // Update any PHI nodes in the exceptional block to indicate that
163 // there is now a new entry in them.
165 for (BasicBlock::iterator I = InvokeDest->begin();
166 PHINode *PN = dyn_cast<PHINode>(I); ++I, ++i)
167 PN->addIncoming(InvokeDestPHIValues[i], BB);
171 // Now that everything is happy, we have one final detail. The PHI nodes in
172 // the exception destination block still have entries due to the original
173 // invoke instruction. Eliminate these entries (which might even delete the
175 InvokeDest->removePredecessor(II->getParent());
178 // We want to clone the entire callee function into the hole between the
179 // "starter" and "ender" blocks. How we accomplish this depends on whether
180 // this is an invoke instruction or a call instruction.
181 BasicBlock *AfterCallBB;
182 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
184 // Add an unconditional branch to make this look like the CallInst case...
185 BranchInst *NewBr = new BranchInst(II->getNormalDest(), TheCall);
187 // Split the basic block. This guarantees that no PHI nodes will have to be
188 // updated due to new incoming edges, and make the invoke case more
189 // symmetric to the call case.
190 AfterCallBB = OrigBB->splitBasicBlock(NewBr,
191 CalledFunc->getName()+".entry");
193 // Remove (unlink) the InvokeInst from the function...
194 OrigBB->getInstList().remove(TheCall);
196 } else { // It's a call
197 // If this is a call instruction, we need to split the basic block that the
200 AfterCallBB = OrigBB->splitBasicBlock(TheCall,
201 CalledFunc->getName()+".entry");
202 // Remove (unlink) the CallInst from the function...
203 AfterCallBB->getInstList().remove(TheCall);
206 // Handle all of the return instructions that we just cloned in, and eliminate
207 // any users of the original call/invoke instruction.
208 if (Returns.size() > 1) {
209 // The PHI node should go at the front of the new basic block to merge all
210 // possible incoming values.
213 if (!TheCall->use_empty()) {
214 PHI = new PHINode(CalledFunc->getReturnType(),
215 TheCall->getName(), AfterCallBB->begin());
217 // Anything that used the result of the function call should now use the
218 // PHI node as their operand.
220 TheCall->replaceAllUsesWith(PHI);
223 // Loop over all of the return instructions, turning them into unconditional
224 // branches to the merge point now, and adding entries to the PHI node as
226 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
227 ReturnInst *RI = Returns[i];
230 assert(RI->getReturnValue() && "Ret should have value!");
231 assert(RI->getReturnValue()->getType() == PHI->getType() &&
232 "Ret value not consistent in function!");
233 PHI->addIncoming(RI->getReturnValue(), RI->getParent());
236 // Add a branch to the merge point where the PHI node lives if it exists.
237 new BranchInst(AfterCallBB, RI);
239 // Delete the return instruction now
240 RI->getParent()->getInstList().erase(RI);
243 } else if (!Returns.empty()) {
244 // Otherwise, if there is exactly one return value, just replace anything
245 // using the return value of the call with the computed value.
246 if (!TheCall->use_empty())
247 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
249 // Add a branch to the merge point where the PHI node lives if it exists.
250 new BranchInst(AfterCallBB, Returns[0]);
252 // Delete the return instruction now
253 Returns[0]->getParent()->getInstList().erase(Returns[0]);
256 // Since we are now done with the Call/Invoke, we can delete it.
259 // Change the branch that used to go to AfterCallBB to branch to the first
260 // basic block of the inlined function.
262 TerminatorInst *Br = OrigBB->getTerminator();
263 assert(Br && Br->getOpcode() == Instruction::Br &&
264 "splitBasicBlock broken!");
265 Br->setOperand(0, FirstNewBlock);
267 // Now that the function is correct, make it a little bit nicer. In
268 // particular, move the basic blocks inserted from the end of the function
269 // into the space made by splitting the source basic block.
271 Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
272 FirstNewBlock, Caller->end());
274 // We should always be able to fold the entry block of the function into the
275 // single predecessor of the block...
276 assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
277 BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
278 SimplifyCFG(CalleeEntry);
280 // Okay, continue the CFG cleanup. It's often the case that there is only a
281 // single return instruction in the callee function. If this is the case,
282 // then we have an unconditional branch from the return block to the
283 // 'AfterCallBB'. Check for this case, and eliminate the branch is possible.
284 SimplifyCFG(AfterCallBB);