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