InlineFunction.cpp revision b957a5e41ed6288f4d033167f6413621a09655ee
1//===- InlineFunction.cpp - Code to perform function inlining -------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements inlining of a function into a call site, resolving
11// parameters and the return value as appropriate.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/Cloning.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/Module.h"
19#include "llvm/Instructions.h"
20#include "llvm/IntrinsicInst.h"
21#include "llvm/Intrinsics.h"
22#include "llvm/Attributes.h"
23#include "llvm/Analysis/CallGraph.h"
24#include "llvm/Analysis/DebugInfo.h"
25#include "llvm/Target/TargetData.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/StringExtras.h"
28#include "llvm/Support/CallSite.h"
29using namespace llvm;
30
31bool llvm::InlineFunction(CallInst *CI, CallGraph *CG, const TargetData *TD,
32                          SmallVectorImpl<AllocaInst*> *StaticAllocas) {
33  return InlineFunction(CallSite(CI), CG, TD, StaticAllocas);
34}
35bool llvm::InlineFunction(InvokeInst *II, CallGraph *CG, const TargetData *TD,
36                          SmallVectorImpl<AllocaInst*> *StaticAllocas) {
37  return InlineFunction(CallSite(II), CG, TD, StaticAllocas);
38}
39
40
41/// HandleCallsInBlockInlinedThroughInvoke - When we inline a basic block into
42/// an invoke, we have to turn all of the calls that can throw into
43/// invokes.  This function analyze BB to see if there are any calls, and if so,
44/// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
45/// nodes in that block with the values specified in InvokeDestPHIValues.
46///
47static void HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB,
48                                                   BasicBlock *InvokeDest,
49                           const SmallVectorImpl<Value*> &InvokeDestPHIValues) {
50  for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
51    Instruction *I = BBI++;
52
53    // We only need to check for function calls: inlined invoke
54    // instructions require no special handling.
55    CallInst *CI = dyn_cast<CallInst>(I);
56    if (CI == 0) continue;
57
58    // If this call cannot unwind, don't convert it to an invoke.
59    if (CI->doesNotThrow())
60      continue;
61
62    // Convert this function call into an invoke instruction.
63    // First, split the basic block.
64    BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
65
66    // Next, create the new invoke instruction, inserting it at the end
67    // of the old basic block.
68    SmallVector<Value*, 8> InvokeArgs(CI->op_begin()+1, CI->op_end());
69    InvokeInst *II =
70      InvokeInst::Create(CI->getCalledValue(), Split, InvokeDest,
71                         InvokeArgs.begin(), InvokeArgs.end(),
72                         CI->getName(), BB->getTerminator());
73    II->setCallingConv(CI->getCallingConv());
74    II->setAttributes(CI->getAttributes());
75
76    // Make sure that anything using the call now uses the invoke!  This also
77    // updates the CallGraph if present.
78    CI->replaceAllUsesWith(II);
79
80    // Delete the unconditional branch inserted by splitBasicBlock
81    BB->getInstList().pop_back();
82    Split->getInstList().pop_front();  // Delete the original call
83
84    // Update any PHI nodes in the exceptional block to indicate that
85    // there is now a new entry in them.
86    unsigned i = 0;
87    for (BasicBlock::iterator I = InvokeDest->begin();
88         isa<PHINode>(I); ++I, ++i)
89      cast<PHINode>(I)->addIncoming(InvokeDestPHIValues[i], BB);
90
91    // This basic block is now complete, the caller will continue scanning the
92    // next one.
93    return;
94  }
95}
96
97
98/// HandleInlinedInvoke - If we inlined an invoke site, we need to convert calls
99/// in the body of the inlined function into invokes and turn unwind
100/// instructions into branches to the invoke unwind dest.
101///
102/// II is the invoke instruction being inlined.  FirstNewBlock is the first
103/// block of the inlined code (the last block is the end of the function),
104/// and InlineCodeInfo is information about the code that got inlined.
105static void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
106                                ClonedCodeInfo &InlinedCodeInfo) {
107  BasicBlock *InvokeDest = II->getUnwindDest();
108  SmallVector<Value*, 8> InvokeDestPHIValues;
109
110  // If there are PHI nodes in the unwind destination block, we need to
111  // keep track of which values came into them from this invoke, then remove
112  // the entry for this block.
113  BasicBlock *InvokeBlock = II->getParent();
114  for (BasicBlock::iterator I = InvokeDest->begin(); isa<PHINode>(I); ++I) {
115    PHINode *PN = cast<PHINode>(I);
116    // Save the value to use for this edge.
117    InvokeDestPHIValues.push_back(PN->getIncomingValueForBlock(InvokeBlock));
118  }
119
120  Function *Caller = FirstNewBlock->getParent();
121
122  // The inlined code is currently at the end of the function, scan from the
123  // start of the inlined code to its end, checking for stuff we need to
124  // rewrite.  If the code doesn't have calls or unwinds, we know there is
125  // nothing to rewrite.
126  if (!InlinedCodeInfo.ContainsCalls && !InlinedCodeInfo.ContainsUnwinds) {
127    // Now that everything is happy, we have one final detail.  The PHI nodes in
128    // the exception destination block still have entries due to the original
129    // invoke instruction.  Eliminate these entries (which might even delete the
130    // PHI node) now.
131    InvokeDest->removePredecessor(II->getParent());
132    return;
133  }
134
135  for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; ++BB){
136    if (InlinedCodeInfo.ContainsCalls)
137      HandleCallsInBlockInlinedThroughInvoke(BB, InvokeDest,
138                                             InvokeDestPHIValues);
139
140    if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
141      // An UnwindInst requires special handling when it gets inlined into an
142      // invoke site.  Once this happens, we know that the unwind would cause
143      // a control transfer to the invoke exception destination, so we can
144      // transform it into a direct branch to the exception destination.
145      BranchInst::Create(InvokeDest, UI);
146
147      // Delete the unwind instruction!
148      UI->eraseFromParent();
149
150      // Update any PHI nodes in the exceptional block to indicate that
151      // there is now a new entry in them.
152      unsigned i = 0;
153      for (BasicBlock::iterator I = InvokeDest->begin();
154           isa<PHINode>(I); ++I, ++i) {
155        PHINode *PN = cast<PHINode>(I);
156        PN->addIncoming(InvokeDestPHIValues[i], BB);
157      }
158    }
159  }
160
161  // Now that everything is happy, we have one final detail.  The PHI nodes in
162  // the exception destination block still have entries due to the original
163  // invoke instruction.  Eliminate these entries (which might even delete the
164  // PHI node) now.
165  InvokeDest->removePredecessor(II->getParent());
166}
167
168/// UpdateCallGraphAfterInlining - Once we have cloned code over from a callee
169/// into the caller, update the specified callgraph to reflect the changes we
170/// made.  Note that it's possible that not all code was copied over, so only
171/// some edges of the callgraph may remain.
172static void UpdateCallGraphAfterInlining(CallSite CS,
173                                         Function::iterator FirstNewBlock,
174                                       DenseMap<const Value*, Value*> &ValueMap,
175                                         CallGraph &CG) {
176  const Function *Caller = CS.getInstruction()->getParent()->getParent();
177  const Function *Callee = CS.getCalledFunction();
178  CallGraphNode *CalleeNode = CG[Callee];
179  CallGraphNode *CallerNode = CG[Caller];
180
181  // Since we inlined some uninlined call sites in the callee into the caller,
182  // add edges from the caller to all of the callees of the callee.
183  CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
184
185  // Consider the case where CalleeNode == CallerNode.
186  CallGraphNode::CalledFunctionsVector CallCache;
187  if (CalleeNode == CallerNode) {
188    CallCache.assign(I, E);
189    I = CallCache.begin();
190    E = CallCache.end();
191  }
192
193  for (; I != E; ++I) {
194    const Value *OrigCall = I->first;
195
196    DenseMap<const Value*, Value*>::iterator VMI = ValueMap.find(OrigCall);
197    // Only copy the edge if the call was inlined!
198    if (VMI == ValueMap.end() || VMI->second == 0)
199      continue;
200
201    // If the call was inlined, but then constant folded, there is no edge to
202    // add.  Check for this case.
203    Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
204    if (NewCall == 0) continue;
205
206    // It's possible that inlining the callsite will cause it to go from an
207    // indirect to a direct call by resolving a function pointer.  If this
208    // happens, set the callee of the new call site to a more precise
209    // destination.  This can also happen if the call graph node of the caller
210    // was just unnecessarily imprecise.
211    if (I->second->getFunction() == 0)
212      if (Function *F = CallSite(NewCall).getCalledFunction()) {
213        // Indirect call site resolved to direct call.
214        CallerNode->addCalledFunction(CallSite::get(NewCall), CG[F]);
215        continue;
216      }
217
218    CallerNode->addCalledFunction(CallSite::get(NewCall), I->second);
219  }
220
221  // Update the call graph by deleting the edge from Callee to Caller.  We must
222  // do this after the loop above in case Caller and Callee are the same.
223  CallerNode->removeCallEdgeFor(CS);
224}
225
226// InlineFunction - This function inlines the called function into the basic
227// block of the caller.  This returns false if it is not possible to inline this
228// call.  The program is still in a well defined state if this occurs though.
229//
230// Note that this only does one level of inlining.  For example, if the
231// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
232// exists in the instruction stream.  Similiarly this will inline a recursive
233// function by one level.
234//
235bool llvm::InlineFunction(CallSite CS, CallGraph *CG, const TargetData *TD,
236                          SmallVectorImpl<AllocaInst*> *StaticAllocas) {
237  Instruction *TheCall = CS.getInstruction();
238  LLVMContext &Context = TheCall->getContext();
239  assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
240         "Instruction not in function!");
241
242  const Function *CalledFunc = CS.getCalledFunction();
243  if (CalledFunc == 0 ||          // Can't inline external function or indirect
244      CalledFunc->isDeclaration() || // call, or call to a vararg function!
245      CalledFunc->getFunctionType()->isVarArg()) return false;
246
247
248  // If the call to the callee is not a tail call, we must clear the 'tail'
249  // flags on any calls that we inline.
250  bool MustClearTailCallFlags =
251    !(isa<CallInst>(TheCall) && cast<CallInst>(TheCall)->isTailCall());
252
253  // If the call to the callee cannot throw, set the 'nounwind' flag on any
254  // calls that we inline.
255  bool MarkNoUnwind = CS.doesNotThrow();
256
257  BasicBlock *OrigBB = TheCall->getParent();
258  Function *Caller = OrigBB->getParent();
259
260  // GC poses two hazards to inlining, which only occur when the callee has GC:
261  //  1. If the caller has no GC, then the callee's GC must be propagated to the
262  //     caller.
263  //  2. If the caller has a differing GC, it is invalid to inline.
264  if (CalledFunc->hasGC()) {
265    if (!Caller->hasGC())
266      Caller->setGC(CalledFunc->getGC());
267    else if (CalledFunc->getGC() != Caller->getGC())
268      return false;
269  }
270
271  // Get an iterator to the last basic block in the function, which will have
272  // the new function inlined after it.
273  //
274  Function::iterator LastBlock = &Caller->back();
275
276  // Make sure to capture all of the return instructions from the cloned
277  // function.
278  SmallVector<ReturnInst*, 8> Returns;
279  ClonedCodeInfo InlinedFunctionInfo;
280  Function::iterator FirstNewBlock;
281
282  { // Scope to destroy ValueMap after cloning.
283    DenseMap<const Value*, Value*> ValueMap;
284
285    assert(CalledFunc->arg_size() == CS.arg_size() &&
286           "No varargs calls can be inlined!");
287
288    // Calculate the vector of arguments to pass into the function cloner, which
289    // matches up the formal to the actual argument values.
290    CallSite::arg_iterator AI = CS.arg_begin();
291    unsigned ArgNo = 0;
292    for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
293         E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
294      Value *ActualArg = *AI;
295
296      // When byval arguments actually inlined, we need to make the copy implied
297      // by them explicit.  However, we don't do this if the callee is readonly
298      // or readnone, because the copy would be unneeded: the callee doesn't
299      // modify the struct.
300      if (CalledFunc->paramHasAttr(ArgNo+1, Attribute::ByVal) &&
301          !CalledFunc->onlyReadsMemory()) {
302        const Type *AggTy = cast<PointerType>(I->getType())->getElementType();
303        const Type *VoidPtrTy =
304            Type::getInt8PtrTy(Context);
305
306        // Create the alloca.  If we have TargetData, use nice alignment.
307        unsigned Align = 1;
308        if (TD) Align = TD->getPrefTypeAlignment(AggTy);
309        Value *NewAlloca = new AllocaInst(AggTy, 0, Align,
310                                          I->getName(),
311                                          &*Caller->begin()->begin());
312        // Emit a memcpy.
313        const Type *Tys[3] = {VoidPtrTy, VoidPtrTy, Type::getInt64Ty(Context)};
314        Function *MemCpyFn = Intrinsic::getDeclaration(Caller->getParent(),
315                                                       Intrinsic::memcpy,
316                                                       Tys, 3);
317        Value *DestCast = new BitCastInst(NewAlloca, VoidPtrTy, "tmp", TheCall);
318        Value *SrcCast = new BitCastInst(*AI, VoidPtrTy, "tmp", TheCall);
319
320        Value *Size;
321        if (TD == 0)
322          Size = ConstantExpr::getSizeOf(AggTy);
323        else
324          Size = ConstantInt::get(Type::getInt64Ty(Context),
325                                  TD->getTypeStoreSize(AggTy));
326
327        // Always generate a memcpy of alignment 1 here because we don't know
328        // the alignment of the src pointer.  Other optimizations can infer
329        // better alignment.
330        Value *CallArgs[] = {
331          DestCast, SrcCast, Size,
332          ConstantInt::get(Type::getInt32Ty(Context), 1),
333          ConstantInt::get(Type::getInt1Ty(Context), 0)
334        };
335        CallInst *TheMemCpy =
336          CallInst::Create(MemCpyFn, CallArgs, CallArgs+5, "", TheCall);
337
338        // If we have a call graph, update it.
339        if (CG) {
340          CallGraphNode *MemCpyCGN = CG->getOrInsertFunction(MemCpyFn);
341          CallGraphNode *CallerNode = (*CG)[Caller];
342          CallerNode->addCalledFunction(TheMemCpy, MemCpyCGN);
343        }
344
345        // Uses of the argument in the function should use our new alloca
346        // instead.
347        ActualArg = NewAlloca;
348      }
349
350      ValueMap[I] = ActualArg;
351    }
352
353    // We want the inliner to prune the code as it copies.  We would LOVE to
354    // have no dead or constant instructions leftover after inlining occurs
355    // (which can happen, e.g., because an argument was constant), but we'll be
356    // happy with whatever the cloner can do.
357    CloneAndPruneFunctionInto(Caller, CalledFunc, ValueMap, Returns, ".i",
358                              &InlinedFunctionInfo, TD, TheCall);
359
360    // Remember the first block that is newly cloned over.
361    FirstNewBlock = LastBlock; ++FirstNewBlock;
362
363    // Update the callgraph if requested.
364    if (CG)
365      UpdateCallGraphAfterInlining(CS, FirstNewBlock, ValueMap, *CG);
366  }
367
368  // If there are any alloca instructions in the block that used to be the entry
369  // block for the callee, move them to the entry block of the caller.  First
370  // calculate which instruction they should be inserted before.  We insert the
371  // instructions at the end of the current alloca list.
372  //
373  {
374    BasicBlock::iterator InsertPoint = Caller->begin()->begin();
375    for (BasicBlock::iterator I = FirstNewBlock->begin(),
376         E = FirstNewBlock->end(); I != E; ) {
377      AllocaInst *AI = dyn_cast<AllocaInst>(I++);
378      if (AI == 0) continue;
379
380      // If the alloca is now dead, remove it.  This often occurs due to code
381      // specialization.
382      if (AI->use_empty()) {
383        AI->eraseFromParent();
384        continue;
385      }
386
387      if (!isa<Constant>(AI->getArraySize()))
388        continue;
389
390      // Keep track of the static allocas that we inline into the caller if the
391      // StaticAllocas pointer is non-null.
392      if (StaticAllocas) StaticAllocas->push_back(AI);
393
394      // Scan for the block of allocas that we can move over, and move them
395      // all at once.
396      while (isa<AllocaInst>(I) &&
397             isa<Constant>(cast<AllocaInst>(I)->getArraySize())) {
398        if (StaticAllocas) StaticAllocas->push_back(cast<AllocaInst>(I));
399        ++I;
400      }
401
402      // Transfer all of the allocas over in a block.  Using splice means
403      // that the instructions aren't removed from the symbol table, then
404      // reinserted.
405      Caller->getEntryBlock().getInstList().splice(InsertPoint,
406                                                   FirstNewBlock->getInstList(),
407                                                   AI, I);
408    }
409  }
410
411  // If the inlined code contained dynamic alloca instructions, wrap the inlined
412  // code with llvm.stacksave/llvm.stackrestore intrinsics.
413  if (InlinedFunctionInfo.ContainsDynamicAllocas) {
414    Module *M = Caller->getParent();
415    // Get the two intrinsics we care about.
416    Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
417    Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
418
419    // If we are preserving the callgraph, add edges to the stacksave/restore
420    // functions for the calls we insert.
421    CallGraphNode *StackSaveCGN = 0, *StackRestoreCGN = 0, *CallerNode = 0;
422    if (CG) {
423      StackSaveCGN    = CG->getOrInsertFunction(StackSave);
424      StackRestoreCGN = CG->getOrInsertFunction(StackRestore);
425      CallerNode = (*CG)[Caller];
426    }
427
428    // Insert the llvm.stacksave.
429    CallInst *SavedPtr = CallInst::Create(StackSave, "savedstack",
430                                          FirstNewBlock->begin());
431    if (CG) CallerNode->addCalledFunction(SavedPtr, StackSaveCGN);
432
433    // Insert a call to llvm.stackrestore before any return instructions in the
434    // inlined function.
435    for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
436      CallInst *CI = CallInst::Create(StackRestore, SavedPtr, "", Returns[i]);
437      if (CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
438    }
439
440    // Count the number of StackRestore calls we insert.
441    unsigned NumStackRestores = Returns.size();
442
443    // If we are inlining an invoke instruction, insert restores before each
444    // unwind.  These unwinds will be rewritten into branches later.
445    if (InlinedFunctionInfo.ContainsUnwinds && isa<InvokeInst>(TheCall)) {
446      for (Function::iterator BB = FirstNewBlock, E = Caller->end();
447           BB != E; ++BB)
448        if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
449          CallInst *CI = CallInst::Create(StackRestore, SavedPtr, "", UI);
450          if (CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
451          ++NumStackRestores;
452        }
453    }
454  }
455
456  // If we are inlining tail call instruction through a call site that isn't
457  // marked 'tail', we must remove the tail marker for any calls in the inlined
458  // code.  Also, calls inlined through a 'nounwind' call site should be marked
459  // 'nounwind'.
460  if (InlinedFunctionInfo.ContainsCalls &&
461      (MustClearTailCallFlags || MarkNoUnwind)) {
462    for (Function::iterator BB = FirstNewBlock, E = Caller->end();
463         BB != E; ++BB)
464      for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
465        if (CallInst *CI = dyn_cast<CallInst>(I)) {
466          if (MustClearTailCallFlags)
467            CI->setTailCall(false);
468          if (MarkNoUnwind)
469            CI->setDoesNotThrow();
470        }
471  }
472
473  // If we are inlining through a 'nounwind' call site then any inlined 'unwind'
474  // instructions are unreachable.
475  if (InlinedFunctionInfo.ContainsUnwinds && MarkNoUnwind)
476    for (Function::iterator BB = FirstNewBlock, E = Caller->end();
477         BB != E; ++BB) {
478      TerminatorInst *Term = BB->getTerminator();
479      if (isa<UnwindInst>(Term)) {
480        new UnreachableInst(Context, Term);
481        BB->getInstList().erase(Term);
482      }
483    }
484
485  // If we are inlining for an invoke instruction, we must make sure to rewrite
486  // any inlined 'unwind' instructions into branches to the invoke exception
487  // destination, and call instructions into invoke instructions.
488  if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
489    HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
490
491  // If we cloned in _exactly one_ basic block, and if that block ends in a
492  // return instruction, we splice the body of the inlined callee directly into
493  // the calling basic block.
494  if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
495    // Move all of the instructions right before the call.
496    OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
497                                 FirstNewBlock->begin(), FirstNewBlock->end());
498    // Remove the cloned basic block.
499    Caller->getBasicBlockList().pop_back();
500
501    // If the call site was an invoke instruction, add a branch to the normal
502    // destination.
503    if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
504      BranchInst::Create(II->getNormalDest(), TheCall);
505
506    // If the return instruction returned a value, replace uses of the call with
507    // uses of the returned value.
508    if (!TheCall->use_empty()) {
509      ReturnInst *R = Returns[0];
510      if (TheCall == R->getReturnValue())
511        TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
512      else
513        TheCall->replaceAllUsesWith(R->getReturnValue());
514    }
515    // Since we are now done with the Call/Invoke, we can delete it.
516    TheCall->eraseFromParent();
517
518    // Since we are now done with the return instruction, delete it also.
519    Returns[0]->eraseFromParent();
520
521    // We are now done with the inlining.
522    return true;
523  }
524
525  // Otherwise, we have the normal case, of more than one block to inline or
526  // multiple return sites.
527
528  // We want to clone the entire callee function into the hole between the
529  // "starter" and "ender" blocks.  How we accomplish this depends on whether
530  // this is an invoke instruction or a call instruction.
531  BasicBlock *AfterCallBB;
532  if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
533
534    // Add an unconditional branch to make this look like the CallInst case...
535    BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
536
537    // Split the basic block.  This guarantees that no PHI nodes will have to be
538    // updated due to new incoming edges, and make the invoke case more
539    // symmetric to the call case.
540    AfterCallBB = OrigBB->splitBasicBlock(NewBr,
541                                          CalledFunc->getName()+".exit");
542
543  } else {  // It's a call
544    // If this is a call instruction, we need to split the basic block that
545    // the call lives in.
546    //
547    AfterCallBB = OrigBB->splitBasicBlock(TheCall,
548                                          CalledFunc->getName()+".exit");
549  }
550
551  // Change the branch that used to go to AfterCallBB to branch to the first
552  // basic block of the inlined function.
553  //
554  TerminatorInst *Br = OrigBB->getTerminator();
555  assert(Br && Br->getOpcode() == Instruction::Br &&
556         "splitBasicBlock broken!");
557  Br->setOperand(0, FirstNewBlock);
558
559
560  // Now that the function is correct, make it a little bit nicer.  In
561  // particular, move the basic blocks inserted from the end of the function
562  // into the space made by splitting the source basic block.
563  Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
564                                     FirstNewBlock, Caller->end());
565
566  // Handle all of the return instructions that we just cloned in, and eliminate
567  // any users of the original call/invoke instruction.
568  const Type *RTy = CalledFunc->getReturnType();
569
570  if (Returns.size() > 1) {
571    // The PHI node should go at the front of the new basic block to merge all
572    // possible incoming values.
573    PHINode *PHI = 0;
574    if (!TheCall->use_empty()) {
575      PHI = PHINode::Create(RTy, TheCall->getName(),
576                            AfterCallBB->begin());
577      // Anything that used the result of the function call should now use the
578      // PHI node as their operand.
579      TheCall->replaceAllUsesWith(PHI);
580    }
581
582    // Loop over all of the return instructions adding entries to the PHI node
583    // as appropriate.
584    if (PHI) {
585      for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
586        ReturnInst *RI = Returns[i];
587        assert(RI->getReturnValue()->getType() == PHI->getType() &&
588               "Ret value not consistent in function!");
589        PHI->addIncoming(RI->getReturnValue(), RI->getParent());
590      }
591
592      // Now that we inserted the PHI, check to see if it has a single value
593      // (e.g. all the entries are the same or undef).  If so, remove the PHI so
594      // it doesn't block other optimizations.
595      if (Value *V = PHI->hasConstantValue()) {
596        PHI->replaceAllUsesWith(V);
597        PHI->eraseFromParent();
598      }
599    }
600
601
602    // Add a branch to the merge points and remove return instructions.
603    for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
604      ReturnInst *RI = Returns[i];
605      BranchInst::Create(AfterCallBB, RI);
606      RI->eraseFromParent();
607    }
608  } else if (!Returns.empty()) {
609    // Otherwise, if there is exactly one return value, just replace anything
610    // using the return value of the call with the computed value.
611    if (!TheCall->use_empty()) {
612      if (TheCall == Returns[0]->getReturnValue())
613        TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
614      else
615        TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
616    }
617
618    // Splice the code from the return block into the block that it will return
619    // to, which contains the code that was after the call.
620    BasicBlock *ReturnBB = Returns[0]->getParent();
621    AfterCallBB->getInstList().splice(AfterCallBB->begin(),
622                                      ReturnBB->getInstList());
623
624    // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
625    ReturnBB->replaceAllUsesWith(AfterCallBB);
626
627    // Delete the return instruction now and empty ReturnBB now.
628    Returns[0]->eraseFromParent();
629    ReturnBB->eraseFromParent();
630  } else if (!TheCall->use_empty()) {
631    // No returns, but something is using the return value of the call.  Just
632    // nuke the result.
633    TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
634  }
635
636  // Since we are now done with the Call/Invoke, we can delete it.
637  TheCall->eraseFromParent();
638
639  // We should always be able to fold the entry block of the function into the
640  // single predecessor of the block...
641  assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
642  BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
643
644  // Splice the code entry block into calling block, right before the
645  // unconditional branch.
646  OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
647  CalleeEntry->replaceAllUsesWith(OrigBB);  // Update PHI nodes
648
649  // Remove the unconditional branch.
650  OrigBB->getInstList().erase(Br);
651
652  // Now we can remove the CalleeEntry block, which is now empty.
653  Caller->getBasicBlockList().erase(CalleeEntry);
654
655  return true;
656}
657