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 was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source 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/Analysis/CallGraph.h"
00022 #include "llvm/Support/CallSite.h"
00023 using namespace llvm;
00024 
00025 bool llvm::InlineFunction(CallInst *CI, CallGraph *CG) {
00026   return InlineFunction(CallSite(CI), CG);
00027 }
00028 bool llvm::InlineFunction(InvokeInst *II, CallGraph *CG) {
00029   return InlineFunction(CallSite(II), CG);
00030 }
00031 
00032 /// HandleInlinedInvoke - If we inlined an invoke site, we need to convert calls
00033 /// in the body of the inlined function into invokes and turn unwind
00034 /// instructions into branches to the invoke unwind dest.
00035 ///
00036 /// II is the invoke instruction begin inlined.  FirstNewBlock is the first
00037 /// block of the inlined code (the last block is the end of the function),
00038 /// and InlineCodeInfo is information about the code that got inlined.
00039 static void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
00040                                 ClonedCodeInfo &InlinedCodeInfo) {
00041   BasicBlock *InvokeDest = II->getUnwindDest();
00042   std::vector<Value*> InvokeDestPHIValues;
00043 
00044   // If there are PHI nodes in the unwind destination block, we need to
00045   // keep track of which values came into them from this invoke, then remove
00046   // the entry for this block.
00047   BasicBlock *InvokeBlock = II->getParent();
00048   for (BasicBlock::iterator I = InvokeDest->begin(); isa<PHINode>(I); ++I) {
00049     PHINode *PN = cast<PHINode>(I);
00050     // Save the value to use for this edge.
00051     InvokeDestPHIValues.push_back(PN->getIncomingValueForBlock(InvokeBlock));
00052   }
00053 
00054   Function *Caller = FirstNewBlock->getParent();
00055   
00056   // The inlined code is currently at the end of the function, scan from the
00057   // start of the inlined code to its end, checking for stuff we need to
00058   // rewrite.
00059   if (InlinedCodeInfo.ContainsCalls || InlinedCodeInfo.ContainsUnwinds) {
00060     for (Function::iterator BB = FirstNewBlock, E = Caller->end();
00061          BB != E; ++BB) {
00062       if (InlinedCodeInfo.ContainsCalls) {
00063         for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ){
00064           Instruction *I = BBI++;
00065           
00066           // We only need to check for function calls: inlined invoke
00067           // instructions require no special handling.
00068           if (!isa<CallInst>(I)) continue;
00069           CallInst *CI = cast<CallInst>(I);
00070 
00071           // If this is an intrinsic function call, don't convert it to an
00072           // invoke.
00073           if (CI->getCalledFunction() &&
00074               CI->getCalledFunction()->getIntrinsicID())
00075             continue;
00076           
00077           // Convert this function call into an invoke instruction.
00078           // First, split the basic block.
00079           BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
00080           
00081           // Next, create the new invoke instruction, inserting it at the end
00082           // of the old basic block.
00083           InvokeInst *II =
00084             new InvokeInst(CI->getCalledValue(), Split, InvokeDest,
00085                            std::vector<Value*>(CI->op_begin()+1, CI->op_end()),
00086                            CI->getName(), BB->getTerminator());
00087           II->setCallingConv(CI->getCallingConv());
00088           
00089           // Make sure that anything using the call now uses the invoke!
00090           CI->replaceAllUsesWith(II);
00091           
00092           // Delete the unconditional branch inserted by splitBasicBlock
00093           BB->getInstList().pop_back();
00094           Split->getInstList().pop_front();  // Delete the original call
00095           
00096           // Update any PHI nodes in the exceptional block to indicate that
00097           // there is now a new entry in them.
00098           unsigned i = 0;
00099           for (BasicBlock::iterator I = InvokeDest->begin();
00100                isa<PHINode>(I); ++I, ++i) {
00101             PHINode *PN = cast<PHINode>(I);
00102             PN->addIncoming(InvokeDestPHIValues[i], BB);
00103           }
00104             
00105           // This basic block is now complete, start scanning the next one.
00106           break;
00107         }
00108       }
00109       
00110       if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
00111         // An UnwindInst requires special handling when it gets inlined into an
00112         // invoke site.  Once this happens, we know that the unwind would cause
00113         // a control transfer to the invoke exception destination, so we can
00114         // transform it into a direct branch to the exception destination.
00115         new BranchInst(InvokeDest, UI);
00116         
00117         // Delete the unwind instruction!
00118         UI->getParent()->getInstList().pop_back();
00119         
00120         // Update any PHI nodes in the exceptional block to indicate that
00121         // there is now a new entry in them.
00122         unsigned i = 0;
00123         for (BasicBlock::iterator I = InvokeDest->begin();
00124              isa<PHINode>(I); ++I, ++i) {
00125           PHINode *PN = cast<PHINode>(I);
00126           PN->addIncoming(InvokeDestPHIValues[i], BB);
00127         }
00128       }
00129     }
00130   }
00131 
00132   // Now that everything is happy, we have one final detail.  The PHI nodes in
00133   // the exception destination block still have entries due to the original
00134   // invoke instruction.  Eliminate these entries (which might even delete the
00135   // PHI node) now.
00136   InvokeDest->removePredecessor(II->getParent());
00137 }
00138 
00139 /// UpdateCallGraphAfterInlining - Once we have cloned code over from a callee
00140 /// into the caller, update the specified callgraph to reflect the changes we
00141 /// made.  Note that it's possible that not all code was copied over, so only
00142 /// some edges of the callgraph will be remain.
00143 static void UpdateCallGraphAfterInlining(const Function *Caller,
00144                                          const Function *Callee,
00145                                          Function::iterator FirstNewBlock,
00146                                        std::map<const Value*, Value*> &ValueMap,
00147                                          CallGraph &CG) {
00148   // Update the call graph by deleting the edge from Callee to Caller
00149   CallGraphNode *CalleeNode = CG[Callee];
00150   CallGraphNode *CallerNode = CG[Caller];
00151   CallerNode->removeCallEdgeTo(CalleeNode);
00152   
00153   // Since we inlined some uninlined call sites in the callee into the caller,
00154   // add edges from the caller to all of the callees of the callee.
00155   for (CallGraphNode::iterator I = CalleeNode->begin(),
00156        E = CalleeNode->end(); I != E; ++I) {
00157     const Instruction *OrigCall = I->first.getInstruction();
00158     
00159     std::map<const Value*, Value*>::iterator VMI = ValueMap.find(OrigCall);
00160     // Only copy the edge if the call was inlined!
00161     if (VMI != ValueMap.end() && VMI->second) {
00162       // If the call was inlined, but then constant folded, there is no edge to
00163       // add.  Check for this case.
00164       if (Instruction *NewCall = dyn_cast<Instruction>(VMI->second))
00165         CallerNode->addCalledFunction(CallSite::get(NewCall), I->second);
00166     }
00167   }
00168 }
00169 
00170 
00171 // InlineFunction - This function inlines the called function into the basic
00172 // block of the caller.  This returns false if it is not possible to inline this
00173 // call.  The program is still in a well defined state if this occurs though.
00174 //
00175 // Note that this only does one level of inlining.  For example, if the
00176 // instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
00177 // exists in the instruction stream.  Similiarly this will inline a recursive
00178 // function by one level.
00179 //
00180 bool llvm::InlineFunction(CallSite CS, CallGraph *CG) {
00181   Instruction *TheCall = CS.getInstruction();
00182   assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
00183          "Instruction not in function!");
00184 
00185   const Function *CalledFunc = CS.getCalledFunction();
00186   if (CalledFunc == 0 ||          // Can't inline external function or indirect
00187       CalledFunc->isExternal() || // call, or call to a vararg function!
00188       CalledFunc->getFunctionType()->isVarArg()) return false;
00189 
00190 
00191   // If the call to the callee is a non-tail call, we must clear the 'tail'
00192   // flags on any calls that we inline.
00193   bool MustClearTailCallFlags =
00194     isa<CallInst>(TheCall) && !cast<CallInst>(TheCall)->isTailCall();
00195 
00196   BasicBlock *OrigBB = TheCall->getParent();
00197   Function *Caller = OrigBB->getParent();
00198 
00199   // Get an iterator to the last basic block in the function, which will have
00200   // the new function inlined after it.
00201   //
00202   Function::iterator LastBlock = &Caller->back();
00203 
00204   // Make sure to capture all of the return instructions from the cloned
00205   // function.
00206   std::vector<ReturnInst*> Returns;
00207   ClonedCodeInfo InlinedFunctionInfo;
00208   Function::iterator FirstNewBlock;
00209   
00210   { // Scope to destroy ValueMap after cloning.
00211     std::map<const Value*, Value*> ValueMap;
00212 
00213     // Calculate the vector of arguments to pass into the function cloner, which
00214     // matches up the formal to the actual argument values.
00215     assert(std::distance(CalledFunc->arg_begin(), CalledFunc->arg_end()) ==
00216            std::distance(CS.arg_begin(), CS.arg_end()) &&
00217            "No varargs calls can be inlined!");
00218     CallSite::arg_iterator AI = CS.arg_begin();
00219     for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
00220            E = CalledFunc->arg_end(); I != E; ++I, ++AI)
00221       ValueMap[I] = *AI;
00222 
00223     // We want the inliner to prune the code as it copies.  We would LOVE to
00224     // have no dead or constant instructions leftover after inlining occurs
00225     // (which can happen, e.g., because an argument was constant), but we'll be
00226     // happy with whatever the cloner can do.
00227     CloneAndPruneFunctionInto(Caller, CalledFunc, ValueMap, Returns, ".i",
00228                               &InlinedFunctionInfo);
00229     
00230     // Remember the first block that is newly cloned over.
00231     FirstNewBlock = LastBlock; ++FirstNewBlock;
00232     
00233     // Update the callgraph if requested.
00234     if (CG)
00235       UpdateCallGraphAfterInlining(Caller, CalledFunc, FirstNewBlock, ValueMap,
00236                                    *CG);
00237   }
00238  
00239   // If there are any alloca instructions in the block that used to be the entry
00240   // block for the callee, move them to the entry block of the caller.  First
00241   // calculate which instruction they should be inserted before.  We insert the
00242   // instructions at the end of the current alloca list.
00243   //
00244   {
00245     BasicBlock::iterator InsertPoint = Caller->begin()->begin();
00246     for (BasicBlock::iterator I = FirstNewBlock->begin(),
00247            E = FirstNewBlock->end(); I != E; )
00248       if (AllocaInst *AI = dyn_cast<AllocaInst>(I++))
00249         if (isa<Constant>(AI->getArraySize())) {
00250           // Scan for the block of allocas that we can move over, and move them
00251           // all at once.
00252           while (isa<AllocaInst>(I) &&
00253                  isa<Constant>(cast<AllocaInst>(I)->getArraySize()))
00254             ++I;
00255 
00256           // Transfer all of the allocas over in a block.  Using splice means
00257           // that they instructions aren't removed from the symbol table, then
00258           // reinserted.
00259           Caller->front().getInstList().splice(InsertPoint,
00260                                                FirstNewBlock->getInstList(),
00261                                                AI, I);
00262         }
00263   }
00264 
00265   // If the inlined code contained dynamic alloca instructions, wrap the inlined
00266   // code with llvm.stacksave/llvm.stackrestore intrinsics.
00267   if (InlinedFunctionInfo.ContainsDynamicAllocas) {
00268     Module *M = Caller->getParent();
00269     const Type *SBytePtr = PointerType::get(Type::SByteTy);
00270     // Get the two intrinsics we care about.
00271     Function *StackSave, *StackRestore;
00272     StackSave    = M->getOrInsertFunction("llvm.stacksave", SBytePtr, NULL);
00273     StackRestore = M->getOrInsertFunction("llvm.stackrestore", Type::VoidTy,
00274                                           SBytePtr, NULL);
00275 
00276     // If we are preserving the callgraph, add edges to the stacksave/restore
00277     // functions for the calls we insert.
00278     CallGraphNode *StackSaveCGN = 0, *StackRestoreCGN = 0, *CallerNode = 0;
00279     if (CG) {
00280       StackSaveCGN    = CG->getOrInsertFunction(StackSave);
00281       StackRestoreCGN = CG->getOrInsertFunction(StackRestore);
00282       CallerNode = (*CG)[Caller];
00283     }
00284       
00285     // Insert the llvm.stacksave.
00286     CallInst *SavedPtr = new CallInst(StackSave, "savedstack", 
00287                                       FirstNewBlock->begin());
00288     if (CG) CallerNode->addCalledFunction(SavedPtr, StackSaveCGN);
00289       
00290     // Insert a call to llvm.stackrestore before any return instructions in the
00291     // inlined function.
00292     for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
00293       CallInst *CI = new CallInst(StackRestore, SavedPtr, "", Returns[i]);
00294       if (CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
00295     }
00296 
00297     // Count the number of StackRestore calls we insert.
00298     unsigned NumStackRestores = Returns.size();
00299     
00300     // If we are inlining an invoke instruction, insert restores before each
00301     // unwind.  These unwinds will be rewritten into branches later.
00302     if (InlinedFunctionInfo.ContainsUnwinds && isa<InvokeInst>(TheCall)) {
00303       for (Function::iterator BB = FirstNewBlock, E = Caller->end();
00304            BB != E; ++BB)
00305         if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
00306           new CallInst(StackRestore, SavedPtr, "", UI);
00307           ++NumStackRestores;
00308         }
00309     }
00310   }
00311 
00312   // If we are inlining tail call instruction through a call site that isn't 
00313   // marked 'tail', we must remove the tail marker for any calls in the inlined
00314   // code.
00315   if (MustClearTailCallFlags && InlinedFunctionInfo.ContainsCalls) {
00316     for (Function::iterator BB = FirstNewBlock, E = Caller->end();
00317          BB != E; ++BB)
00318       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
00319         if (CallInst *CI = dyn_cast<CallInst>(I))
00320           CI->setTailCall(false);
00321   }
00322 
00323   // If we are inlining for an invoke instruction, we must make sure to rewrite
00324   // any inlined 'unwind' instructions into branches to the invoke exception
00325   // destination, and call instructions into invoke instructions.
00326   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
00327     HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
00328 
00329   // If we cloned in _exactly one_ basic block, and if that block ends in a
00330   // return instruction, we splice the body of the inlined callee directly into
00331   // the calling basic block.
00332   if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
00333     // Move all of the instructions right before the call.
00334     OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
00335                                  FirstNewBlock->begin(), FirstNewBlock->end());
00336     // Remove the cloned basic block.
00337     Caller->getBasicBlockList().pop_back();
00338 
00339     // If the call site was an invoke instruction, add a branch to the normal
00340     // destination.
00341     if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
00342       new BranchInst(II->getNormalDest(), TheCall);
00343 
00344     // If the return instruction returned a value, replace uses of the call with
00345     // uses of the returned value.
00346     if (!TheCall->use_empty())
00347       TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
00348 
00349     // Since we are now done with the Call/Invoke, we can delete it.
00350     TheCall->getParent()->getInstList().erase(TheCall);
00351 
00352     // Since we are now done with the return instruction, delete it also.
00353     Returns[0]->getParent()->getInstList().erase(Returns[0]);
00354 
00355     // We are now done with the inlining.
00356     return true;
00357   }
00358 
00359   // Otherwise, we have the normal case, of more than one block to inline or
00360   // multiple return sites.
00361 
00362   // We want to clone the entire callee function into the hole between the
00363   // "starter" and "ender" blocks.  How we accomplish this depends on whether
00364   // this is an invoke instruction or a call instruction.
00365   BasicBlock *AfterCallBB;
00366   if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
00367 
00368     // Add an unconditional branch to make this look like the CallInst case...
00369     BranchInst *NewBr = new BranchInst(II->getNormalDest(), TheCall);
00370 
00371     // Split the basic block.  This guarantees that no PHI nodes will have to be
00372     // updated due to new incoming edges, and make the invoke case more
00373     // symmetric to the call case.
00374     AfterCallBB = OrigBB->splitBasicBlock(NewBr,
00375                                           CalledFunc->getName()+".exit");
00376 
00377   } else {  // It's a call
00378     // If this is a call instruction, we need to split the basic block that
00379     // the call lives in.
00380     //
00381     AfterCallBB = OrigBB->splitBasicBlock(TheCall,
00382                                           CalledFunc->getName()+".exit");
00383   }
00384 
00385   // Change the branch that used to go to AfterCallBB to branch to the first
00386   // basic block of the inlined function.
00387   //
00388   TerminatorInst *Br = OrigBB->getTerminator();
00389   assert(Br && Br->getOpcode() == Instruction::Br &&
00390          "splitBasicBlock broken!");
00391   Br->setOperand(0, FirstNewBlock);
00392 
00393 
00394   // Now that the function is correct, make it a little bit nicer.  In
00395   // particular, move the basic blocks inserted from the end of the function
00396   // into the space made by splitting the source basic block.
00397   //
00398   Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
00399                                      FirstNewBlock, Caller->end());
00400 
00401   // Handle all of the return instructions that we just cloned in, and eliminate
00402   // any users of the original call/invoke instruction.
00403   if (Returns.size() > 1) {
00404     // The PHI node should go at the front of the new basic block to merge all
00405     // possible incoming values.
00406     //
00407     PHINode *PHI = 0;
00408     if (!TheCall->use_empty()) {
00409       PHI = new PHINode(CalledFunc->getReturnType(),
00410                         TheCall->getName(), AfterCallBB->begin());
00411 
00412       // Anything that used the result of the function call should now use the
00413       // PHI node as their operand.
00414       //
00415       TheCall->replaceAllUsesWith(PHI);
00416     }
00417 
00418     // Loop over all of the return instructions, turning them into unconditional
00419     // branches to the merge point now, and adding entries to the PHI node as
00420     // appropriate.
00421     for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
00422       ReturnInst *RI = Returns[i];
00423 
00424       if (PHI) {
00425         assert(RI->getReturnValue() && "Ret should have value!");
00426         assert(RI->getReturnValue()->getType() == PHI->getType() &&
00427                "Ret value not consistent in function!");
00428         PHI->addIncoming(RI->getReturnValue(), RI->getParent());
00429       }
00430 
00431       // Add a branch to the merge point where the PHI node lives if it exists.
00432       new BranchInst(AfterCallBB, RI);
00433 
00434       // Delete the return instruction now
00435       RI->getParent()->getInstList().erase(RI);
00436     }
00437 
00438   } else if (!Returns.empty()) {
00439     // Otherwise, if there is exactly one return value, just replace anything
00440     // using the return value of the call with the computed value.
00441     if (!TheCall->use_empty())
00442       TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
00443 
00444     // Splice the code from the return block into the block that it will return
00445     // to, which contains the code that was after the call.
00446     BasicBlock *ReturnBB = Returns[0]->getParent();
00447     AfterCallBB->getInstList().splice(AfterCallBB->begin(),
00448                                       ReturnBB->getInstList());
00449 
00450     // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
00451     ReturnBB->replaceAllUsesWith(AfterCallBB);
00452 
00453     // Delete the return instruction now and empty ReturnBB now.
00454     Returns[0]->eraseFromParent();
00455     ReturnBB->eraseFromParent();
00456   } else if (!TheCall->use_empty()) {
00457     // No returns, but something is using the return value of the call.  Just
00458     // nuke the result.
00459     TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
00460   }
00461 
00462   // Since we are now done with the Call/Invoke, we can delete it.
00463   TheCall->eraseFromParent();
00464 
00465   // We should always be able to fold the entry block of the function into the
00466   // single predecessor of the block...
00467   assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
00468   BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
00469 
00470   // Splice the code entry block into calling block, right before the
00471   // unconditional branch.
00472   OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
00473   CalleeEntry->replaceAllUsesWith(OrigBB);  // Update PHI nodes
00474 
00475   // Remove the unconditional branch.
00476   OrigBB->getInstList().erase(Br);
00477 
00478   // Now we can remove the CalleeEntry block, which is now empty.
00479   Caller->getBasicBlockList().erase(CalleeEntry);
00480   
00481   return true;
00482 }