InlineFunction.cpp revision 206274
172339Sabial//===- InlineFunction.cpp - Code to perform function inlining -------------===//
272339Sabial//
372339Sabial//                     The LLVM Compiler Infrastructure
472339Sabial//
572339Sabial// This file is distributed under the University of Illinois Open Source
672339Sabial// License. See LICENSE.TXT for details.
772339Sabial//
872339Sabial//===----------------------------------------------------------------------===//
972339Sabial//
1072339Sabial// This file implements inlining of a function into a call site, resolving
1172339Sabial// parameters and the return value as appropriate.
1272339Sabial//
1372339Sabial//===----------------------------------------------------------------------===//
1472339Sabial
1572339Sabial#include "llvm/Transforms/Utils/Cloning.h"
1672339Sabial#include "llvm/Constants.h"
1772339Sabial#include "llvm/DerivedTypes.h"
1872339Sabial#include "llvm/LLVMContext.h"
1972339Sabial#include "llvm/Module.h"
2072339Sabial#include "llvm/Instructions.h"
2172339Sabial#include "llvm/IntrinsicInst.h"
2272339Sabial#include "llvm/Intrinsics.h"
2372339Sabial#include "llvm/Attributes.h"
2472339Sabial#include "llvm/Analysis/CallGraph.h"
2572339Sabial#include "llvm/Analysis/DebugInfo.h"
2672339Sabial#include "llvm/Target/TargetData.h"
2772339Sabial#include "llvm/ADT/SmallVector.h"
2872339Sabial#include "llvm/ADT/StringExtras.h"
2972339Sabial#include "llvm/Support/CallSite.h"
3072339Sabialusing namespace llvm;
3172339Sabial
3272339Sabialbool llvm::InlineFunction(CallInst *CI, CallGraph *CG, const TargetData *TD,
3372339Sabial                          SmallVectorImpl<AllocaInst*> *StaticAllocas) {
3472339Sabial  return InlineFunction(CallSite(CI), CG, TD, StaticAllocas);
3572339Sabial}
3672339Sabialbool llvm::InlineFunction(InvokeInst *II, CallGraph *CG, const TargetData *TD,
3772339Sabial                          SmallVectorImpl<AllocaInst*> *StaticAllocas) {
3872339Sabial  return InlineFunction(CallSite(II), CG, TD, StaticAllocas);
3972339Sabial}
4072339Sabial
4172339Sabial
4272339Sabial/// HandleCallsInBlockInlinedThroughInvoke - When we inline a basic block into
4372339Sabial/// an invoke, we have to turn all of the calls that can throw into
4472339Sabial/// invokes.  This function analyze BB to see if there are any calls, and if so,
4572339Sabial/// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
4672339Sabial/// nodes in that block with the values specified in InvokeDestPHIValues.
4772339Sabial///
4872339Sabialstatic void HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB,
4972339Sabial                                                   BasicBlock *InvokeDest,
5072339Sabial                           const SmallVectorImpl<Value*> &InvokeDestPHIValues) {
5172339Sabial  for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
5272339Sabial    Instruction *I = BBI++;
5372339Sabial
5472339Sabial    // We only need to check for function calls: inlined invoke
5572339Sabial    // instructions require no special handling.
5672339Sabial    CallInst *CI = dyn_cast<CallInst>(I);
5772339Sabial    if (CI == 0) continue;
5872339Sabial
5972339Sabial    // If this call cannot unwind, don't convert it to an invoke.
6072339Sabial    if (CI->doesNotThrow())
6172339Sabial      continue;
6272339Sabial
6372339Sabial    // Convert this function call into an invoke instruction.
6472339Sabial    // First, split the basic block.
6572339Sabial    BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
6672339Sabial
6772339Sabial    // Next, create the new invoke instruction, inserting it at the end
6872339Sabial    // of the old basic block.
6972339Sabial    SmallVector<Value*, 8> InvokeArgs(CI->op_begin()+1, CI->op_end());
7072339Sabial    InvokeInst *II =
7172339Sabial      InvokeInst::Create(CI->getCalledValue(), Split, InvokeDest,
7272339Sabial                         InvokeArgs.begin(), InvokeArgs.end(),
7372339Sabial                         CI->getName(), BB->getTerminator());
7472339Sabial    II->setCallingConv(CI->getCallingConv());
7572339Sabial    II->setAttributes(CI->getAttributes());
7672339Sabial
7772339Sabial    // Make sure that anything using the call now uses the invoke!  This also
7872339Sabial    // updates the CallGraph if present.
7972339Sabial    CI->replaceAllUsesWith(II);
8072339Sabial
8172339Sabial    // Delete the unconditional branch inserted by splitBasicBlock
8272339Sabial    BB->getInstList().pop_back();
8372339Sabial    Split->getInstList().pop_front();  // Delete the original call
8472339Sabial
8572339Sabial    // Update any PHI nodes in the exceptional block to indicate that
8672339Sabial    // there is now a new entry in them.
8772339Sabial    unsigned i = 0;
8872339Sabial    for (BasicBlock::iterator I = InvokeDest->begin();
8972339Sabial         isa<PHINode>(I); ++I, ++i)
9072339Sabial      cast<PHINode>(I)->addIncoming(InvokeDestPHIValues[i], BB);
9172339Sabial
9272339Sabial    // This basic block is now complete, the caller will continue scanning the
9372339Sabial    // next one.
9472339Sabial    return;
9572339Sabial  }
9672339Sabial}
9772339Sabial
9872339Sabial
9972339Sabial/// HandleInlinedInvoke - If we inlined an invoke site, we need to convert calls
10072339Sabial/// in the body of the inlined function into invokes and turn unwind
10172339Sabial/// instructions into branches to the invoke unwind dest.
10272339Sabial///
10372339Sabial/// II is the invoke instruction being inlined.  FirstNewBlock is the first
10472339Sabial/// block of the inlined code (the last block is the end of the function),
10572339Sabial/// and InlineCodeInfo is information about the code that got inlined.
10672339Sabialstatic void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
10772339Sabial                                ClonedCodeInfo &InlinedCodeInfo) {
10872339Sabial  BasicBlock *InvokeDest = II->getUnwindDest();
10972339Sabial  SmallVector<Value*, 8> InvokeDestPHIValues;
11072339Sabial
11172339Sabial  // If there are PHI nodes in the unwind destination block, we need to
11272339Sabial  // keep track of which values came into them from this invoke, then remove
11372339Sabial  // the entry for this block.
11472339Sabial  BasicBlock *InvokeBlock = II->getParent();
11572339Sabial  for (BasicBlock::iterator I = InvokeDest->begin(); isa<PHINode>(I); ++I) {
11672339Sabial    PHINode *PN = cast<PHINode>(I);
11772339Sabial    // Save the value to use for this edge.
11872339Sabial    InvokeDestPHIValues.push_back(PN->getIncomingValueForBlock(InvokeBlock));
11972339Sabial  }
12072339Sabial
12172339Sabial  Function *Caller = FirstNewBlock->getParent();
12272339Sabial
12372339Sabial  // The inlined code is currently at the end of the function, scan from the
12472339Sabial  // start of the inlined code to its end, checking for stuff we need to
12572339Sabial  // rewrite.  If the code doesn't have calls or unwinds, we know there is
12672339Sabial  // nothing to rewrite.
12772339Sabial  if (!InlinedCodeInfo.ContainsCalls && !InlinedCodeInfo.ContainsUnwinds) {
12872339Sabial    // Now that everything is happy, we have one final detail.  The PHI nodes in
12972339Sabial    // the exception destination block still have entries due to the original
13072339Sabial    // invoke instruction.  Eliminate these entries (which might even delete the
13172339Sabial    // PHI node) now.
13272339Sabial    InvokeDest->removePredecessor(II->getParent());
13372339Sabial    return;
13472339Sabial  }
13572339Sabial
13672339Sabial  for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; ++BB){
13772339Sabial    if (InlinedCodeInfo.ContainsCalls)
13872339Sabial      HandleCallsInBlockInlinedThroughInvoke(BB, InvokeDest,
13972339Sabial                                             InvokeDestPHIValues);
14072339Sabial
14172339Sabial    if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
14272339Sabial      // An UnwindInst requires special handling when it gets inlined into an
14372339Sabial      // invoke site.  Once this happens, we know that the unwind would cause
14472339Sabial      // a control transfer to the invoke exception destination, so we can
14572339Sabial      // transform it into a direct branch to the exception destination.
14672339Sabial      BranchInst::Create(InvokeDest, UI);
14772339Sabial
14872339Sabial      // Delete the unwind instruction!
14972339Sabial      UI->eraseFromParent();
15072339Sabial
15172339Sabial      // Update any PHI nodes in the exceptional block to indicate that
15272339Sabial      // there is now a new entry in them.
15372339Sabial      unsigned i = 0;
15472339Sabial      for (BasicBlock::iterator I = InvokeDest->begin();
15572339Sabial           isa<PHINode>(I); ++I, ++i) {
15672339Sabial        PHINode *PN = cast<PHINode>(I);
15772339Sabial        PN->addIncoming(InvokeDestPHIValues[i], BB);
15872339Sabial      }
15972339Sabial    }
16072339Sabial  }
16172339Sabial
16272339Sabial  // Now that everything is happy, we have one final detail.  The PHI nodes in
16372339Sabial  // the exception destination block still have entries due to the original
16472339Sabial  // invoke instruction.  Eliminate these entries (which might even delete the
16572339Sabial  // PHI node) now.
16672339Sabial  InvokeDest->removePredecessor(II->getParent());
16772339Sabial}
16872339Sabial
16972339Sabial/// UpdateCallGraphAfterInlining - Once we have cloned code over from a callee
17072339Sabial/// into the caller, update the specified callgraph to reflect the changes we
17172339Sabial/// made.  Note that it's possible that not all code was copied over, so only
17272339Sabial/// some edges of the callgraph may remain.
17372339Sabialstatic void UpdateCallGraphAfterInlining(CallSite CS,
17472339Sabial                                         Function::iterator FirstNewBlock,
17572339Sabial                                       DenseMap<const Value*, Value*> &ValueMap,
17672339Sabial                                         CallGraph &CG) {
17772339Sabial  const Function *Caller = CS.getInstruction()->getParent()->getParent();
17872339Sabial  const Function *Callee = CS.getCalledFunction();
17972339Sabial  CallGraphNode *CalleeNode = CG[Callee];
18072339Sabial  CallGraphNode *CallerNode = CG[Caller];
18172339Sabial
18272339Sabial  // Since we inlined some uninlined call sites in the callee into the caller,
18372339Sabial  // add edges from the caller to all of the callees of the callee.
18472339Sabial  CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
18572339Sabial
18672339Sabial  // Consider the case where CalleeNode == CallerNode.
18772339Sabial  CallGraphNode::CalledFunctionsVector CallCache;
18872339Sabial  if (CalleeNode == CallerNode) {
18972339Sabial    CallCache.assign(I, E);
19072339Sabial    I = CallCache.begin();
19172339Sabial    E = CallCache.end();
19272339Sabial  }
19372339Sabial
19472339Sabial  for (; I != E; ++I) {
19572339Sabial    const Value *OrigCall = I->first;
19672339Sabial
19772339Sabial    DenseMap<const Value*, Value*>::iterator VMI = ValueMap.find(OrigCall);
19872339Sabial    // Only copy the edge if the call was inlined!
19972339Sabial    if (VMI == ValueMap.end() || VMI->second == 0)
20072339Sabial      continue;
20172339Sabial
20272339Sabial    // If the call was inlined, but then constant folded, there is no edge to
20372339Sabial    // add.  Check for this case.
20472339Sabial    if (Instruction *NewCall = dyn_cast<Instruction>(VMI->second))
20572339Sabial      CallerNode->addCalledFunction(CallSite::get(NewCall), I->second);
20672339Sabial  }
20772339Sabial
20872339Sabial  // Update the call graph by deleting the edge from Callee to Caller.  We must
20972339Sabial  // do this after the loop above in case Caller and Callee are the same.
21072339Sabial  CallerNode->removeCallEdgeFor(CS);
21172339Sabial}
21272339Sabial
21372339Sabial// InlineFunction - This function inlines the called function into the basic
21472339Sabial// block of the caller.  This returns false if it is not possible to inline this
21572339Sabial// call.  The program is still in a well defined state if this occurs though.
21672339Sabial//
21772339Sabial// Note that this only does one level of inlining.  For example, if the
21872339Sabial// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
21972339Sabial// exists in the instruction stream.  Similiarly this will inline a recursive
22072339Sabial// function by one level.
22172339Sabial//
22272339Sabialbool llvm::InlineFunction(CallSite CS, CallGraph *CG, const TargetData *TD,
22372339Sabial                          SmallVectorImpl<AllocaInst*> *StaticAllocas) {
22472339Sabial  Instruction *TheCall = CS.getInstruction();
22572339Sabial  LLVMContext &Context = TheCall->getContext();
22672339Sabial  assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
22772339Sabial         "Instruction not in function!");
22872339Sabial
22972339Sabial  const Function *CalledFunc = CS.getCalledFunction();
23072339Sabial  if (CalledFunc == 0 ||          // Can't inline external function or indirect
23172339Sabial      CalledFunc->isDeclaration() || // call, or call to a vararg function!
23272339Sabial      CalledFunc->getFunctionType()->isVarArg()) return false;
23372339Sabial
23472339Sabial
23572339Sabial  // If the call to the callee is not a tail call, we must clear the 'tail'
23672339Sabial  // flags on any calls that we inline.
23772339Sabial  bool MustClearTailCallFlags =
23872339Sabial    !(isa<CallInst>(TheCall) && cast<CallInst>(TheCall)->isTailCall());
23972339Sabial
24072339Sabial  // If the call to the callee cannot throw, set the 'nounwind' flag on any
24172339Sabial  // calls that we inline.
24272339Sabial  bool MarkNoUnwind = CS.doesNotThrow();
24372339Sabial
24472339Sabial  BasicBlock *OrigBB = TheCall->getParent();
24572339Sabial  Function *Caller = OrigBB->getParent();
24672339Sabial
24772339Sabial  // GC poses two hazards to inlining, which only occur when the callee has GC:
24872339Sabial  //  1. If the caller has no GC, then the callee's GC must be propagated to the
24972339Sabial  //     caller.
25072339Sabial  //  2. If the caller has a differing GC, it is invalid to inline.
25172339Sabial  if (CalledFunc->hasGC()) {
25272339Sabial    if (!Caller->hasGC())
25372339Sabial      Caller->setGC(CalledFunc->getGC());
25472339Sabial    else if (CalledFunc->getGC() != Caller->getGC())
25572339Sabial      return false;
25672339Sabial  }
25772339Sabial
25872339Sabial  // Get an iterator to the last basic block in the function, which will have
25972339Sabial  // the new function inlined after it.
26072339Sabial  //
26172339Sabial  Function::iterator LastBlock = &Caller->back();
26272339Sabial
26372339Sabial  // Make sure to capture all of the return instructions from the cloned
26472339Sabial  // function.
26572339Sabial  SmallVector<ReturnInst*, 8> Returns;
26672339Sabial  ClonedCodeInfo InlinedFunctionInfo;
26772339Sabial  Function::iterator FirstNewBlock;
26872339Sabial
26972339Sabial  { // Scope to destroy ValueMap after cloning.
27072339Sabial    DenseMap<const Value*, Value*> ValueMap;
27172339Sabial
27272339Sabial    assert(CalledFunc->arg_size() == CS.arg_size() &&
27372339Sabial           "No varargs calls can be inlined!");
27472339Sabial
27572339Sabial    // Calculate the vector of arguments to pass into the function cloner, which
27672339Sabial    // matches up the formal to the actual argument values.
27772339Sabial    CallSite::arg_iterator AI = CS.arg_begin();
27872339Sabial    unsigned ArgNo = 0;
27972339Sabial    for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
28072339Sabial         E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
28172339Sabial      Value *ActualArg = *AI;
28272339Sabial
28372339Sabial      // When byval arguments actually inlined, we need to make the copy implied
28472339Sabial      // by them explicit.  However, we don't do this if the callee is readonly
28572339Sabial      // or readnone, because the copy would be unneeded: the callee doesn't
28672339Sabial      // modify the struct.
28772339Sabial      if (CalledFunc->paramHasAttr(ArgNo+1, Attribute::ByVal) &&
28872339Sabial          !CalledFunc->onlyReadsMemory()) {
28972339Sabial        const Type *AggTy = cast<PointerType>(I->getType())->getElementType();
29072339Sabial        const Type *VoidPtrTy =
29172339Sabial            Type::getInt8PtrTy(Context);
29272339Sabial
29372339Sabial        // Create the alloca.  If we have TargetData, use nice alignment.
29472339Sabial        unsigned Align = 1;
29572339Sabial        if (TD) Align = TD->getPrefTypeAlignment(AggTy);
29672339Sabial        Value *NewAlloca = new AllocaInst(AggTy, 0, Align,
29772339Sabial                                          I->getName(),
29872339Sabial                                          &*Caller->begin()->begin());
29972339Sabial        // Emit a memcpy.
30072339Sabial        const Type *Tys[3] = {VoidPtrTy, VoidPtrTy, Type::getInt64Ty(Context)};
30172339Sabial        Function *MemCpyFn = Intrinsic::getDeclaration(Caller->getParent(),
30272339Sabial                                                       Intrinsic::memcpy,
30372339Sabial                                                       Tys, 3);
30472339Sabial        Value *DestCast = new BitCastInst(NewAlloca, VoidPtrTy, "tmp", TheCall);
30572339Sabial        Value *SrcCast = new BitCastInst(*AI, VoidPtrTy, "tmp", TheCall);
30672339Sabial
30772339Sabial        Value *Size;
30872339Sabial        if (TD == 0)
30972339Sabial          Size = ConstantExpr::getSizeOf(AggTy);
31072339Sabial        else
31172339Sabial          Size = ConstantInt::get(Type::getInt64Ty(Context),
31272339Sabial                                  TD->getTypeStoreSize(AggTy));
31372339Sabial
31472339Sabial        // Always generate a memcpy of alignment 1 here because we don't know
31572339Sabial        // the alignment of the src pointer.  Other optimizations can infer
31672339Sabial        // better alignment.
31772339Sabial        Value *CallArgs[] = {
31872339Sabial          DestCast, SrcCast, Size,
31972339Sabial          ConstantInt::get(Type::getInt32Ty(Context), 1),
32072339Sabial          ConstantInt::get(Type::getInt1Ty(Context), 0)
32172339Sabial        };
32272339Sabial        CallInst *TheMemCpy =
32372339Sabial          CallInst::Create(MemCpyFn, CallArgs, CallArgs+5, "", TheCall);
32472339Sabial
32572339Sabial        // If we have a call graph, update it.
32672339Sabial        if (CG) {
32772339Sabial          CallGraphNode *MemCpyCGN = CG->getOrInsertFunction(MemCpyFn);
32872339Sabial          CallGraphNode *CallerNode = (*CG)[Caller];
32972339Sabial          CallerNode->addCalledFunction(TheMemCpy, MemCpyCGN);
33072339Sabial        }
33172339Sabial
33272339Sabial        // Uses of the argument in the function should use our new alloca
33372339Sabial        // instead.
33472339Sabial        ActualArg = NewAlloca;
33572339Sabial      }
33672339Sabial
33772339Sabial      ValueMap[I] = ActualArg;
33872339Sabial    }
33972339Sabial
34072339Sabial    // We want the inliner to prune the code as it copies.  We would LOVE to
34172339Sabial    // have no dead or constant instructions leftover after inlining occurs
34272339Sabial    // (which can happen, e.g., because an argument was constant), but we'll be
34372339Sabial    // happy with whatever the cloner can do.
34472339Sabial    CloneAndPruneFunctionInto(Caller, CalledFunc, ValueMap, Returns, ".i",
34572339Sabial                              &InlinedFunctionInfo, TD, TheCall);
34672339Sabial
34772339Sabial    // Remember the first block that is newly cloned over.
34872339Sabial    FirstNewBlock = LastBlock; ++FirstNewBlock;
34972339Sabial
35072339Sabial    // Update the callgraph if requested.
35172339Sabial    if (CG)
35272339Sabial      UpdateCallGraphAfterInlining(CS, FirstNewBlock, ValueMap, *CG);
35372339Sabial  }
35472339Sabial
35572339Sabial  // If there are any alloca instructions in the block that used to be the entry
35672339Sabial  // block for the callee, move them to the entry block of the caller.  First
35772339Sabial  // calculate which instruction they should be inserted before.  We insert the
35872339Sabial  // instructions at the end of the current alloca list.
35972339Sabial  //
36072339Sabial  {
36172339Sabial    BasicBlock::iterator InsertPoint = Caller->begin()->begin();
36272339Sabial    for (BasicBlock::iterator I = FirstNewBlock->begin(),
36372339Sabial         E = FirstNewBlock->end(); I != E; ) {
36472339Sabial      AllocaInst *AI = dyn_cast<AllocaInst>(I++);
36572339Sabial      if (AI == 0) continue;
36672339Sabial
36772339Sabial      // If the alloca is now dead, remove it.  This often occurs due to code
36872339Sabial      // specialization.
36972339Sabial      if (AI->use_empty()) {
37072339Sabial        AI->eraseFromParent();
37172339Sabial        continue;
37272339Sabial      }
37372339Sabial
37472339Sabial      if (!isa<Constant>(AI->getArraySize()))
37572339Sabial        continue;
37672339Sabial
37772339Sabial      // Keep track of the static allocas that we inline into the caller if the
37872339Sabial      // StaticAllocas pointer is non-null.
37972339Sabial      if (StaticAllocas) StaticAllocas->push_back(AI);
38072339Sabial
38172339Sabial      // Scan for the block of allocas that we can move over, and move them
38272339Sabial      // all at once.
38372339Sabial      while (isa<AllocaInst>(I) &&
38472339Sabial             isa<Constant>(cast<AllocaInst>(I)->getArraySize())) {
38572339Sabial        if (StaticAllocas) StaticAllocas->push_back(cast<AllocaInst>(I));
38672339Sabial        ++I;
38772339Sabial      }
38872339Sabial
38972339Sabial      // Transfer all of the allocas over in a block.  Using splice means
39072339Sabial      // that the instructions aren't removed from the symbol table, then
39172339Sabial      // reinserted.
39272339Sabial      Caller->getEntryBlock().getInstList().splice(InsertPoint,
39372339Sabial                                                   FirstNewBlock->getInstList(),
39472339Sabial                                                   AI, I);
39572339Sabial    }
39672339Sabial  }
39772339Sabial
39872339Sabial  // If the inlined code contained dynamic alloca instructions, wrap the inlined
39972339Sabial  // code with llvm.stacksave/llvm.stackrestore intrinsics.
40072339Sabial  if (InlinedFunctionInfo.ContainsDynamicAllocas) {
40172339Sabial    Module *M = Caller->getParent();
40272339Sabial    // Get the two intrinsics we care about.
40372339Sabial    Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
40472339Sabial    Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
40572339Sabial
40672339Sabial    // If we are preserving the callgraph, add edges to the stacksave/restore
40772339Sabial    // functions for the calls we insert.
40872339Sabial    CallGraphNode *StackSaveCGN = 0, *StackRestoreCGN = 0, *CallerNode = 0;
40972339Sabial    if (CG) {
41072339Sabial      StackSaveCGN    = CG->getOrInsertFunction(StackSave);
41172339Sabial      StackRestoreCGN = CG->getOrInsertFunction(StackRestore);
41272339Sabial      CallerNode = (*CG)[Caller];
41372339Sabial    }
41472339Sabial
41572339Sabial    // Insert the llvm.stacksave.
41672339Sabial    CallInst *SavedPtr = CallInst::Create(StackSave, "savedstack",
41772339Sabial                                          FirstNewBlock->begin());
41872339Sabial    if (CG) CallerNode->addCalledFunction(SavedPtr, StackSaveCGN);
41972339Sabial
42072339Sabial    // Insert a call to llvm.stackrestore before any return instructions in the
42172339Sabial    // inlined function.
42272339Sabial    for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
42372339Sabial      CallInst *CI = CallInst::Create(StackRestore, SavedPtr, "", Returns[i]);
42472339Sabial      if (CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
42572339Sabial    }
42672339Sabial
42772339Sabial    // Count the number of StackRestore calls we insert.
42872339Sabial    unsigned NumStackRestores = Returns.size();
42972339Sabial
43072339Sabial    // If we are inlining an invoke instruction, insert restores before each
43172339Sabial    // unwind.  These unwinds will be rewritten into branches later.
43272339Sabial    if (InlinedFunctionInfo.ContainsUnwinds && isa<InvokeInst>(TheCall)) {
43372339Sabial      for (Function::iterator BB = FirstNewBlock, E = Caller->end();
43472339Sabial           BB != E; ++BB)
43572339Sabial        if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
43672339Sabial          CallInst *CI = CallInst::Create(StackRestore, SavedPtr, "", UI);
43772339Sabial          if (CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
43872339Sabial          ++NumStackRestores;
43972339Sabial        }
44072339Sabial    }
44172339Sabial  }
44272339Sabial
44372339Sabial  // If we are inlining tail call instruction through a call site that isn't
44472339Sabial  // marked 'tail', we must remove the tail marker for any calls in the inlined
44572339Sabial  // code.  Also, calls inlined through a 'nounwind' call site should be marked
44672339Sabial  // 'nounwind'.
44772339Sabial  if (InlinedFunctionInfo.ContainsCalls &&
44872339Sabial      (MustClearTailCallFlags || MarkNoUnwind)) {
44972339Sabial    for (Function::iterator BB = FirstNewBlock, E = Caller->end();
45072339Sabial         BB != E; ++BB)
45172339Sabial      for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
45272339Sabial        if (CallInst *CI = dyn_cast<CallInst>(I)) {
45372339Sabial          if (MustClearTailCallFlags)
45472339Sabial            CI->setTailCall(false);
45572339Sabial          if (MarkNoUnwind)
45672339Sabial            CI->setDoesNotThrow();
45772339Sabial        }
45872339Sabial  }
45972339Sabial
46072339Sabial  // If we are inlining through a 'nounwind' call site then any inlined 'unwind'
46172339Sabial  // instructions are unreachable.
46272339Sabial  if (InlinedFunctionInfo.ContainsUnwinds && MarkNoUnwind)
46372339Sabial    for (Function::iterator BB = FirstNewBlock, E = Caller->end();
46472339Sabial         BB != E; ++BB) {
46572339Sabial      TerminatorInst *Term = BB->getTerminator();
46672339Sabial      if (isa<UnwindInst>(Term)) {
46772339Sabial        new UnreachableInst(Context, Term);
46872339Sabial        BB->getInstList().erase(Term);
46972339Sabial      }
47072339Sabial    }
47172339Sabial
47272339Sabial  // If we are inlining for an invoke instruction, we must make sure to rewrite
47372339Sabial  // any inlined 'unwind' instructions into branches to the invoke exception
47472339Sabial  // destination, and call instructions into invoke instructions.
47572339Sabial  if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
47672339Sabial    HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
47772339Sabial
47872339Sabial  // If we cloned in _exactly one_ basic block, and if that block ends in a
47972339Sabial  // return instruction, we splice the body of the inlined callee directly into
48072339Sabial  // the calling basic block.
48172339Sabial  if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
48272339Sabial    // Move all of the instructions right before the call.
48372339Sabial    OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
48472339Sabial                                 FirstNewBlock->begin(), FirstNewBlock->end());
48572339Sabial    // Remove the cloned basic block.
48672339Sabial    Caller->getBasicBlockList().pop_back();
48772339Sabial
48872339Sabial    // If the call site was an invoke instruction, add a branch to the normal
48972339Sabial    // destination.
49072339Sabial    if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
49172339Sabial      BranchInst::Create(II->getNormalDest(), TheCall);
49272339Sabial
49372339Sabial    // If the return instruction returned a value, replace uses of the call with
49472339Sabial    // uses of the returned value.
49572339Sabial    if (!TheCall->use_empty()) {
49672339Sabial      ReturnInst *R = Returns[0];
49772339Sabial      if (TheCall == R->getReturnValue())
49872339Sabial        TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
49972339Sabial      else
50072339Sabial        TheCall->replaceAllUsesWith(R->getReturnValue());
50172339Sabial    }
50272339Sabial    // Since we are now done with the Call/Invoke, we can delete it.
50372339Sabial    TheCall->eraseFromParent();
50472339Sabial
50572339Sabial    // Since we are now done with the return instruction, delete it also.
50672339Sabial    Returns[0]->eraseFromParent();
50772339Sabial
50872339Sabial    // We are now done with the inlining.
50972339Sabial    return true;
51072339Sabial  }
51172339Sabial
51272339Sabial  // Otherwise, we have the normal case, of more than one block to inline or
51372339Sabial  // multiple return sites.
51472339Sabial
51572339Sabial  // We want to clone the entire callee function into the hole between the
51672339Sabial  // "starter" and "ender" blocks.  How we accomplish this depends on whether
51772339Sabial  // this is an invoke instruction or a call instruction.
51872339Sabial  BasicBlock *AfterCallBB;
51972339Sabial  if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
52072339Sabial
52172339Sabial    // Add an unconditional branch to make this look like the CallInst case...
52272339Sabial    BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
52372339Sabial
52472339Sabial    // Split the basic block.  This guarantees that no PHI nodes will have to be
52572339Sabial    // updated due to new incoming edges, and make the invoke case more
52672339Sabial    // symmetric to the call case.
52772339Sabial    AfterCallBB = OrigBB->splitBasicBlock(NewBr,
52872339Sabial                                          CalledFunc->getName()+".exit");
52972339Sabial
53072339Sabial  } else {  // It's a call
53172339Sabial    // If this is a call instruction, we need to split the basic block that
53272339Sabial    // the call lives in.
53372339Sabial    //
53472339Sabial    AfterCallBB = OrigBB->splitBasicBlock(TheCall,
53572339Sabial                                          CalledFunc->getName()+".exit");
53672339Sabial  }
53772339Sabial
53872339Sabial  // Change the branch that used to go to AfterCallBB to branch to the first
53972339Sabial  // basic block of the inlined function.
54072339Sabial  //
54172339Sabial  TerminatorInst *Br = OrigBB->getTerminator();
54272339Sabial  assert(Br && Br->getOpcode() == Instruction::Br &&
54372339Sabial         "splitBasicBlock broken!");
54472339Sabial  Br->setOperand(0, FirstNewBlock);
54572339Sabial
54672339Sabial
54772339Sabial  // Now that the function is correct, make it a little bit nicer.  In
54872339Sabial  // particular, move the basic blocks inserted from the end of the function
54972339Sabial  // into the space made by splitting the source basic block.
55072339Sabial  Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
55172339Sabial                                     FirstNewBlock, Caller->end());
55272339Sabial
55372339Sabial  // Handle all of the return instructions that we just cloned in, and eliminate
55472339Sabial  // any users of the original call/invoke instruction.
55572339Sabial  const Type *RTy = CalledFunc->getReturnType();
55672339Sabial
55772339Sabial  if (Returns.size() > 1) {
55872339Sabial    // The PHI node should go at the front of the new basic block to merge all
55972339Sabial    // possible incoming values.
56072339Sabial    PHINode *PHI = 0;
56172339Sabial    if (!TheCall->use_empty()) {
56272339Sabial      PHI = PHINode::Create(RTy, TheCall->getName(),
56372339Sabial                            AfterCallBB->begin());
56472339Sabial      // Anything that used the result of the function call should now use the
56572339Sabial      // PHI node as their operand.
56672339Sabial      TheCall->replaceAllUsesWith(PHI);
56772339Sabial    }
56872339Sabial
56972339Sabial    // Loop over all of the return instructions adding entries to the PHI node
57072339Sabial    // as appropriate.
57172339Sabial    if (PHI) {
57272339Sabial      for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
57372339Sabial        ReturnInst *RI = Returns[i];
57472339Sabial        assert(RI->getReturnValue()->getType() == PHI->getType() &&
57572339Sabial               "Ret value not consistent in function!");
57672339Sabial        PHI->addIncoming(RI->getReturnValue(), RI->getParent());
57772339Sabial      }
57872339Sabial
57972339Sabial      // Now that we inserted the PHI, check to see if it has a single value
58072339Sabial      // (e.g. all the entries are the same or undef).  If so, remove the PHI so
58172339Sabial      // it doesn't block other optimizations.
58272339Sabial      if (Value *V = PHI->hasConstantValue()) {
58372339Sabial        PHI->replaceAllUsesWith(V);
58472339Sabial        PHI->eraseFromParent();
58572339Sabial      }
58672339Sabial    }
58772339Sabial
58872339Sabial
58972339Sabial    // Add a branch to the merge points and remove return instructions.
59072339Sabial    for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
59172339Sabial      ReturnInst *RI = Returns[i];
59272339Sabial      BranchInst::Create(AfterCallBB, RI);
59372339Sabial      RI->eraseFromParent();
59472339Sabial    }
59572339Sabial  } else if (!Returns.empty()) {
59672339Sabial    // Otherwise, if there is exactly one return value, just replace anything
59772339Sabial    // using the return value of the call with the computed value.
59872339Sabial    if (!TheCall->use_empty()) {
59972339Sabial      if (TheCall == Returns[0]->getReturnValue())
60072339Sabial        TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
60172339Sabial      else
60272339Sabial        TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
60372339Sabial    }
60472339Sabial
60572339Sabial    // Splice the code from the return block into the block that it will return
60672339Sabial    // to, which contains the code that was after the call.
60772339Sabial    BasicBlock *ReturnBB = Returns[0]->getParent();
60872339Sabial    AfterCallBB->getInstList().splice(AfterCallBB->begin(),
60972339Sabial                                      ReturnBB->getInstList());
61072339Sabial
61172339Sabial    // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
61272339Sabial    ReturnBB->replaceAllUsesWith(AfterCallBB);
61372339Sabial
61472339Sabial    // Delete the return instruction now and empty ReturnBB now.
61572339Sabial    Returns[0]->eraseFromParent();
61672339Sabial    ReturnBB->eraseFromParent();
61772339Sabial  } else if (!TheCall->use_empty()) {
61872339Sabial    // No returns, but something is using the return value of the call.  Just
61972339Sabial    // nuke the result.
62072339Sabial    TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
62172339Sabial  }
62272339Sabial
62372339Sabial  // Since we are now done with the Call/Invoke, we can delete it.
62472339Sabial  TheCall->eraseFromParent();
62572339Sabial
62672339Sabial  // We should always be able to fold the entry block of the function into the
62772339Sabial  // single predecessor of the block...
62872339Sabial  assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
62972339Sabial  BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
63072339Sabial
63172339Sabial  // Splice the code entry block into calling block, right before the
63272339Sabial  // unconditional branch.
63372339Sabial  OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
63472339Sabial  CalleeEntry->replaceAllUsesWith(OrigBB);  // Update PHI nodes
63572339Sabial
63672339Sabial  // Remove the unconditional branch.
63772339Sabial  OrigBB->getInstList().erase(Br);
63872339Sabial
63972339Sabial  // Now we can remove the CalleeEntry block, which is now empty.
64072339Sabial  Caller->getBasicBlockList().erase(CalleeEntry);
64172339Sabial
64272339Sabial  return true;
64372339Sabial}
64472339Sabial