LLVM API Documentation

InlineFunction.cpp

Go to the documentation of this file.
00001 //===- InlineFunction.cpp - Code to perform function inlining -------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements inlining of a function into a call site, resolving
00011 // parameters and the return value as appropriate.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Transforms/Utils/Cloning.h"
00016 #include "llvm/Constants.h"
00017 #include "llvm/DerivedTypes.h"
00018 #include "llvm/Module.h"
00019 #include "llvm/Instructions.h"
00020 #include "llvm/Intrinsics.h"
00021 #include "llvm/Attributes.h"
00022 #include "llvm/Analysis/CallGraph.h"
00023 #include "llvm/Target/TargetData.h"
00024 #include "llvm/ADT/SmallVector.h"
00025 #include "llvm/ADT/StringExtras.h"
00026 #include "llvm/Support/CallSite.h"
00027 using namespace llvm;
00028 
00029 bool llvm::InlineFunction(CallInst *CI, CallGraph *CG, const TargetData *TD) {
00030   return InlineFunction(CallSite(CI), CG, TD);
00031 }
00032 bool llvm::InlineFunction(InvokeInst *II, CallGraph *CG, const TargetData *TD) {
00033   return InlineFunction(CallSite(II), CG, TD);
00034 }
00035 
00036 /// HandleInlinedInvoke - If we inlined an invoke site, we need to convert calls
00037 /// in the body of the inlined function into invokes and turn unwind
00038 /// instructions into branches to the invoke unwind dest.
00039 ///
00040 /// II is the invoke instruction being inlined.  FirstNewBlock is the first
00041 /// block of the inlined code (the last block is the end of the function),
00042 /// and InlineCodeInfo is information about the code that got inlined.
00043 static void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
00044                                 ClonedCodeInfo &InlinedCodeInfo) {
00045   BasicBlock *InvokeDest = II->getUnwindDest();
00046   std::vector<Value*> InvokeDestPHIValues;
00047 
00048   // If there are PHI nodes in the unwind destination block, we need to
00049   // keep track of which values came into them from this invoke, then remove
00050   // the entry for this block.
00051   BasicBlock *InvokeBlock = II->getParent();
00052   for (BasicBlock::iterator I = InvokeDest->begin(); isa<PHINode>(I); ++I) {
00053     PHINode *PN = cast<PHINode>(I);
00054     // Save the value to use for this edge.
00055     InvokeDestPHIValues.push_back(PN->getIncomingValueForBlock(InvokeBlock));
00056   }
00057 
00058   Function *Caller = FirstNewBlock->getParent();
00059 
00060   // The inlined code is currently at the end of the function, scan from the
00061   // start of the inlined code to its end, checking for stuff we need to
00062   // rewrite.
00063   if (InlinedCodeInfo.ContainsCalls || InlinedCodeInfo.ContainsUnwinds) {
00064     for (Function::iterator BB = FirstNewBlock, E = Caller->end();
00065          BB != E; ++BB) {
00066       if (InlinedCodeInfo.ContainsCalls) {
00067         for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ){
00068           Instruction *I = BBI++;
00069 
00070           // We only need to check for function calls: inlined invoke
00071           // instructions require no special handling.
00072           if (!isa<CallInst>(I)) continue;
00073           CallInst *CI = cast<CallInst>(I);
00074 
00075           // If this call cannot unwind, don't convert it to an invoke.
00076           if (CI->doesNotThrow())
00077             continue;
00078 
00079           // Convert this function call into an invoke instruction.
00080           // First, split the basic block.
00081           BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
00082 
00083           // Next, create the new invoke instruction, inserting it at the end
00084           // of the old basic block.
00085           SmallVector<Value*, 8> InvokeArgs(CI->op_begin()+1, CI->op_end());
00086           InvokeInst *II =
00087             InvokeInst::Create(CI->getCalledValue(), Split, InvokeDest,
00088                                InvokeArgs.begin(), InvokeArgs.end(),
00089                                CI->getName(), BB->getTerminator());
00090           II->setCallingConv(CI->getCallingConv());
00091           II->setAttributes(CI->getAttributes());
00092 
00093           // Make sure that anything using the call now uses the invoke!
00094           CI->replaceAllUsesWith(II);
00095 
00096           // Delete the unconditional branch inserted by splitBasicBlock
00097           BB->getInstList().pop_back();
00098           Split->getInstList().pop_front();  // Delete the original call
00099 
00100           // Update any PHI nodes in the exceptional block to indicate that
00101           // there is now a new entry in them.
00102           unsigned i = 0;
00103           for (BasicBlock::iterator I = InvokeDest->begin();
00104                isa<PHINode>(I); ++I, ++i) {
00105             PHINode *PN = cast<PHINode>(I);
00106             PN->addIncoming(InvokeDestPHIValues[i], BB);
00107           }
00108 
00109           // This basic block is now complete, start scanning the next one.
00110           break;
00111         }
00112       }
00113 
00114       if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
00115         // An UnwindInst requires special handling when it gets inlined into an
00116         // invoke site.  Once this happens, we know that the unwind would cause
00117         // a control transfer to the invoke exception destination, so we can
00118         // transform it into a direct branch to the exception destination.
00119         BranchInst::Create(InvokeDest, UI);
00120 
00121         // Delete the unwind instruction!
00122         UI->eraseFromParent();
00123 
00124         // Update any PHI nodes in the exceptional block to indicate that
00125         // there is now a new entry in them.
00126         unsigned i = 0;
00127         for (BasicBlock::iterator I = InvokeDest->begin();
00128              isa<PHINode>(I); ++I, ++i) {
00129           PHINode *PN = cast<PHINode>(I);
00130           PN->addIncoming(InvokeDestPHIValues[i], BB);
00131         }
00132       }
00133     }
00134   }
00135 
00136   // Now that everything is happy, we have one final detail.  The PHI nodes in
00137   // the exception destination block still have entries due to the original
00138   // invoke instruction.  Eliminate these entries (which might even delete the
00139   // PHI node) now.
00140   InvokeDest->removePredecessor(II->getParent());
00141 }
00142 
00143 /// UpdateCallGraphAfterInlining - Once we have cloned code over from a callee
00144 /// into the caller, update the specified callgraph to reflect the changes we
00145 /// made.  Note that it's possible that not all code was copied over, so only
00146 /// some edges of the callgraph may remain.
00147 static void UpdateCallGraphAfterInlining(CallSite CS,
00148                                          Function::iterator FirstNewBlock,
00149                                        DenseMap<const Value*, Value*> &ValueMap,
00150                                          CallGraph &CG) {
00151   const Function *Caller = CS.getInstruction()->getParent()->getParent();
00152   const Function *Callee = CS.getCalledFunction();
00153   CallGraphNode *CalleeNode = CG[Callee];
00154   CallGraphNode *CallerNode = CG[Caller];
00155 
00156   // Since we inlined some uninlined call sites in the callee into the caller,
00157   // add edges from the caller to all of the callees of the callee.
00158   CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
00159 
00160   // Consider the case where CalleeNode == CallerNode.
00161   CallGraphNode::CalledFunctionsVector CallCache;
00162   if (CalleeNode == CallerNode) {
00163     CallCache.assign(I, E);
00164     I = CallCache.begin();
00165     E = CallCache.end();
00166   }
00167 
00168   for (; I != E; ++I) {
00169     const Instruction *OrigCall = I->first.getInstruction();
00170 
00171     DenseMap<const Value*, Value*>::iterator VMI = ValueMap.find(OrigCall);
00172     // Only copy the edge if the call was inlined!
00173     if (VMI != ValueMap.end() && VMI->second) {
00174       // If the call was inlined, but then constant folded, there is no edge to
00175       // add.  Check for this case.
00176       if (Instruction *NewCall = dyn_cast<Instruction>(VMI->second))
00177         CallerNode->addCalledFunction(CallSite::get(NewCall), I->second);
00178     }
00179   }
00180   // Update the call graph by deleting the edge from Callee to Caller.  We must
00181   // do this after the loop above in case Caller and Callee are the same.
00182   CallerNode->removeCallEdgeFor(CS);
00183 }
00184 
00185 
00186 // InlineFunction - This function inlines the called function into the basic
00187 // block of the caller.  This returns false if it is not possible to inline this
00188 // call.  The program is still in a well defined state if this occurs though.
00189 //
00190 // Note that this only does one level of inlining.  For example, if the
00191 // instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
00192 // exists in the instruction stream.  Similiarly this will inline a recursive
00193 // function by one level.
00194 //
00195 bool llvm::InlineFunction(CallSite CS, CallGraph *CG, const TargetData *TD) {
00196   Instruction *TheCall = CS.getInstruction();
00197   assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
00198          "Instruction not in function!");
00199 
00200   const Function *CalledFunc = CS.getCalledFunction();
00201   if (CalledFunc == 0 ||          // Can't inline external function or indirect
00202       CalledFunc->isDeclaration() || // call, or call to a vararg function!
00203       CalledFunc->getFunctionType()->isVarArg()) return false;
00204 
00205 
00206   // If the call to the callee is not a tail call, we must clear the 'tail'
00207   // flags on any calls that we inline.
00208   bool MustClearTailCallFlags =
00209     !(isa<CallInst>(TheCall) && cast<CallInst>(TheCall)->isTailCall());
00210 
00211   // If the call to the callee cannot throw, set the 'nounwind' flag on any
00212   // calls that we inline.
00213   bool MarkNoUnwind = CS.doesNotThrow();
00214 
00215   BasicBlock *OrigBB = TheCall->getParent();
00216   Function *Caller = OrigBB->getParent();
00217 
00218   // GC poses two hazards to inlining, which only occur when the callee has GC:
00219   //  1. If the caller has no GC, then the callee's GC must be propagated to the
00220   //     caller.
00221   //  2. If the caller has a differing GC, it is invalid to inline.
00222   if (CalledFunc->hasGC()) {
00223     if (!Caller->hasGC())
00224       Caller->setGC(CalledFunc->getGC());
00225     else if (CalledFunc->getGC() != Caller->getGC())
00226       return false;
00227   }
00228 
00229   // Get an iterator to the last basic block in the function, which will have
00230   // the new function inlined after it.
00231   //
00232   Function::iterator LastBlock = &Caller->back();
00233 
00234   // Make sure to capture all of the return instructions from the cloned
00235   // function.
00236   std::vector<ReturnInst*> Returns;
00237   ClonedCodeInfo InlinedFunctionInfo;
00238   Function::iterator FirstNewBlock;
00239 
00240   { // Scope to destroy ValueMap after cloning.
00241     DenseMap<const Value*, Value*> ValueMap;
00242 
00243     assert(CalledFunc->arg_size() == CS.arg_size() &&
00244            "No varargs calls can be inlined!");
00245 
00246     // Calculate the vector of arguments to pass into the function cloner, which
00247     // matches up the formal to the actual argument values.
00248     CallSite::arg_iterator AI = CS.arg_begin();
00249     unsigned ArgNo = 0;
00250     for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
00251          E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
00252       Value *ActualArg = *AI;
00253 
00254       // When byval arguments actually inlined, we need to make the copy implied
00255       // by them explicit.  However, we don't do this if the callee is readonly
00256       // or readnone, because the copy would be unneeded: the callee doesn't
00257       // modify the struct.
00258       if (CalledFunc->paramHasAttr(ArgNo+1, Attribute::ByVal) &&
00259           !CalledFunc->onlyReadsMemory()) {
00260         const Type *AggTy = cast<PointerType>(I->getType())->getElementType();
00261         const Type *VoidPtrTy = PointerType::getUnqual(Type::Int8Ty);
00262 
00263         // Create the alloca.  If we have TargetData, use nice alignment.
00264         unsigned Align = 1;
00265         if (TD) Align = TD->getPrefTypeAlignment(AggTy);
00266         Value *NewAlloca = new AllocaInst(AggTy, 0, Align, I->getName(),
00267                                           Caller->begin()->begin());
00268         // Emit a memcpy.
00269         const Type *Tys[] = { Type::Int64Ty };
00270         Function *MemCpyFn = Intrinsic::getDeclaration(Caller->getParent(),
00271                                                        Intrinsic::memcpy, 
00272                                                        Tys, 1);
00273         Value *DestCast = new BitCastInst(NewAlloca, VoidPtrTy, "tmp", TheCall);
00274         Value *SrcCast = new BitCastInst(*AI, VoidPtrTy, "tmp", TheCall);
00275 
00276         Value *Size;
00277         if (TD == 0)
00278           Size = ConstantExpr::getSizeOf(AggTy);
00279         else
00280           Size = ConstantInt::get(Type::Int64Ty, TD->getTypeStoreSize(AggTy));
00281 
00282         // Always generate a memcpy of alignment 1 here because we don't know
00283         // the alignment of the src pointer.  Other optimizations can infer
00284         // better alignment.
00285         Value *CallArgs[] = {
00286           DestCast, SrcCast, Size, ConstantInt::get(Type::Int32Ty, 1)
00287         };
00288         CallInst *TheMemCpy =
00289           CallInst::Create(MemCpyFn, CallArgs, CallArgs+4, "", TheCall);
00290 
00291         // If we have a call graph, update it.
00292         if (CG) {
00293           CallGraphNode *MemCpyCGN = CG->getOrInsertFunction(MemCpyFn);
00294           CallGraphNode *CallerNode = (*CG)[Caller];
00295           CallerNode->addCalledFunction(TheMemCpy, MemCpyCGN);
00296         }
00297 
00298         // Uses of the argument in the function should use our new alloca
00299         // instead.
00300         ActualArg = NewAlloca;
00301       }
00302 
00303       ValueMap[I] = ActualArg;
00304     }
00305 
00306     // We want the inliner to prune the code as it copies.  We would LOVE to
00307     // have no dead or constant instructions leftover after inlining occurs
00308     // (which can happen, e.g., because an argument was constant), but we'll be
00309     // happy with whatever the cloner can do.
00310     CloneAndPruneFunctionInto(Caller, CalledFunc, ValueMap, Returns, ".i",
00311                               &InlinedFunctionInfo, TD);
00312 
00313     // Remember the first block that is newly cloned over.
00314     FirstNewBlock = LastBlock; ++FirstNewBlock;
00315 
00316     // Update the callgraph if requested.
00317     if (CG)
00318       UpdateCallGraphAfterInlining(CS, FirstNewBlock, ValueMap, *CG);
00319   }
00320 
00321   // If there are any alloca instructions in the block that used to be the entry
00322   // block for the callee, move them to the entry block of the caller.  First
00323   // calculate which instruction they should be inserted before.  We insert the
00324   // instructions at the end of the current alloca list.
00325   //
00326   {
00327     BasicBlock::iterator InsertPoint = Caller->begin()->begin();
00328     for (BasicBlock::iterator I = FirstNewBlock->begin(),
00329            E = FirstNewBlock->end(); I != E; )
00330       if (AllocaInst *AI = dyn_cast<AllocaInst>(I++)) {
00331         // If the alloca is now dead, remove it.  This often occurs due to code
00332         // specialization.
00333         if (AI->use_empty()) {
00334           AI->eraseFromParent();
00335           continue;
00336         }
00337 
00338         if (isa<Constant>(AI->getArraySize())) {
00339           // Scan for the block of allocas that we can move over, and move them
00340           // all at once.
00341           while (isa<AllocaInst>(I) &&
00342                  isa<Constant>(cast<AllocaInst>(I)->getArraySize()))
00343             ++I;
00344 
00345           // Transfer all of the allocas over in a block.  Using splice means
00346           // that the instructions aren't removed from the symbol table, then
00347           // reinserted.
00348           Caller->getEntryBlock().getInstList().splice(
00349               InsertPoint,
00350               FirstNewBlock->getInstList(),
00351               AI, I);
00352         }
00353       }
00354   }
00355 
00356   // If the inlined code contained dynamic alloca instructions, wrap the inlined
00357   // code with llvm.stacksave/llvm.stackrestore intrinsics.
00358   if (InlinedFunctionInfo.ContainsDynamicAllocas) {
00359     Module *M = Caller->getParent();
00360     // Get the two intrinsics we care about.
00361     Constant *StackSave, *StackRestore;
00362     StackSave    = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
00363     StackRestore = Intrinsic::getDeclaration(M, Intrinsic::stackrestore);
00364 
00365     // If we are preserving the callgraph, add edges to the stacksave/restore
00366     // functions for the calls we insert.
00367     CallGraphNode *StackSaveCGN = 0, *StackRestoreCGN = 0, *CallerNode = 0;
00368     if (CG) {
00369       // We know that StackSave/StackRestore are Function*'s, because they are
00370       // intrinsics which must have the right types.
00371       StackSaveCGN    = CG->getOrInsertFunction(cast<Function>(StackSave));
00372       StackRestoreCGN = CG->getOrInsertFunction(cast<Function>(StackRestore));
00373       CallerNode = (*CG)[Caller];
00374     }
00375 
00376     // Insert the llvm.stacksave.
00377     CallInst *SavedPtr = CallInst::Create(StackSave, "savedstack",
00378                                           FirstNewBlock->begin());
00379     if (CG) CallerNode->addCalledFunction(SavedPtr, StackSaveCGN);
00380 
00381     // Insert a call to llvm.stackrestore before any return instructions in the
00382     // inlined function.
00383     for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
00384       CallInst *CI = CallInst::Create(StackRestore, SavedPtr, "", Returns[i]);
00385       if (CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
00386     }
00387 
00388     // Count the number of StackRestore calls we insert.
00389     unsigned NumStackRestores = Returns.size();
00390 
00391     // If we are inlining an invoke instruction, insert restores before each
00392     // unwind.  These unwinds will be rewritten into branches later.
00393     if (InlinedFunctionInfo.ContainsUnwinds && isa<InvokeInst>(TheCall)) {
00394       for (Function::iterator BB = FirstNewBlock, E = Caller->end();
00395            BB != E; ++BB)
00396         if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
00397           CallInst::Create(StackRestore, SavedPtr, "", UI);
00398           ++NumStackRestores;
00399         }
00400     }
00401   }
00402 
00403   // If we are inlining tail call instruction through a call site that isn't
00404   // marked 'tail', we must remove the tail marker for any calls in the inlined
00405   // code.  Also, calls inlined through a 'nounwind' call site should be marked
00406   // 'nounwind'.
00407   if (InlinedFunctionInfo.ContainsCalls &&
00408       (MustClearTailCallFlags || MarkNoUnwind)) {
00409     for (Function::iterator BB = FirstNewBlock, E = Caller->end();
00410          BB != E; ++BB)
00411       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
00412         if (CallInst *CI = dyn_cast<CallInst>(I)) {
00413           if (MustClearTailCallFlags)
00414             CI->setTailCall(false);
00415           if (MarkNoUnwind)
00416             CI->setDoesNotThrow();
00417         }
00418   }
00419 
00420   // If we are inlining through a 'nounwind' call site then any inlined 'unwind'
00421   // instructions are unreachable.
00422   if (InlinedFunctionInfo.ContainsUnwinds && MarkNoUnwind)
00423     for (Function::iterator BB = FirstNewBlock, E = Caller->end();
00424          BB != E; ++BB) {
00425       TerminatorInst *Term = BB->getTerminator();
00426       if (isa<UnwindInst>(Term)) {
00427         new UnreachableInst(Term);
00428         BB->getInstList().erase(Term);
00429       }
00430     }
00431 
00432   // If we are inlining for an invoke instruction, we must make sure to rewrite
00433   // any inlined 'unwind' instructions into branches to the invoke exception
00434   // destination, and call instructions into invoke instructions.
00435   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
00436     HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
00437 
00438   // If we cloned in _exactly one_ basic block, and if that block ends in a
00439   // return instruction, we splice the body of the inlined callee directly into
00440   // the calling basic block.
00441   if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
00442     // Move all of the instructions right before the call.
00443     OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
00444                                  FirstNewBlock->begin(), FirstNewBlock->end());
00445     // Remove the cloned basic block.
00446     Caller->getBasicBlockList().pop_back();
00447 
00448     // If the call site was an invoke instruction, add a branch to the normal
00449     // destination.
00450     if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
00451       BranchInst::Create(II->getNormalDest(), TheCall);
00452 
00453     // If the return instruction returned a value, replace uses of the call with
00454     // uses of the returned value.
00455     if (!TheCall->use_empty()) {
00456       ReturnInst *R = Returns[0];
00457       TheCall->replaceAllUsesWith(R->getReturnValue());
00458     }
00459     // Since we are now done with the Call/Invoke, we can delete it.
00460     TheCall->eraseFromParent();
00461 
00462     // Since we are now done with the return instruction, delete it also.
00463     Returns[0]->eraseFromParent();
00464 
00465     // We are now done with the inlining.
00466     return true;
00467   }
00468 
00469   // Otherwise, we have the normal case, of more than one block to inline or
00470   // multiple return sites.
00471 
00472   // We want to clone the entire callee function into the hole between the
00473   // "starter" and "ender" blocks.  How we accomplish this depends on whether
00474   // this is an invoke instruction or a call instruction.
00475   BasicBlock *AfterCallBB;
00476   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
00477 
00478     // Add an unconditional branch to make this look like the CallInst case...
00479     BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
00480 
00481     // Split the basic block.  This guarantees that no PHI nodes will have to be
00482     // updated due to new incoming edges, and make the invoke case more
00483     // symmetric to the call case.
00484     AfterCallBB = OrigBB->splitBasicBlock(NewBr,
00485                                           CalledFunc->getName()+".exit");
00486 
00487   } else {  // It's a call
00488     // If this is a call instruction, we need to split the basic block that
00489     // the call lives in.
00490     //
00491     AfterCallBB = OrigBB->splitBasicBlock(TheCall,
00492                                           CalledFunc->getName()+".exit");
00493   }
00494 
00495   // Change the branch that used to go to AfterCallBB to branch to the first
00496   // basic block of the inlined function.
00497   //
00498   TerminatorInst *Br = OrigBB->getTerminator();
00499   assert(Br && Br->getOpcode() == Instruction::Br &&
00500          "splitBasicBlock broken!");
00501   Br->setOperand(0, FirstNewBlock);
00502 
00503 
00504   // Now that the function is correct, make it a little bit nicer.  In
00505   // particular, move the basic blocks inserted from the end of the function
00506   // into the space made by splitting the source basic block.
00507   Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
00508                                      FirstNewBlock, Caller->end());
00509 
00510   // Handle all of the return instructions that we just cloned in, and eliminate
00511   // any users of the original call/invoke instruction.
00512   const Type *RTy = CalledFunc->getReturnType();
00513 
00514   if (Returns.size() > 1) {
00515     // The PHI node should go at the front of the new basic block to merge all
00516     // possible incoming values.
00517     PHINode *PHI = 0;
00518     if (!TheCall->use_empty()) {
00519       PHI = PHINode::Create(RTy, TheCall->getName(),
00520                             AfterCallBB->begin());
00521       // Anything that used the result of the function call should now use the
00522       // PHI node as their operand.
00523       TheCall->replaceAllUsesWith(PHI);
00524     }
00525 
00526     // Loop over all of the return instructions adding entries to the PHI node
00527     // as appropriate.
00528     if (PHI) {
00529       for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
00530         ReturnInst *RI = Returns[i];
00531         assert(RI->getReturnValue()->getType() == PHI->getType() &&
00532                "Ret value not consistent in function!");
00533         PHI->addIncoming(RI->getReturnValue(), RI->getParent());
00534       }
00535     }
00536 
00537     // Add a branch to the merge points and remove return instructions.
00538     for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
00539       ReturnInst *RI = Returns[i];
00540       BranchInst::Create(AfterCallBB, RI);
00541       RI->eraseFromParent();
00542     }
00543   } else if (!Returns.empty()) {
00544     // Otherwise, if there is exactly one return value, just replace anything
00545     // using the return value of the call with the computed value.
00546     if (!TheCall->use_empty())
00547       TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
00548 
00549     // Splice the code from the return block into the block that it will return
00550     // to, which contains the code that was after the call.
00551     BasicBlock *ReturnBB = Returns[0]->getParent();
00552     AfterCallBB->getInstList().splice(AfterCallBB->begin(),
00553                                       ReturnBB->getInstList());
00554 
00555     // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
00556     ReturnBB->replaceAllUsesWith(AfterCallBB);
00557 
00558     // Delete the return instruction now and empty ReturnBB now.
00559     Returns[0]->eraseFromParent();
00560     ReturnBB->eraseFromParent();
00561   } else if (!TheCall->use_empty()) {
00562     // No returns, but something is using the return value of the call.  Just
00563     // nuke the result.
00564     TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
00565   }
00566 
00567   // Since we are now done with the Call/Invoke, we can delete it.
00568   TheCall->eraseFromParent();
00569 
00570   // We should always be able to fold the entry block of the function into the
00571   // single predecessor of the block...
00572   assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
00573   BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
00574 
00575   // Splice the code entry block into calling block, right before the
00576   // unconditional branch.
00577   OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
00578   CalleeEntry->replaceAllUsesWith(OrigBB);  // Update PHI nodes
00579 
00580   // Remove the unconditional branch.
00581   OrigBB->getInstList().erase(Br);
00582 
00583   // Now we can remove the CalleeEntry block, which is now empty.
00584   Caller->getBasicBlockList().erase(CalleeEntry);
00585 
00586   return true;
00587 }