1 //===- InlineFunction.cpp - Code to perform function inlining -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/Utils/Cloning.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Module.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/IntrinsicInst.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/Attributes.h"
24 #include "llvm/Analysis/CallGraph.h"
25 #include "llvm/Analysis/DebugInfo.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/Support/CallSite.h"
32 bool llvm::InlineFunction(CallInst *CI, CallGraph *CG, const TargetData *TD) {
33 return InlineFunction(CallSite(CI), CG, TD);
35 bool llvm::InlineFunction(InvokeInst *II, CallGraph *CG, const TargetData *TD) {
36 return InlineFunction(CallSite(II), CG, TD);
40 /// HandleCallsInBlockInlinedThroughInvoke - When we inline a basic block into
41 /// an invoke, we have to check all of all of the calls that can throw into
42 /// invokes. This function analyze BB to see if there are any calls, and if so,
43 /// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
44 /// nodes in that block with the values specified in InvokeDestPHIValues. If
45 /// CallerCGN is specified, this function updates the call graph.
47 static void HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB,
48 BasicBlock *InvokeDest,
49 const SmallVectorImpl<Value*> &InvokeDestPHIValues,
50 CallGraphNode *CallerCGN) {
51 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
52 Instruction *I = BBI++;
54 // We only need to check for function calls: inlined invoke
55 // instructions require no special handling.
56 CallInst *CI = dyn_cast<CallInst>(I);
57 if (CI == 0) continue;
59 // If this call cannot unwind, don't convert it to an invoke.
60 if (CI->doesNotThrow())
63 // Convert this function call into an invoke instruction.
64 // First, split the basic block.
65 BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
67 // Next, create the new invoke instruction, inserting it at the end
68 // of the old basic block.
69 SmallVector<Value*, 8> InvokeArgs(CI->op_begin()+1, CI->op_end());
71 InvokeInst::Create(CI->getCalledValue(), Split, InvokeDest,
72 InvokeArgs.begin(), InvokeArgs.end(),
73 CI->getName(), BB->getTerminator());
74 II->setCallingConv(CI->getCallingConv());
75 II->setAttributes(CI->getAttributes());
77 // Make sure that anything using the call now uses the invoke!
78 CI->replaceAllUsesWith(II);
80 // Update the callgraph if present.
82 // We should be able to do this:
83 // (*CG)[Caller]->replaceCallSite(CI, II);
84 // but that fails if the old call site isn't in the call graph,
85 // which, because of LLVM bug 3601, it sometimes isn't.
86 for (CallGraphNode::iterator NI = CallerCGN->begin(), NE = CallerCGN->end();
88 if (NI->first == CI) {
95 // Delete the unconditional branch inserted by splitBasicBlock
96 BB->getInstList().pop_back();
97 Split->getInstList().pop_front(); // Delete the original call
99 // Update any PHI nodes in the exceptional block to indicate that
100 // there is now a new entry in them.
102 for (BasicBlock::iterator I = InvokeDest->begin();
103 isa<PHINode>(I); ++I, ++i)
104 cast<PHINode>(I)->addIncoming(InvokeDestPHIValues[i], BB);
106 // This basic block is now complete, the caller will continue scanning the
113 /// HandleInlinedInvoke - If we inlined an invoke site, we need to convert calls
114 /// in the body of the inlined function into invokes and turn unwind
115 /// instructions into branches to the invoke unwind dest.
117 /// II is the invoke instruction being inlined. FirstNewBlock is the first
118 /// block of the inlined code (the last block is the end of the function),
119 /// and InlineCodeInfo is information about the code that got inlined.
120 static void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
121 ClonedCodeInfo &InlinedCodeInfo,
123 BasicBlock *InvokeDest = II->getUnwindDest();
124 SmallVector<Value*, 8> InvokeDestPHIValues;
126 // If there are PHI nodes in the unwind destination block, we need to
127 // keep track of which values came into them from this invoke, then remove
128 // the entry for this block.
129 BasicBlock *InvokeBlock = II->getParent();
130 for (BasicBlock::iterator I = InvokeDest->begin(); isa<PHINode>(I); ++I) {
131 PHINode *PN = cast<PHINode>(I);
132 // Save the value to use for this edge.
133 InvokeDestPHIValues.push_back(PN->getIncomingValueForBlock(InvokeBlock));
136 Function *Caller = FirstNewBlock->getParent();
138 // The inlined code is currently at the end of the function, scan from the
139 // start of the inlined code to its end, checking for stuff we need to
140 // rewrite. If the code doesn't have calls or unwinds, we know there is
141 // nothing to rewrite.
142 if (!InlinedCodeInfo.ContainsCalls && !InlinedCodeInfo.ContainsUnwinds) {
143 // Now that everything is happy, we have one final detail. The PHI nodes in
144 // the exception destination block still have entries due to the original
145 // invoke instruction. Eliminate these entries (which might even delete the
147 InvokeDest->removePredecessor(II->getParent());
151 CallGraphNode *CallerCGN = 0;
152 if (CG) CallerCGN = (*CG)[Caller];
154 for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; ++BB){
155 if (InlinedCodeInfo.ContainsCalls)
156 HandleCallsInBlockInlinedThroughInvoke(BB, InvokeDest,
157 InvokeDestPHIValues, CallerCGN);
159 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.
164 BranchInst::Create(InvokeDest, UI);
166 // Delete the unwind instruction!
167 UI->eraseFromParent();
169 // Update any PHI nodes in the exceptional block to indicate that
170 // there is now a new entry in them.
172 for (BasicBlock::iterator I = InvokeDest->begin();
173 isa<PHINode>(I); ++I, ++i) {
174 PHINode *PN = cast<PHINode>(I);
175 PN->addIncoming(InvokeDestPHIValues[i], BB);
180 // Now that everything is happy, we have one final detail. The PHI nodes in
181 // the exception destination block still have entries due to the original
182 // invoke instruction. Eliminate these entries (which might even delete the
184 InvokeDest->removePredecessor(II->getParent());
187 /// UpdateCallGraphAfterInlining - Once we have cloned code over from a callee
188 /// into the caller, update the specified callgraph to reflect the changes we
189 /// made. Note that it's possible that not all code was copied over, so only
190 /// some edges of the callgraph may remain.
191 static void UpdateCallGraphAfterInlining(CallSite CS,
192 Function::iterator FirstNewBlock,
193 DenseMap<const Value*, Value*> &ValueMap,
195 const Function *Caller = CS.getInstruction()->getParent()->getParent();
196 const Function *Callee = CS.getCalledFunction();
197 CallGraphNode *CalleeNode = CG[Callee];
198 CallGraphNode *CallerNode = CG[Caller];
200 // Since we inlined some uninlined call sites in the callee into the caller,
201 // add edges from the caller to all of the callees of the callee.
202 CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
204 // Consider the case where CalleeNode == CallerNode.
205 CallGraphNode::CalledFunctionsVector CallCache;
206 if (CalleeNode == CallerNode) {
207 CallCache.assign(I, E);
208 I = CallCache.begin();
212 for (; I != E; ++I) {
213 const Instruction *OrigCall = I->first.getInstruction();
215 DenseMap<const Value*, Value*>::iterator VMI = ValueMap.find(OrigCall);
216 // Only copy the edge if the call was inlined!
217 if (VMI == ValueMap.end() || VMI->second == 0)
220 // If the call was inlined, but then constant folded, there is no edge to
221 // add. Check for this case.
222 if (Instruction *NewCall = dyn_cast<Instruction>(VMI->second))
223 CallerNode->addCalledFunction(CallSite::get(NewCall), I->second);
226 // Update the call graph by deleting the edge from Callee to Caller. We must
227 // do this after the loop above in case Caller and Callee are the same.
228 CallerNode->removeCallEdgeFor(CS);
231 /// findFnRegionEndMarker - This is a utility routine that is used by
232 /// InlineFunction. Return llvm.dbg.region.end intrinsic that corresponds
233 /// to the llvm.dbg.func.start of the function F. Otherwise return NULL.
235 static const DbgRegionEndInst *findFnRegionEndMarker(const Function *F) {
237 GlobalVariable *FnStart = NULL;
238 const DbgRegionEndInst *FnEnd = NULL;
239 for (Function::const_iterator FI = F->begin(), FE =F->end(); FI != FE; ++FI)
240 for (BasicBlock::const_iterator BI = FI->begin(), BE = FI->end(); BI != BE;
242 if (FnStart == NULL) {
243 if (const DbgFuncStartInst *FSI = dyn_cast<DbgFuncStartInst>(BI)) {
244 DISubprogram SP(cast<GlobalVariable>(FSI->getSubprogram()));
245 assert (SP.isNull() == false && "Invalid llvm.dbg.func.start");
247 FnStart = SP.getGV();
252 if (const DbgRegionEndInst *REI = dyn_cast<DbgRegionEndInst>(BI))
253 if (REI->getContext() == FnStart)
259 // InlineFunction - This function inlines the called function into the basic
260 // block of the caller. This returns false if it is not possible to inline this
261 // call. The program is still in a well defined state if this occurs though.
263 // Note that this only does one level of inlining. For example, if the
264 // instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
265 // exists in the instruction stream. Similiarly this will inline a recursive
266 // function by one level.
268 bool llvm::InlineFunction(CallSite CS, CallGraph *CG, const TargetData *TD) {
269 Instruction *TheCall = CS.getInstruction();
270 LLVMContext &Context = TheCall->getContext();
271 assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
272 "Instruction not in function!");
274 const Function *CalledFunc = CS.getCalledFunction();
275 if (CalledFunc == 0 || // Can't inline external function or indirect
276 CalledFunc->isDeclaration() || // call, or call to a vararg function!
277 CalledFunc->getFunctionType()->isVarArg()) return false;
280 // If the call to the callee is not a tail call, we must clear the 'tail'
281 // flags on any calls that we inline.
282 bool MustClearTailCallFlags =
283 !(isa<CallInst>(TheCall) && cast<CallInst>(TheCall)->isTailCall());
285 // If the call to the callee cannot throw, set the 'nounwind' flag on any
286 // calls that we inline.
287 bool MarkNoUnwind = CS.doesNotThrow();
289 BasicBlock *OrigBB = TheCall->getParent();
290 Function *Caller = OrigBB->getParent();
292 // GC poses two hazards to inlining, which only occur when the callee has GC:
293 // 1. If the caller has no GC, then the callee's GC must be propagated to the
295 // 2. If the caller has a differing GC, it is invalid to inline.
296 if (CalledFunc->hasGC()) {
297 if (!Caller->hasGC())
298 Caller->setGC(CalledFunc->getGC());
299 else if (CalledFunc->getGC() != Caller->getGC())
303 // Get an iterator to the last basic block in the function, which will have
304 // the new function inlined after it.
306 Function::iterator LastBlock = &Caller->back();
308 // Make sure to capture all of the return instructions from the cloned
310 SmallVector<ReturnInst*, 8> Returns;
311 ClonedCodeInfo InlinedFunctionInfo;
312 Function::iterator FirstNewBlock;
314 { // Scope to destroy ValueMap after cloning.
315 DenseMap<const Value*, Value*> ValueMap;
317 assert(CalledFunc->arg_size() == CS.arg_size() &&
318 "No varargs calls can be inlined!");
320 // Calculate the vector of arguments to pass into the function cloner, which
321 // matches up the formal to the actual argument values.
322 CallSite::arg_iterator AI = CS.arg_begin();
324 for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
325 E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
326 Value *ActualArg = *AI;
328 // When byval arguments actually inlined, we need to make the copy implied
329 // by them explicit. However, we don't do this if the callee is readonly
330 // or readnone, because the copy would be unneeded: the callee doesn't
331 // modify the struct.
332 if (CalledFunc->paramHasAttr(ArgNo+1, Attribute::ByVal) &&
333 !CalledFunc->onlyReadsMemory()) {
334 const Type *AggTy = cast<PointerType>(I->getType())->getElementType();
335 const Type *VoidPtrTy =
336 PointerType::getUnqual(Type::getInt8Ty(Context));
338 // Create the alloca. If we have TargetData, use nice alignment.
340 if (TD) Align = TD->getPrefTypeAlignment(AggTy);
341 Value *NewAlloca = new AllocaInst(AggTy, 0, Align,
343 &*Caller->begin()->begin());
345 const Type *Tys[] = { Type::getInt64Ty(Context) };
346 Function *MemCpyFn = Intrinsic::getDeclaration(Caller->getParent(),
349 Value *DestCast = new BitCastInst(NewAlloca, VoidPtrTy, "tmp", TheCall);
350 Value *SrcCast = new BitCastInst(*AI, VoidPtrTy, "tmp", TheCall);
354 Size = ConstantExpr::getSizeOf(AggTy);
356 Size = ConstantInt::get(Type::getInt64Ty(Context),
357 TD->getTypeStoreSize(AggTy));
359 // Always generate a memcpy of alignment 1 here because we don't know
360 // the alignment of the src pointer. Other optimizations can infer
362 Value *CallArgs[] = {
363 DestCast, SrcCast, Size,
364 ConstantInt::get(Type::getInt32Ty(Context), 1)
366 CallInst *TheMemCpy =
367 CallInst::Create(MemCpyFn, CallArgs, CallArgs+4, "", TheCall);
369 // If we have a call graph, update it.
371 CallGraphNode *MemCpyCGN = CG->getOrInsertFunction(MemCpyFn);
372 CallGraphNode *CallerNode = (*CG)[Caller];
373 CallerNode->addCalledFunction(TheMemCpy, MemCpyCGN);
376 // Uses of the argument in the function should use our new alloca
378 ActualArg = NewAlloca;
381 ValueMap[I] = ActualArg;
384 // Adjust llvm.dbg.region.end. If the CalledFunc has region end
385 // marker then clone that marker after next stop point at the
386 // call site. The function body cloner does not clone original
387 // region end marker from the CalledFunc. This will ensure that
388 // inlined function's scope ends at the right place.
389 if (const DbgRegionEndInst *DREI = findFnRegionEndMarker(CalledFunc)) {
390 for (BasicBlock::iterator BI = TheCall, BE = TheCall->getParent()->end();
392 if (DbgStopPointInst *DSPI = dyn_cast<DbgStopPointInst>(BI)) {
393 if (DbgRegionEndInst *NewDREI =
394 dyn_cast<DbgRegionEndInst>(DREI->clone(Context)))
395 NewDREI->insertAfter(DSPI);
401 // We want the inliner to prune the code as it copies. We would LOVE to
402 // have no dead or constant instructions leftover after inlining occurs
403 // (which can happen, e.g., because an argument was constant), but we'll be
404 // happy with whatever the cloner can do.
405 CloneAndPruneFunctionInto(Caller, CalledFunc, ValueMap, Returns, ".i",
406 &InlinedFunctionInfo, TD);
408 // Remember the first block that is newly cloned over.
409 FirstNewBlock = LastBlock; ++FirstNewBlock;
411 // Update the callgraph if requested.
413 UpdateCallGraphAfterInlining(CS, FirstNewBlock, ValueMap, *CG);
416 // If there are any alloca instructions in the block that used to be the entry
417 // block for the callee, move them to the entry block of the caller. First
418 // calculate which instruction they should be inserted before. We insert the
419 // instructions at the end of the current alloca list.
422 BasicBlock::iterator InsertPoint = Caller->begin()->begin();
423 for (BasicBlock::iterator I = FirstNewBlock->begin(),
424 E = FirstNewBlock->end(); I != E; ) {
425 AllocaInst *AI = dyn_cast<AllocaInst>(I++);
426 if (AI == 0) continue;
428 // If the alloca is now dead, remove it. This often occurs due to code
430 if (AI->use_empty()) {
431 AI->eraseFromParent();
435 if (!isa<Constant>(AI->getArraySize()))
438 // Scan for the block of allocas that we can move over, and move them
440 while (isa<AllocaInst>(I) &&
441 isa<Constant>(cast<AllocaInst>(I)->getArraySize()))
444 // Transfer all of the allocas over in a block. Using splice means
445 // that the instructions aren't removed from the symbol table, then
447 Caller->getEntryBlock().getInstList().splice(InsertPoint,
448 FirstNewBlock->getInstList(),
453 // If the inlined code contained dynamic alloca instructions, wrap the inlined
454 // code with llvm.stacksave/llvm.stackrestore intrinsics.
455 if (InlinedFunctionInfo.ContainsDynamicAllocas) {
456 Module *M = Caller->getParent();
457 // Get the two intrinsics we care about.
458 Constant *StackSave, *StackRestore;
459 StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
460 StackRestore = Intrinsic::getDeclaration(M, Intrinsic::stackrestore);
462 // If we are preserving the callgraph, add edges to the stacksave/restore
463 // functions for the calls we insert.
464 CallGraphNode *StackSaveCGN = 0, *StackRestoreCGN = 0, *CallerNode = 0;
466 // We know that StackSave/StackRestore are Function*'s, because they are
467 // intrinsics which must have the right types.
468 StackSaveCGN = CG->getOrInsertFunction(cast<Function>(StackSave));
469 StackRestoreCGN = CG->getOrInsertFunction(cast<Function>(StackRestore));
470 CallerNode = (*CG)[Caller];
473 // Insert the llvm.stacksave.
474 CallInst *SavedPtr = CallInst::Create(StackSave, "savedstack",
475 FirstNewBlock->begin());
476 if (CG) CallerNode->addCalledFunction(SavedPtr, StackSaveCGN);
478 // Insert a call to llvm.stackrestore before any return instructions in the
480 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
481 CallInst *CI = CallInst::Create(StackRestore, SavedPtr, "", Returns[i]);
482 if (CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
485 // Count the number of StackRestore calls we insert.
486 unsigned NumStackRestores = Returns.size();
488 // If we are inlining an invoke instruction, insert restores before each
489 // unwind. These unwinds will be rewritten into branches later.
490 if (InlinedFunctionInfo.ContainsUnwinds && isa<InvokeInst>(TheCall)) {
491 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
493 if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
494 CallInst::Create(StackRestore, SavedPtr, "", UI);
500 // If we are inlining tail call instruction through a call site that isn't
501 // marked 'tail', we must remove the tail marker for any calls in the inlined
502 // code. Also, calls inlined through a 'nounwind' call site should be marked
504 if (InlinedFunctionInfo.ContainsCalls &&
505 (MustClearTailCallFlags || MarkNoUnwind)) {
506 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
508 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
509 if (CallInst *CI = dyn_cast<CallInst>(I)) {
510 if (MustClearTailCallFlags)
511 CI->setTailCall(false);
513 CI->setDoesNotThrow();
517 // If we are inlining through a 'nounwind' call site then any inlined 'unwind'
518 // instructions are unreachable.
519 if (InlinedFunctionInfo.ContainsUnwinds && MarkNoUnwind)
520 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
522 TerminatorInst *Term = BB->getTerminator();
523 if (isa<UnwindInst>(Term)) {
524 new UnreachableInst(Context, Term);
525 BB->getInstList().erase(Term);
529 // If we are inlining for an invoke instruction, we must make sure to rewrite
530 // any inlined 'unwind' instructions into branches to the invoke exception
531 // destination, and call instructions into invoke instructions.
532 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
533 HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo, CG);
535 // If we cloned in _exactly one_ basic block, and if that block ends in a
536 // return instruction, we splice the body of the inlined callee directly into
537 // the calling basic block.
538 if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
539 // Move all of the instructions right before the call.
540 OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
541 FirstNewBlock->begin(), FirstNewBlock->end());
542 // Remove the cloned basic block.
543 Caller->getBasicBlockList().pop_back();
545 // If the call site was an invoke instruction, add a branch to the normal
547 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
548 BranchInst::Create(II->getNormalDest(), TheCall);
550 // If the return instruction returned a value, replace uses of the call with
551 // uses of the returned value.
552 if (!TheCall->use_empty()) {
553 ReturnInst *R = Returns[0];
554 if (TheCall == R->getReturnValue())
555 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
557 TheCall->replaceAllUsesWith(R->getReturnValue());
559 // Since we are now done with the Call/Invoke, we can delete it.
560 TheCall->eraseFromParent();
562 // Since we are now done with the return instruction, delete it also.
563 Returns[0]->eraseFromParent();
565 // We are now done with the inlining.
569 // Otherwise, we have the normal case, of more than one block to inline or
570 // multiple return sites.
572 // We want to clone the entire callee function into the hole between the
573 // "starter" and "ender" blocks. How we accomplish this depends on whether
574 // this is an invoke instruction or a call instruction.
575 BasicBlock *AfterCallBB;
576 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
578 // Add an unconditional branch to make this look like the CallInst case...
579 BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
581 // Split the basic block. This guarantees that no PHI nodes will have to be
582 // updated due to new incoming edges, and make the invoke case more
583 // symmetric to the call case.
584 AfterCallBB = OrigBB->splitBasicBlock(NewBr,
585 CalledFunc->getName()+".exit");
587 } else { // It's a call
588 // If this is a call instruction, we need to split the basic block that
589 // the call lives in.
591 AfterCallBB = OrigBB->splitBasicBlock(TheCall,
592 CalledFunc->getName()+".exit");
595 // Change the branch that used to go to AfterCallBB to branch to the first
596 // basic block of the inlined function.
598 TerminatorInst *Br = OrigBB->getTerminator();
599 assert(Br && Br->getOpcode() == Instruction::Br &&
600 "splitBasicBlock broken!");
601 Br->setOperand(0, FirstNewBlock);
604 // Now that the function is correct, make it a little bit nicer. In
605 // particular, move the basic blocks inserted from the end of the function
606 // into the space made by splitting the source basic block.
607 Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
608 FirstNewBlock, Caller->end());
610 // Handle all of the return instructions that we just cloned in, and eliminate
611 // any users of the original call/invoke instruction.
612 const Type *RTy = CalledFunc->getReturnType();
614 if (Returns.size() > 1) {
615 // The PHI node should go at the front of the new basic block to merge all
616 // possible incoming values.
618 if (!TheCall->use_empty()) {
619 PHI = PHINode::Create(RTy, TheCall->getName(),
620 AfterCallBB->begin());
621 // Anything that used the result of the function call should now use the
622 // PHI node as their operand.
623 TheCall->replaceAllUsesWith(PHI);
626 // Loop over all of the return instructions adding entries to the PHI node
629 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
630 ReturnInst *RI = Returns[i];
631 assert(RI->getReturnValue()->getType() == PHI->getType() &&
632 "Ret value not consistent in function!");
633 PHI->addIncoming(RI->getReturnValue(), RI->getParent());
637 // Add a branch to the merge points and remove return instructions.
638 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
639 ReturnInst *RI = Returns[i];
640 BranchInst::Create(AfterCallBB, RI);
641 RI->eraseFromParent();
643 } else if (!Returns.empty()) {
644 // Otherwise, if there is exactly one return value, just replace anything
645 // using the return value of the call with the computed value.
646 if (!TheCall->use_empty()) {
647 if (TheCall == Returns[0]->getReturnValue())
648 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
650 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
653 // Splice the code from the return block into the block that it will return
654 // to, which contains the code that was after the call.
655 BasicBlock *ReturnBB = Returns[0]->getParent();
656 AfterCallBB->getInstList().splice(AfterCallBB->begin(),
657 ReturnBB->getInstList());
659 // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
660 ReturnBB->replaceAllUsesWith(AfterCallBB);
662 // Delete the return instruction now and empty ReturnBB now.
663 Returns[0]->eraseFromParent();
664 ReturnBB->eraseFromParent();
665 } else if (!TheCall->use_empty()) {
666 // No returns, but something is using the return value of the call. Just
668 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
671 // Since we are now done with the Call/Invoke, we can delete it.
672 TheCall->eraseFromParent();
674 // We should always be able to fold the entry block of the function into the
675 // single predecessor of the block...
676 assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
677 BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
679 // Splice the code entry block into calling block, right before the
680 // unconditional branch.
681 OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
682 CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
684 // Remove the unconditional branch.
685 OrigBB->getInstList().erase(Br);
687 // Now we can remove the CalleeEntry block, which is now empty.
688 Caller->getBasicBlockList().erase(CalleeEntry);