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