1 //===- InlineFunction.cpp - Code to perform function inlining -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements inlining of a function into a call site, resolving
11 // parameters and the return value as appropriate.
13 // The code in this file for handling inlines through invoke
14 // instructions preserves semantics only under some assumptions about
15 // the behavior of unwinders which correspond to gcc-style libUnwind
16 // exception personality functions. Eventually the IR will be
17 // improved to make this unnecessary, but until then, this code is
18 // marked [LIBUNWIND].
20 //===----------------------------------------------------------------------===//
22 #include "llvm/Transforms/Utils/Cloning.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Module.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/IntrinsicInst.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/Attributes.h"
30 #include "llvm/Analysis/CallGraph.h"
31 #include "llvm/Analysis/DebugInfo.h"
32 #include "llvm/Analysis/InstructionSimplify.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Transforms/Utils/Local.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/Support/CallSite.h"
38 #include "llvm/Support/IRBuilder.h"
41 bool llvm::InlineFunction(CallInst *CI, InlineFunctionInfo &IFI) {
42 return InlineFunction(CallSite(CI), IFI);
44 bool llvm::InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI) {
45 return InlineFunction(CallSite(II), IFI);
49 /// A class for recording information about inlining through an invoke.
50 class InvokeInliningInfo {
51 BasicBlock *UnwindDest;
52 SmallVector<Value*, 8> UnwindDestPHIValues;
55 InvokeInliningInfo(InvokeInst *II) : UnwindDest(II->getUnwindDest()) {
56 // If there are PHI nodes in the unwind destination block, we
57 // need to keep track of which values came into them from the
58 // invoke before removing the edge from this block.
59 llvm::BasicBlock *InvokeBlock = II->getParent();
60 for (BasicBlock::iterator I = UnwindDest->begin(); isa<PHINode>(I); ++I) {
61 PHINode *PN = cast<PHINode>(I);
62 // Save the value to use for this edge.
63 llvm::Value *Incoming = PN->getIncomingValueForBlock(InvokeBlock);
64 UnwindDestPHIValues.push_back(Incoming);
68 BasicBlock *getUnwindDest() const {
72 /// Add incoming-PHI values to the unwind destination block for
73 /// the given basic block, using the values for the original
74 /// invoke's source block.
75 void addIncomingPHIValuesFor(BasicBlock *BB) const {
76 BasicBlock::iterator I = UnwindDest->begin();
77 for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
78 PHINode *PN = cast<PHINode>(I);
79 PN->addIncoming(UnwindDestPHIValues[i], BB);
85 /// [LIBUNWIND] Check whether the given value is the _Unwind_Resume
86 /// function specified by the Itanium EH ABI.
87 static bool isUnwindResume(Value *value) {
88 Function *fn = dyn_cast<Function>(value);
89 if (!fn) return false;
91 // declare void @_Unwind_Resume(i8*)
92 if (fn->getName() != "_Unwind_Resume") return false;
93 const FunctionType *fnType = fn->getFunctionType();
94 if (!fnType->getReturnType()->isVoidTy()) return false;
95 if (fnType->isVarArg()) return false;
96 if (fnType->getNumParams() != 1) return false;
97 const PointerType *paramType = dyn_cast<PointerType>(fnType->getParamType(0));
98 return (paramType && paramType->getElementType()->isIntegerTy(8));
101 /// [LIBUNWIND] Find the (possibly absent) call to @llvm.eh.selector in
102 /// the given landing pad.
103 static EHSelectorInst *findSelectorForLandingPad(BasicBlock *lpad) {
104 for (BasicBlock::iterator i = lpad->begin(), e = lpad->end(); i != e; i++)
105 if (EHSelectorInst *selector = dyn_cast<EHSelectorInst>(i))
110 /// [LIBUNWIND] Check whether this selector is "only cleanups":
111 /// call i32 @llvm.eh.selector(blah, blah, i32 0)
112 static bool isCleanupOnlySelector(EHSelectorInst *selector) {
113 if (selector->getNumArgOperands() != 3) return false;
114 ConstantInt *val = dyn_cast<ConstantInt>(selector->getArgOperand(2));
115 return (val && val->isZero());
118 /// HandleCallsInBlockInlinedThroughInvoke - When we inline a basic block into
119 /// an invoke, we have to turn all of the calls that can throw into
120 /// invokes. This function analyze BB to see if there are any calls, and if so,
121 /// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
122 /// nodes in that block with the values specified in InvokeDestPHIValues.
124 /// Returns true to indicate that the next block should be skipped.
125 static bool HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB,
126 InvokeInliningInfo &Invoke) {
127 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
128 Instruction *I = BBI++;
130 // We only need to check for function calls: inlined invoke
131 // instructions require no special handling.
132 CallInst *CI = dyn_cast<CallInst>(I);
133 if (CI == 0) continue;
135 // LIBUNWIND: merge selector instructions.
136 if (EHSelectorInst *Inner = dyn_cast<EHSelectorInst>(CI)) {
137 EHSelectorInst *Outer = findSelectorForLandingPad(Invoke.getUnwindDest());
138 if (!Outer) continue;
140 bool innerIsOnlyCleanup = isCleanupOnlySelector(Inner);
141 bool outerIsOnlyCleanup = isCleanupOnlySelector(Outer);
143 // If both selectors contain only cleanups, we don't need to do
144 // anything. TODO: this is really just a very specific instance
145 // of a much more general optimization.
146 if (innerIsOnlyCleanup && outerIsOnlyCleanup) continue;
148 // Otherwise, we just append the outer selector to the inner selector.
149 SmallVector<Value*, 16> NewSelector;
150 for (unsigned i = 0, e = Inner->getNumArgOperands(); i != e; ++i)
151 NewSelector.push_back(Inner->getArgOperand(i));
152 for (unsigned i = 2, e = Outer->getNumArgOperands(); i != e; ++i)
153 NewSelector.push_back(Outer->getArgOperand(i));
155 CallInst *NewInner = CallInst::Create(Inner->getCalledValue(),
160 // No need to copy attributes, calling convention, etc.
161 NewInner->takeName(Inner);
162 Inner->replaceAllUsesWith(NewInner);
163 Inner->eraseFromParent();
167 // If this call cannot unwind, don't convert it to an invoke.
168 if (CI->doesNotThrow())
171 // Convert this function call into an invoke instruction.
172 // First, split the basic block.
173 BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
175 bool skipNextBlock = false;
177 // LIBUNWIND: If this is a call to @_Unwind_Resume, just branch
178 // directly to the new landing pad.
179 if (isUnwindResume(CI->getCalledValue())) {
180 BranchInst::Create(Invoke.getUnwindDest(), BB->getTerminator());
182 // TODO: 'Split' is now unreachable; clean it up.
184 // We want to leave the original call intact so that the call
185 // graph and other structures won't get misled. We also have to
186 // avoid processing the next block, or we'll iterate here forever.
187 skipNextBlock = true;
189 // Otherwise, create the new invoke instruction.
191 ImmutableCallSite CS(CI);
192 SmallVector<Value*, 8> InvokeArgs(CS.arg_begin(), CS.arg_end());
194 InvokeInst::Create(CI->getCalledValue(), Split, Invoke.getUnwindDest(),
195 InvokeArgs.begin(), InvokeArgs.end(),
196 CI->getName(), BB->getTerminator());
197 II->setCallingConv(CI->getCallingConv());
198 II->setAttributes(CI->getAttributes());
200 // Make sure that anything using the call now uses the invoke! This also
201 // updates the CallGraph if present, because it uses a WeakVH.
202 CI->replaceAllUsesWith(II);
204 Split->getInstList().pop_front(); // Delete the original call
207 // Delete the unconditional branch inserted by splitBasicBlock
208 BB->getInstList().pop_back();
210 // Update any PHI nodes in the exceptional block to indicate that
211 // there is now a new entry in them.
212 Invoke.addIncomingPHIValuesFor(BB);
214 // This basic block is now complete, the caller will continue scanning the
216 return skipNextBlock;
223 /// HandleInlinedInvoke - If we inlined an invoke site, we need to convert calls
224 /// in the body of the inlined function into invokes and turn unwind
225 /// instructions into branches to the invoke unwind dest.
227 /// II is the invoke instruction being inlined. FirstNewBlock is the first
228 /// block of the inlined code (the last block is the end of the function),
229 /// and InlineCodeInfo is information about the code that got inlined.
230 static void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
231 ClonedCodeInfo &InlinedCodeInfo) {
232 BasicBlock *InvokeDest = II->getUnwindDest();
234 Function *Caller = FirstNewBlock->getParent();
236 // The inlined code is currently at the end of the function, scan from the
237 // start of the inlined code to its end, checking for stuff we need to
238 // rewrite. If the code doesn't have calls or unwinds, we know there is
239 // nothing to rewrite.
240 if (!InlinedCodeInfo.ContainsCalls && !InlinedCodeInfo.ContainsUnwinds) {
241 // Now that everything is happy, we have one final detail. The PHI nodes in
242 // the exception destination block still have entries due to the original
243 // invoke instruction. Eliminate these entries (which might even delete the
245 InvokeDest->removePredecessor(II->getParent());
249 InvokeInliningInfo Invoke(II);
251 for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; ++BB){
252 if (InlinedCodeInfo.ContainsCalls)
253 if (HandleCallsInBlockInlinedThroughInvoke(BB, Invoke)) {
254 // Honor a request to skip the next block. We don't need to
255 // consider UnwindInsts in this case either.
260 if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
261 // An UnwindInst requires special handling when it gets inlined into an
262 // invoke site. Once this happens, we know that the unwind would cause
263 // a control transfer to the invoke exception destination, so we can
264 // transform it into a direct branch to the exception destination.
265 BranchInst::Create(InvokeDest, UI);
267 // Delete the unwind instruction!
268 UI->eraseFromParent();
270 // Update any PHI nodes in the exceptional block to indicate that
271 // there is now a new entry in them.
272 Invoke.addIncomingPHIValuesFor(BB);
276 // Now that everything is happy, we have one final detail. The PHI nodes in
277 // the exception destination block still have entries due to the original
278 // invoke instruction. Eliminate these entries (which might even delete the
280 InvokeDest->removePredecessor(II->getParent());
283 /// UpdateCallGraphAfterInlining - Once we have cloned code over from a callee
284 /// into the caller, update the specified callgraph to reflect the changes we
285 /// made. Note that it's possible that not all code was copied over, so only
286 /// some edges of the callgraph may remain.
287 static void UpdateCallGraphAfterInlining(CallSite CS,
288 Function::iterator FirstNewBlock,
289 ValueToValueMapTy &VMap,
290 InlineFunctionInfo &IFI) {
291 CallGraph &CG = *IFI.CG;
292 const Function *Caller = CS.getInstruction()->getParent()->getParent();
293 const Function *Callee = CS.getCalledFunction();
294 CallGraphNode *CalleeNode = CG[Callee];
295 CallGraphNode *CallerNode = CG[Caller];
297 // Since we inlined some uninlined call sites in the callee into the caller,
298 // add edges from the caller to all of the callees of the callee.
299 CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
301 // Consider the case where CalleeNode == CallerNode.
302 CallGraphNode::CalledFunctionsVector CallCache;
303 if (CalleeNode == CallerNode) {
304 CallCache.assign(I, E);
305 I = CallCache.begin();
309 for (; I != E; ++I) {
310 const Value *OrigCall = I->first;
312 ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
313 // Only copy the edge if the call was inlined!
314 if (VMI == VMap.end() || VMI->second == 0)
317 // If the call was inlined, but then constant folded, there is no edge to
318 // add. Check for this case.
319 Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
320 if (NewCall == 0) continue;
322 // Remember that this call site got inlined for the client of
324 IFI.InlinedCalls.push_back(NewCall);
326 // It's possible that inlining the callsite will cause it to go from an
327 // indirect to a direct call by resolving a function pointer. If this
328 // happens, set the callee of the new call site to a more precise
329 // destination. This can also happen if the call graph node of the caller
330 // was just unnecessarily imprecise.
331 if (I->second->getFunction() == 0)
332 if (Function *F = CallSite(NewCall).getCalledFunction()) {
333 // Indirect call site resolved to direct call.
334 CallerNode->addCalledFunction(CallSite(NewCall), CG[F]);
339 CallerNode->addCalledFunction(CallSite(NewCall), I->second);
342 // Update the call graph by deleting the edge from Callee to Caller. We must
343 // do this after the loop above in case Caller and Callee are the same.
344 CallerNode->removeCallEdgeFor(CS);
347 /// HandleByValArgument - When inlining a call site that has a byval argument,
348 /// we have to make the implicit memcpy explicit by adding it.
349 static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
350 const Function *CalledFunc,
351 InlineFunctionInfo &IFI,
352 unsigned ByValAlignment) {
353 const Type *AggTy = cast<PointerType>(Arg->getType())->getElementType();
355 // If the called function is readonly, then it could not mutate the caller's
356 // copy of the byval'd memory. In this case, it is safe to elide the copy and
358 if (CalledFunc->onlyReadsMemory()) {
359 // If the byval argument has a specified alignment that is greater than the
360 // passed in pointer, then we either have to round up the input pointer or
361 // give up on this transformation.
362 if (ByValAlignment <= 1) // 0 = unspecified, 1 = no particular alignment.
365 // If the pointer is already known to be sufficiently aligned, or if we can
366 // round it up to a larger alignment, then we don't need a temporary.
367 if (getOrEnforceKnownAlignment(Arg, ByValAlignment,
368 IFI.TD) >= ByValAlignment)
371 // Otherwise, we have to make a memcpy to get a safe alignment. This is bad
372 // for code quality, but rarely happens and is required for correctness.
375 LLVMContext &Context = Arg->getContext();
377 const Type *VoidPtrTy = Type::getInt8PtrTy(Context);
379 // Create the alloca. If we have TargetData, use nice alignment.
382 Align = IFI.TD->getPrefTypeAlignment(AggTy);
384 // If the byval had an alignment specified, we *must* use at least that
385 // alignment, as it is required by the byval argument (and uses of the
386 // pointer inside the callee).
387 Align = std::max(Align, ByValAlignment);
389 Function *Caller = TheCall->getParent()->getParent();
391 Value *NewAlloca = new AllocaInst(AggTy, 0, Align, Arg->getName(),
392 &*Caller->begin()->begin());
394 const Type *Tys[3] = {VoidPtrTy, VoidPtrTy, Type::getInt64Ty(Context)};
395 Function *MemCpyFn = Intrinsic::getDeclaration(Caller->getParent(),
398 Value *DestCast = new BitCastInst(NewAlloca, VoidPtrTy, "tmp", TheCall);
399 Value *SrcCast = new BitCastInst(Arg, VoidPtrTy, "tmp", TheCall);
403 Size = ConstantExpr::getSizeOf(AggTy);
405 Size = ConstantInt::get(Type::getInt64Ty(Context),
406 IFI.TD->getTypeStoreSize(AggTy));
408 // Always generate a memcpy of alignment 1 here because we don't know
409 // the alignment of the src pointer. Other optimizations can infer
411 Value *CallArgs[] = {
412 DestCast, SrcCast, Size,
413 ConstantInt::get(Type::getInt32Ty(Context), 1),
414 ConstantInt::getFalse(Context) // isVolatile
416 CallInst *TheMemCpy =
417 CallInst::Create(MemCpyFn, CallArgs, CallArgs+5, "", TheCall);
419 // If we have a call graph, update it.
420 if (CallGraph *CG = IFI.CG) {
421 CallGraphNode *MemCpyCGN = CG->getOrInsertFunction(MemCpyFn);
422 CallGraphNode *CallerNode = (*CG)[Caller];
423 CallerNode->addCalledFunction(TheMemCpy, MemCpyCGN);
426 // Uses of the argument in the function should use our new alloca
431 // isUsedByLifetimeMarker - Check whether this Value is used by a lifetime
433 static bool isUsedByLifetimeMarker(Value *V) {
434 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE;
436 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*UI)) {
437 switch (II->getIntrinsicID()) {
439 case Intrinsic::lifetime_start:
440 case Intrinsic::lifetime_end:
448 // hasLifetimeMarkers - Check whether the given alloca already has
449 // lifetime.start or lifetime.end intrinsics.
450 static bool hasLifetimeMarkers(AllocaInst *AI) {
451 const Type *Int8PtrTy = Type::getInt8PtrTy(AI->getType()->getContext());
452 if (AI->getType() == Int8PtrTy)
453 return isUsedByLifetimeMarker(AI);
455 // Do a scan to find all the bitcasts to i8*.
456 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end(); I != E;
458 if (I->getType() != Int8PtrTy) continue;
459 if (!isa<BitCastInst>(*I)) continue;
460 if (isUsedByLifetimeMarker(*I))
466 // InlineFunction - This function inlines the called function into the basic
467 // block of the caller. This returns false if it is not possible to inline this
468 // call. The program is still in a well defined state if this occurs though.
470 // Note that this only does one level of inlining. For example, if the
471 // instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
472 // exists in the instruction stream. Similarly this will inline a recursive
473 // function by one level.
475 bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI) {
476 Instruction *TheCall = CS.getInstruction();
477 LLVMContext &Context = TheCall->getContext();
478 assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
479 "Instruction not in function!");
481 // If IFI has any state in it, zap it before we fill it in.
484 const Function *CalledFunc = CS.getCalledFunction();
485 if (CalledFunc == 0 || // Can't inline external function or indirect
486 CalledFunc->isDeclaration() || // call, or call to a vararg function!
487 CalledFunc->getFunctionType()->isVarArg()) return false;
489 // If the call to the callee is not a tail call, we must clear the 'tail'
490 // flags on any calls that we inline.
491 bool MustClearTailCallFlags =
492 !(isa<CallInst>(TheCall) && cast<CallInst>(TheCall)->isTailCall());
494 // If the call to the callee cannot throw, set the 'nounwind' flag on any
495 // calls that we inline.
496 bool MarkNoUnwind = CS.doesNotThrow();
498 BasicBlock *OrigBB = TheCall->getParent();
499 Function *Caller = OrigBB->getParent();
501 // GC poses two hazards to inlining, which only occur when the callee has GC:
502 // 1. If the caller has no GC, then the callee's GC must be propagated to the
504 // 2. If the caller has a differing GC, it is invalid to inline.
505 if (CalledFunc->hasGC()) {
506 if (!Caller->hasGC())
507 Caller->setGC(CalledFunc->getGC());
508 else if (CalledFunc->getGC() != Caller->getGC())
512 // Get an iterator to the last basic block in the function, which will have
513 // the new function inlined after it.
515 Function::iterator LastBlock = &Caller->back();
517 // Make sure to capture all of the return instructions from the cloned
519 SmallVector<ReturnInst*, 8> Returns;
520 ClonedCodeInfo InlinedFunctionInfo;
521 Function::iterator FirstNewBlock;
523 { // Scope to destroy VMap after cloning.
524 ValueToValueMapTy VMap;
526 assert(CalledFunc->arg_size() == CS.arg_size() &&
527 "No varargs calls can be inlined!");
529 // Calculate the vector of arguments to pass into the function cloner, which
530 // matches up the formal to the actual argument values.
531 CallSite::arg_iterator AI = CS.arg_begin();
533 for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
534 E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
535 Value *ActualArg = *AI;
537 // When byval arguments actually inlined, we need to make the copy implied
538 // by them explicit. However, we don't do this if the callee is readonly
539 // or readnone, because the copy would be unneeded: the callee doesn't
540 // modify the struct.
541 if (CalledFunc->paramHasAttr(ArgNo+1, Attribute::ByVal)) {
542 ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
543 CalledFunc->getParamAlignment(ArgNo+1));
545 // Calls that we inline may use the new alloca, so we need to clear
546 // their 'tail' flags if HandleByValArgument introduced a new alloca and
547 // the callee has calls.
548 MustClearTailCallFlags |= ActualArg != *AI;
554 // We want the inliner to prune the code as it copies. We would LOVE to
555 // have no dead or constant instructions leftover after inlining occurs
556 // (which can happen, e.g., because an argument was constant), but we'll be
557 // happy with whatever the cloner can do.
558 CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
559 /*ModuleLevelChanges=*/false, Returns, ".i",
560 &InlinedFunctionInfo, IFI.TD, TheCall);
562 // Remember the first block that is newly cloned over.
563 FirstNewBlock = LastBlock; ++FirstNewBlock;
565 // Update the callgraph if requested.
567 UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
570 // If there are any alloca instructions in the block that used to be the entry
571 // block for the callee, move them to the entry block of the caller. First
572 // calculate which instruction they should be inserted before. We insert the
573 // instructions at the end of the current alloca list.
576 BasicBlock::iterator InsertPoint = Caller->begin()->begin();
577 for (BasicBlock::iterator I = FirstNewBlock->begin(),
578 E = FirstNewBlock->end(); I != E; ) {
579 AllocaInst *AI = dyn_cast<AllocaInst>(I++);
580 if (AI == 0) continue;
582 // If the alloca is now dead, remove it. This often occurs due to code
584 if (AI->use_empty()) {
585 AI->eraseFromParent();
589 if (!isa<Constant>(AI->getArraySize()))
592 // Keep track of the static allocas that we inline into the caller.
593 IFI.StaticAllocas.push_back(AI);
595 // Scan for the block of allocas that we can move over, and move them
597 while (isa<AllocaInst>(I) &&
598 isa<Constant>(cast<AllocaInst>(I)->getArraySize())) {
599 IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
603 // Transfer all of the allocas over in a block. Using splice means
604 // that the instructions aren't removed from the symbol table, then
606 Caller->getEntryBlock().getInstList().splice(InsertPoint,
607 FirstNewBlock->getInstList(),
612 // Leave lifetime markers for the static alloca's, scoping them to the
613 // function we just inlined.
614 if (!IFI.StaticAllocas.empty()) {
615 // Also preserve the call graph, if applicable.
616 CallGraphNode *StartCGN = 0, *EndCGN = 0, *CallerNode = 0;
617 if (CallGraph *CG = IFI.CG) {
618 Function *Start = Intrinsic::getDeclaration(Caller->getParent(),
619 Intrinsic::lifetime_start);
620 Function *End = Intrinsic::getDeclaration(Caller->getParent(),
621 Intrinsic::lifetime_end);
622 StartCGN = CG->getOrInsertFunction(Start);
623 EndCGN = CG->getOrInsertFunction(End);
624 CallerNode = (*CG)[Caller];
627 IRBuilder<> builder(FirstNewBlock->begin());
628 for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
629 AllocaInst *AI = IFI.StaticAllocas[ai];
631 // If the alloca is already scoped to something smaller than the whole
632 // function then there's no need to add redundant, less accurate markers.
633 if (hasLifetimeMarkers(AI))
636 CallInst *StartCall = builder.CreateLifetimeStart(AI);
637 if (IFI.CG) CallerNode->addCalledFunction(StartCall, StartCGN);
638 for (unsigned ri = 0, re = Returns.size(); ri != re; ++ri) {
639 IRBuilder<> builder(Returns[ri]);
640 CallInst *EndCall = builder.CreateLifetimeEnd(AI);
641 if (IFI.CG) CallerNode->addCalledFunction(EndCall, EndCGN);
646 // If the inlined code contained dynamic alloca instructions, wrap the inlined
647 // code with llvm.stacksave/llvm.stackrestore intrinsics.
648 if (InlinedFunctionInfo.ContainsDynamicAllocas) {
649 Module *M = Caller->getParent();
650 // Get the two intrinsics we care about.
651 Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
652 Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
654 // If we are preserving the callgraph, add edges to the stacksave/restore
655 // functions for the calls we insert.
656 CallGraphNode *StackSaveCGN = 0, *StackRestoreCGN = 0, *CallerNode = 0;
657 if (CallGraph *CG = IFI.CG) {
658 StackSaveCGN = CG->getOrInsertFunction(StackSave);
659 StackRestoreCGN = CG->getOrInsertFunction(StackRestore);
660 CallerNode = (*CG)[Caller];
663 // Insert the llvm.stacksave.
664 CallInst *SavedPtr = CallInst::Create(StackSave, "savedstack",
665 FirstNewBlock->begin());
666 if (IFI.CG) CallerNode->addCalledFunction(SavedPtr, StackSaveCGN);
668 // Insert a call to llvm.stackrestore before any return instructions in the
670 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
671 CallInst *CI = CallInst::Create(StackRestore, SavedPtr, "", Returns[i]);
672 if (IFI.CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
675 // Count the number of StackRestore calls we insert.
676 unsigned NumStackRestores = Returns.size();
678 // If we are inlining an invoke instruction, insert restores before each
679 // unwind. These unwinds will be rewritten into branches later.
680 if (InlinedFunctionInfo.ContainsUnwinds && isa<InvokeInst>(TheCall)) {
681 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
683 if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
684 CallInst *CI = CallInst::Create(StackRestore, SavedPtr, "", UI);
685 if (IFI.CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
691 // If we are inlining tail call instruction through a call site that isn't
692 // marked 'tail', we must remove the tail marker for any calls in the inlined
693 // code. Also, calls inlined through a 'nounwind' call site should be marked
695 if (InlinedFunctionInfo.ContainsCalls &&
696 (MustClearTailCallFlags || MarkNoUnwind)) {
697 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
699 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
700 if (CallInst *CI = dyn_cast<CallInst>(I)) {
701 if (MustClearTailCallFlags)
702 CI->setTailCall(false);
704 CI->setDoesNotThrow();
708 // If we are inlining through a 'nounwind' call site then any inlined 'unwind'
709 // instructions are unreachable.
710 if (InlinedFunctionInfo.ContainsUnwinds && MarkNoUnwind)
711 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
713 TerminatorInst *Term = BB->getTerminator();
714 if (isa<UnwindInst>(Term)) {
715 new UnreachableInst(Context, Term);
716 BB->getInstList().erase(Term);
720 // If we are inlining for an invoke instruction, we must make sure to rewrite
721 // any inlined 'unwind' instructions into branches to the invoke exception
722 // destination, and call instructions into invoke instructions.
723 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
724 HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
726 // If we cloned in _exactly one_ basic block, and if that block ends in a
727 // return instruction, we splice the body of the inlined callee directly into
728 // the calling basic block.
729 if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
730 // Move all of the instructions right before the call.
731 OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
732 FirstNewBlock->begin(), FirstNewBlock->end());
733 // Remove the cloned basic block.
734 Caller->getBasicBlockList().pop_back();
736 // If the call site was an invoke instruction, add a branch to the normal
738 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
739 BranchInst::Create(II->getNormalDest(), TheCall);
741 // If the return instruction returned a value, replace uses of the call with
742 // uses of the returned value.
743 if (!TheCall->use_empty()) {
744 ReturnInst *R = Returns[0];
745 if (TheCall == R->getReturnValue())
746 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
748 TheCall->replaceAllUsesWith(R->getReturnValue());
750 // Since we are now done with the Call/Invoke, we can delete it.
751 TheCall->eraseFromParent();
753 // Since we are now done with the return instruction, delete it also.
754 Returns[0]->eraseFromParent();
756 // We are now done with the inlining.
760 // Otherwise, we have the normal case, of more than one block to inline or
761 // multiple return sites.
763 // We want to clone the entire callee function into the hole between the
764 // "starter" and "ender" blocks. How we accomplish this depends on whether
765 // this is an invoke instruction or a call instruction.
766 BasicBlock *AfterCallBB;
767 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
769 // Add an unconditional branch to make this look like the CallInst case...
770 BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
772 // Split the basic block. This guarantees that no PHI nodes will have to be
773 // updated due to new incoming edges, and make the invoke case more
774 // symmetric to the call case.
775 AfterCallBB = OrigBB->splitBasicBlock(NewBr,
776 CalledFunc->getName()+".exit");
778 } else { // It's a call
779 // If this is a call instruction, we need to split the basic block that
780 // the call lives in.
782 AfterCallBB = OrigBB->splitBasicBlock(TheCall,
783 CalledFunc->getName()+".exit");
786 // Change the branch that used to go to AfterCallBB to branch to the first
787 // basic block of the inlined function.
789 TerminatorInst *Br = OrigBB->getTerminator();
790 assert(Br && Br->getOpcode() == Instruction::Br &&
791 "splitBasicBlock broken!");
792 Br->setOperand(0, FirstNewBlock);
795 // Now that the function is correct, make it a little bit nicer. In
796 // particular, move the basic blocks inserted from the end of the function
797 // into the space made by splitting the source basic block.
798 Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
799 FirstNewBlock, Caller->end());
801 // Handle all of the return instructions that we just cloned in, and eliminate
802 // any users of the original call/invoke instruction.
803 const Type *RTy = CalledFunc->getReturnType();
806 if (Returns.size() > 1) {
807 // The PHI node should go at the front of the new basic block to merge all
808 // possible incoming values.
809 if (!TheCall->use_empty()) {
810 PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
811 AfterCallBB->begin());
812 // Anything that used the result of the function call should now use the
813 // PHI node as their operand.
814 TheCall->replaceAllUsesWith(PHI);
817 // Loop over all of the return instructions adding entries to the PHI node
820 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
821 ReturnInst *RI = Returns[i];
822 assert(RI->getReturnValue()->getType() == PHI->getType() &&
823 "Ret value not consistent in function!");
824 PHI->addIncoming(RI->getReturnValue(), RI->getParent());
829 // Add a branch to the merge points and remove return instructions.
830 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
831 ReturnInst *RI = Returns[i];
832 BranchInst::Create(AfterCallBB, RI);
833 RI->eraseFromParent();
835 } else if (!Returns.empty()) {
836 // Otherwise, if there is exactly one return value, just replace anything
837 // using the return value of the call with the computed value.
838 if (!TheCall->use_empty()) {
839 if (TheCall == Returns[0]->getReturnValue())
840 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
842 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
845 // Splice the code from the return block into the block that it will return
846 // to, which contains the code that was after the call.
847 BasicBlock *ReturnBB = Returns[0]->getParent();
848 AfterCallBB->getInstList().splice(AfterCallBB->begin(),
849 ReturnBB->getInstList());
851 // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
852 ReturnBB->replaceAllUsesWith(AfterCallBB);
854 // Delete the return instruction now and empty ReturnBB now.
855 Returns[0]->eraseFromParent();
856 ReturnBB->eraseFromParent();
857 } else if (!TheCall->use_empty()) {
858 // No returns, but something is using the return value of the call. Just
860 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
863 // Since we are now done with the Call/Invoke, we can delete it.
864 TheCall->eraseFromParent();
866 // We should always be able to fold the entry block of the function into the
867 // single predecessor of the block...
868 assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
869 BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
871 // Splice the code entry block into calling block, right before the
872 // unconditional branch.
873 OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
874 CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
876 // Remove the unconditional branch.
877 OrigBB->getInstList().erase(Br);
879 // Now we can remove the CalleeEntry block, which is now empty.
880 Caller->getBasicBlockList().erase(CalleeEntry);
882 // If we inserted a phi node, check to see if it has a single value (e.g. all
883 // the entries are the same or undef). If so, remove the PHI so it doesn't
884 // block other optimizations.
886 if (Value *V = SimplifyInstruction(PHI, IFI.TD)) {
887 PHI->replaceAllUsesWith(V);
888 PHI->eraseFromParent();