blob: c43af27c9d1bdb31fef555f4bd00a1f23854c49c [file] [log] [blame]
Chris Lattnerca398dc2003-05-29 15:11:31 +00001//===- InlineFunction.cpp - Code to perform function inlining -------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerca398dc2003-05-29 15:11:31 +00009//
10// This file implements inlining of a function into a call site, resolving
11// parameters and the return value as appropriate.
12//
Chris Lattnerca398dc2003-05-29 15:11:31 +000013//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/Cloning.h"
Chris Lattner3787e762004-10-17 23:21:07 +000016#include "llvm/Constants.h"
Chris Lattner7152c232003-08-24 04:06:56 +000017#include "llvm/DerivedTypes.h"
Chris Lattnerca398dc2003-05-29 15:11:31 +000018#include "llvm/Module.h"
Chris Lattner80a38d22003-08-24 06:59:16 +000019#include "llvm/Instructions.h"
Devang Patel517576d2009-04-15 00:17:06 +000020#include "llvm/IntrinsicInst.h"
Chris Lattner80a38d22003-08-24 06:59:16 +000021#include "llvm/Intrinsics.h"
Devang Pateleaf42ab2008-09-23 23:03:40 +000022#include "llvm/Attributes.h"
Chris Lattner468fb1d2006-01-14 20:07:50 +000023#include "llvm/Analysis/CallGraph.h"
Devang Patel517576d2009-04-15 00:17:06 +000024#include "llvm/Analysis/DebugInfo.h"
Chris Lattnerc93adca2008-01-11 06:09:30 +000025#include "llvm/Target/TargetData.h"
Chris Lattner93e985f2007-02-13 02:10:56 +000026#include "llvm/ADT/SmallVector.h"
Devang Patel641ca932008-03-10 18:22:16 +000027#include "llvm/ADT/StringExtras.h"
Chris Lattner80a38d22003-08-24 06:59:16 +000028#include "llvm/Support/CallSite.h"
Chris Lattnerf7703df2004-01-09 06:12:26 +000029using namespace llvm;
Chris Lattnerca398dc2003-05-29 15:11:31 +000030
Chris Lattner8f2718f2009-08-27 04:20:52 +000031bool llvm::InlineFunction(CallInst *CI, CallGraph *CG, const TargetData *TD,
32 SmallVectorImpl<AllocaInst*> *StaticAllocas) {
33 return InlineFunction(CallSite(CI), CG, TD, StaticAllocas);
Chris Lattner468fb1d2006-01-14 20:07:50 +000034}
Chris Lattner8f2718f2009-08-27 04:20:52 +000035bool llvm::InlineFunction(InvokeInst *II, CallGraph *CG, const TargetData *TD,
36 SmallVectorImpl<AllocaInst*> *StaticAllocas) {
37 return InlineFunction(CallSite(II), CG, TD, StaticAllocas);
Chris Lattner468fb1d2006-01-14 20:07:50 +000038}
Chris Lattner80a38d22003-08-24 06:59:16 +000039
Chris Lattner135755d2009-08-27 03:51:50 +000040
41/// HandleCallsInBlockInlinedThroughInvoke - When we inline a basic block into
Eric Christopherf61f89a2009-09-06 22:20:54 +000042/// an invoke, we have to turn all of the calls that can throw into
Chris Lattner135755d2009-08-27 03:51:50 +000043/// invokes. This function analyze BB to see if there are any calls, and if so,
44/// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
Chris Lattner81dfb382009-09-01 18:44:06 +000045/// nodes in that block with the values specified in InvokeDestPHIValues.
Chris Lattner135755d2009-08-27 03:51:50 +000046///
47static void HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB,
48 BasicBlock *InvokeDest,
Chris Lattner81dfb382009-09-01 18:44:06 +000049 const SmallVectorImpl<Value*> &InvokeDestPHIValues) {
Chris Lattner135755d2009-08-27 03:51:50 +000050 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
51 Instruction *I = BBI++;
52
53 // We only need to check for function calls: inlined invoke
54 // instructions require no special handling.
55 CallInst *CI = dyn_cast<CallInst>(I);
56 if (CI == 0) continue;
57
58 // If this call cannot unwind, don't convert it to an invoke.
59 if (CI->doesNotThrow())
60 continue;
61
62 // Convert this function call into an invoke instruction.
63 // First, split the basic block.
64 BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
65
66 // Next, create the new invoke instruction, inserting it at the end
67 // of the old basic block.
Eric Christopher551754c2010-04-16 23:37:20 +000068 SmallVector<Value*, 8> InvokeArgs(CI->op_begin()+1, CI->op_end());
Chris Lattner135755d2009-08-27 03:51:50 +000069 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
Chris Lattner81dfb382009-09-01 18:44:06 +000076 // Make sure that anything using the call now uses the invoke! This also
77 // updates the CallGraph if present.
Chris Lattner135755d2009-08-27 03:51:50 +000078 CI->replaceAllUsesWith(II);
79
Chris Lattner135755d2009-08-27 03:51:50 +000080 // 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
Chris Lattnercd4d3392006-01-13 19:05:59 +000098/// 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///
Nick Lewyckydac5c4b2009-02-03 04:34:40 +0000102/// II is the invoke instruction being inlined. FirstNewBlock is the first
Chris Lattnercd4d3392006-01-13 19:05:59 +0000103/// block of the inlined code (the last block is the end of the function),
104/// and InlineCodeInfo is information about the code that got inlined.
105static void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
Chris Lattner81dfb382009-09-01 18:44:06 +0000106 ClonedCodeInfo &InlinedCodeInfo) {
Chris Lattnercd4d3392006-01-13 19:05:59 +0000107 BasicBlock *InvokeDest = II->getUnwindDest();
Chris Lattner135755d2009-08-27 03:51:50 +0000108 SmallVector<Value*, 8> InvokeDestPHIValues;
Chris Lattnercd4d3392006-01-13 19:05:59 +0000109
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();
Duncan Sandsa7212e52008-09-05 12:37:12 +0000121
Chris Lattnercd4d3392006-01-13 19:05:59 +0000122 // 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
Chris Lattner135755d2009-08-27 03:51:50 +0000124 // 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
Chris Lattner135755d2009-08-27 03:51:50 +0000135 for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; ++BB){
136 if (InlinedCodeInfo.ContainsCalls)
137 HandleCallsInBlockInlinedThroughInvoke(BB, InvokeDest,
Chris Lattner81dfb382009-09-01 18:44:06 +0000138 InvokeDestPHIValues);
Duncan Sandsa7212e52008-09-05 12:37:12 +0000139
Chris Lattner135755d2009-08-27 03:51:50 +0000140 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);
Chris Lattnercd4d3392006-01-13 19:05:59 +0000146
Chris Lattner135755d2009-08-27 03:51:50 +0000147 // Delete the unwind instruction!
148 UI->eraseFromParent();
Duncan Sandsa3355ff2007-12-03 20:06:50 +0000149
Chris Lattner135755d2009-08-27 03:51:50 +0000150 // 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);
Chris Lattnercd4d3392006-01-13 19:05:59 +0000157 }
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
Chris Lattnerd85340f2006-07-12 18:29:36 +0000168/// 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
Duncan Sandsd7b98512008-09-08 11:05:51 +0000171/// some edges of the callgraph may remain.
172static void UpdateCallGraphAfterInlining(CallSite CS,
Chris Lattnerd85340f2006-07-12 18:29:36 +0000173 Function::iterator FirstNewBlock,
Chris Lattner5e665f52007-02-03 00:08:31 +0000174 DenseMap<const Value*, Value*> &ValueMap,
Chris Lattner468fb1d2006-01-14 20:07:50 +0000175 CallGraph &CG) {
Duncan Sandsd7b98512008-09-08 11:05:51 +0000176 const Function *Caller = CS.getInstruction()->getParent()->getParent();
177 const Function *Callee = CS.getCalledFunction();
Chris Lattner468fb1d2006-01-14 20:07:50 +0000178 CallGraphNode *CalleeNode = CG[Callee];
179 CallGraphNode *CallerNode = CG[Caller];
Duncan Sandsa7212e52008-09-05 12:37:12 +0000180
Chris Lattnerd85340f2006-07-12 18:29:36 +0000181 // Since we inlined some uninlined call sites in the callee into the caller,
Chris Lattner468fb1d2006-01-14 20:07:50 +0000182 // add edges from the caller to all of the callees of the callee.
Gabor Greifc478e522009-01-15 18:40:09 +0000183 CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
184
185 // Consider the case where CalleeNode == CallerNode.
Gabor Greif12532982009-01-17 00:09:08 +0000186 CallGraphNode::CalledFunctionsVector CallCache;
Gabor Greifc478e522009-01-15 18:40:09 +0000187 if (CalleeNode == CallerNode) {
188 CallCache.assign(I, E);
189 I = CallCache.begin();
190 E = CallCache.end();
191 }
192
193 for (; I != E; ++I) {
Chris Lattnera541b0f2009-09-01 06:31:31 +0000194 const Value *OrigCall = I->first;
Duncan Sandsa7212e52008-09-05 12:37:12 +0000195
Chris Lattner5e665f52007-02-03 00:08:31 +0000196 DenseMap<const Value*, Value*>::iterator VMI = ValueMap.find(OrigCall);
Chris Lattner981418b2006-07-12 21:37:11 +0000197 // Only copy the edge if the call was inlined!
Chris Lattner135755d2009-08-27 03:51:50 +0000198 if (VMI == ValueMap.end() || VMI->second == 0)
199 continue;
200
201 // If the call was inlined, but then constant folded, there is no edge to
202 // add. Check for this case.
203 if (Instruction *NewCall = dyn_cast<Instruction>(VMI->second))
204 CallerNode->addCalledFunction(CallSite::get(NewCall), I->second);
Chris Lattnerd85340f2006-07-12 18:29:36 +0000205 }
Chris Lattner135755d2009-08-27 03:51:50 +0000206
Dale Johannesen39fa3242009-01-13 22:43:37 +0000207 // Update the call graph by deleting the edge from Callee to Caller. We must
208 // do this after the loop above in case Caller and Callee are the same.
209 CallerNode->removeCallEdgeFor(CS);
Chris Lattner468fb1d2006-01-14 20:07:50 +0000210}
211
Chris Lattnerca398dc2003-05-29 15:11:31 +0000212// InlineFunction - This function inlines the called function into the basic
213// block of the caller. This returns false if it is not possible to inline this
214// call. The program is still in a well defined state if this occurs though.
215//
Misha Brukmanfd939082005-04-21 23:48:37 +0000216// Note that this only does one level of inlining. For example, if the
217// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
Chris Lattnerca398dc2003-05-29 15:11:31 +0000218// exists in the instruction stream. Similiarly this will inline a recursive
219// function by one level.
220//
Chris Lattner8f2718f2009-08-27 04:20:52 +0000221bool llvm::InlineFunction(CallSite CS, CallGraph *CG, const TargetData *TD,
222 SmallVectorImpl<AllocaInst*> *StaticAllocas) {
Chris Lattner80a38d22003-08-24 06:59:16 +0000223 Instruction *TheCall = CS.getInstruction();
Owen Andersone922c022009-07-22 00:24:57 +0000224 LLVMContext &Context = TheCall->getContext();
Chris Lattner80a38d22003-08-24 06:59:16 +0000225 assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
226 "Instruction not in function!");
Chris Lattnerca398dc2003-05-29 15:11:31 +0000227
Chris Lattner80a38d22003-08-24 06:59:16 +0000228 const Function *CalledFunc = CS.getCalledFunction();
Chris Lattnerca398dc2003-05-29 15:11:31 +0000229 if (CalledFunc == 0 || // Can't inline external function or indirect
Reid Spencer5cbf9852007-01-30 20:08:39 +0000230 CalledFunc->isDeclaration() || // call, or call to a vararg function!
Eric Christopher0623e902010-03-24 23:35:21 +0000231 CalledFunc->getFunctionType()->isVarArg()) return false;
Chris Lattnerca398dc2003-05-29 15:11:31 +0000232
Chris Lattner1b491412005-05-06 06:47:52 +0000233
Chris Lattneraf9985c2009-02-12 07:06:42 +0000234 // If the call to the callee is not a tail call, we must clear the 'tail'
Chris Lattner1b491412005-05-06 06:47:52 +0000235 // flags on any calls that we inline.
236 bool MustClearTailCallFlags =
Chris Lattneraf9985c2009-02-12 07:06:42 +0000237 !(isa<CallInst>(TheCall) && cast<CallInst>(TheCall)->isTailCall());
Chris Lattner1b491412005-05-06 06:47:52 +0000238
Duncan Sandsf0c33542007-12-19 21:13:37 +0000239 // If the call to the callee cannot throw, set the 'nounwind' flag on any
240 // calls that we inline.
241 bool MarkNoUnwind = CS.doesNotThrow();
242
Chris Lattner80a38d22003-08-24 06:59:16 +0000243 BasicBlock *OrigBB = TheCall->getParent();
Chris Lattnerca398dc2003-05-29 15:11:31 +0000244 Function *Caller = OrigBB->getParent();
245
Gordon Henriksen0e138212007-12-25 03:10:07 +0000246 // GC poses two hazards to inlining, which only occur when the callee has GC:
247 // 1. If the caller has no GC, then the callee's GC must be propagated to the
248 // caller.
249 // 2. If the caller has a differing GC, it is invalid to inline.
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000250 if (CalledFunc->hasGC()) {
251 if (!Caller->hasGC())
252 Caller->setGC(CalledFunc->getGC());
253 else if (CalledFunc->getGC() != Caller->getGC())
Gordon Henriksen0e138212007-12-25 03:10:07 +0000254 return false;
255 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000256
Chris Lattner5052c912004-02-04 01:41:09 +0000257 // Get an iterator to the last basic block in the function, which will have
258 // the new function inlined after it.
259 //
260 Function::iterator LastBlock = &Caller->back();
261
Chris Lattner5e923de2004-02-04 02:51:48 +0000262 // Make sure to capture all of the return instructions from the cloned
Chris Lattnerca398dc2003-05-29 15:11:31 +0000263 // function.
Chris Lattnerec1bea02009-08-27 04:02:30 +0000264 SmallVector<ReturnInst*, 8> Returns;
Chris Lattnercd4d3392006-01-13 19:05:59 +0000265 ClonedCodeInfo InlinedFunctionInfo;
Dale Johannesen0744f092009-03-04 02:09:48 +0000266 Function::iterator FirstNewBlock;
Duncan Sandsf0c33542007-12-19 21:13:37 +0000267
Chris Lattner5e923de2004-02-04 02:51:48 +0000268 { // Scope to destroy ValueMap after cloning.
Chris Lattner5e665f52007-02-03 00:08:31 +0000269 DenseMap<const Value*, Value*> ValueMap;
Chris Lattner5b5bc302006-05-27 01:28:04 +0000270
Dan Gohman9614fcc2008-06-20 17:11:32 +0000271 assert(CalledFunc->arg_size() == CS.arg_size() &&
Chris Lattner5e923de2004-02-04 02:51:48 +0000272 "No varargs calls can be inlined!");
Duncan Sandsa7212e52008-09-05 12:37:12 +0000273
Chris Lattnerc93adca2008-01-11 06:09:30 +0000274 // Calculate the vector of arguments to pass into the function cloner, which
275 // matches up the formal to the actual argument values.
Chris Lattner5e923de2004-02-04 02:51:48 +0000276 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattnerc93adca2008-01-11 06:09:30 +0000277 unsigned ArgNo = 0;
Chris Lattnere4d5c442005-03-15 04:54:21 +0000278 for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
Chris Lattnerc93adca2008-01-11 06:09:30 +0000279 E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
280 Value *ActualArg = *AI;
Duncan Sandsa7212e52008-09-05 12:37:12 +0000281
Duncan Sandsd82375c2008-01-27 18:12:58 +0000282 // When byval arguments actually inlined, we need to make the copy implied
283 // by them explicit. However, we don't do this if the callee is readonly
284 // or readnone, because the copy would be unneeded: the callee doesn't
285 // modify the struct.
Devang Patel05988662008-09-25 21:00:45 +0000286 if (CalledFunc->paramHasAttr(ArgNo+1, Attribute::ByVal) &&
Duncan Sandsd82375c2008-01-27 18:12:58 +0000287 !CalledFunc->onlyReadsMemory()) {
Chris Lattnerc93adca2008-01-11 06:09:30 +0000288 const Type *AggTy = cast<PointerType>(I->getType())->getElementType();
Owen Anderson1d0be152009-08-13 21:58:54 +0000289 const Type *VoidPtrTy =
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000290 Type::getInt8PtrTy(Context);
Duncan Sandsa7212e52008-09-05 12:37:12 +0000291
Chris Lattnerc93adca2008-01-11 06:09:30 +0000292 // Create the alloca. If we have TargetData, use nice alignment.
293 unsigned Align = 1;
294 if (TD) Align = TD->getPrefTypeAlignment(AggTy);
Owen Anderson50dead02009-07-15 23:53:25 +0000295 Value *NewAlloca = new AllocaInst(AggTy, 0, Align,
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000296 I->getName(),
297 &*Caller->begin()->begin());
Chris Lattnerc93adca2008-01-11 06:09:30 +0000298 // Emit a memcpy.
Mon P Wang20adc9d2010-04-04 03:10:48 +0000299 const Type *Tys[3] = {VoidPtrTy, VoidPtrTy, Type::getInt64Ty(Context)};
Chris Lattnerc93adca2008-01-11 06:09:30 +0000300 Function *MemCpyFn = Intrinsic::getDeclaration(Caller->getParent(),
Chris Lattner824b9582008-11-21 16:42:48 +0000301 Intrinsic::memcpy,
Mon P Wang20adc9d2010-04-04 03:10:48 +0000302 Tys, 3);
Chris Lattnerc93adca2008-01-11 06:09:30 +0000303 Value *DestCast = new BitCastInst(NewAlloca, VoidPtrTy, "tmp", TheCall);
304 Value *SrcCast = new BitCastInst(*AI, VoidPtrTy, "tmp", TheCall);
Duncan Sandsa7212e52008-09-05 12:37:12 +0000305
Chris Lattnerc93adca2008-01-11 06:09:30 +0000306 Value *Size;
307 if (TD == 0)
Owen Andersonbaf3c402009-07-29 18:55:55 +0000308 Size = ConstantExpr::getSizeOf(AggTy);
Chris Lattnerc93adca2008-01-11 06:09:30 +0000309 else
Owen Anderson1d0be152009-08-13 21:58:54 +0000310 Size = ConstantInt::get(Type::getInt64Ty(Context),
Mon P Wang20adc9d2010-04-04 03:10:48 +0000311 TD->getTypeStoreSize(AggTy));
Duncan Sandsa7212e52008-09-05 12:37:12 +0000312
Chris Lattnerc93adca2008-01-11 06:09:30 +0000313 // Always generate a memcpy of alignment 1 here because we don't know
314 // the alignment of the src pointer. Other optimizations can infer
315 // better alignment.
316 Value *CallArgs[] = {
Owen Anderson1d0be152009-08-13 21:58:54 +0000317 DestCast, SrcCast, Size,
Mon P Wang20adc9d2010-04-04 03:10:48 +0000318 ConstantInt::get(Type::getInt32Ty(Context), 1),
319 ConstantInt::get(Type::getInt1Ty(Context), 0)
Chris Lattnerc93adca2008-01-11 06:09:30 +0000320 };
321 CallInst *TheMemCpy =
Mon P Wang20adc9d2010-04-04 03:10:48 +0000322 CallInst::Create(MemCpyFn, CallArgs, CallArgs+5, "", TheCall);
Duncan Sandsa7212e52008-09-05 12:37:12 +0000323
Chris Lattnerc93adca2008-01-11 06:09:30 +0000324 // If we have a call graph, update it.
325 if (CG) {
326 CallGraphNode *MemCpyCGN = CG->getOrInsertFunction(MemCpyFn);
327 CallGraphNode *CallerNode = (*CG)[Caller];
328 CallerNode->addCalledFunction(TheMemCpy, MemCpyCGN);
329 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000330
Chris Lattnerc93adca2008-01-11 06:09:30 +0000331 // Uses of the argument in the function should use our new alloca
332 // instead.
333 ActualArg = NewAlloca;
334 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000335
Chris Lattnerc93adca2008-01-11 06:09:30 +0000336 ValueMap[I] = ActualArg;
337 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000338
Chris Lattner5b5bc302006-05-27 01:28:04 +0000339 // We want the inliner to prune the code as it copies. We would LOVE to
340 // have no dead or constant instructions leftover after inlining occurs
341 // (which can happen, e.g., because an argument was constant), but we'll be
342 // happy with whatever the cloner can do.
343 CloneAndPruneFunctionInto(Caller, CalledFunc, ValueMap, Returns, ".i",
Devang Patel53bb5c92009-11-10 23:06:00 +0000344 &InlinedFunctionInfo, TD, TheCall);
Duncan Sandsa7212e52008-09-05 12:37:12 +0000345
Chris Lattnerd85340f2006-07-12 18:29:36 +0000346 // Remember the first block that is newly cloned over.
347 FirstNewBlock = LastBlock; ++FirstNewBlock;
Duncan Sandsa7212e52008-09-05 12:37:12 +0000348
Chris Lattnerd85340f2006-07-12 18:29:36 +0000349 // Update the callgraph if requested.
350 if (CG)
Duncan Sandsd7b98512008-09-08 11:05:51 +0000351 UpdateCallGraphAfterInlining(CS, FirstNewBlock, ValueMap, *CG);
Misha Brukmanfd939082005-04-21 23:48:37 +0000352 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000353
Chris Lattnerca398dc2003-05-29 15:11:31 +0000354 // If there are any alloca instructions in the block that used to be the entry
355 // block for the callee, move them to the entry block of the caller. First
356 // calculate which instruction they should be inserted before. We insert the
357 // instructions at the end of the current alloca list.
358 //
Chris Lattner21f20552006-01-13 18:16:48 +0000359 {
Chris Lattner80a38d22003-08-24 06:59:16 +0000360 BasicBlock::iterator InsertPoint = Caller->begin()->begin();
Chris Lattner5e923de2004-02-04 02:51:48 +0000361 for (BasicBlock::iterator I = FirstNewBlock->begin(),
Chris Lattner135755d2009-08-27 03:51:50 +0000362 E = FirstNewBlock->end(); I != E; ) {
363 AllocaInst *AI = dyn_cast<AllocaInst>(I++);
364 if (AI == 0) continue;
365
366 // If the alloca is now dead, remove it. This often occurs due to code
367 // specialization.
368 if (AI->use_empty()) {
369 AI->eraseFromParent();
370 continue;
Chris Lattner33bb3c82006-09-13 19:23:57 +0000371 }
Chris Lattner135755d2009-08-27 03:51:50 +0000372
373 if (!isa<Constant>(AI->getArraySize()))
374 continue;
375
Chris Lattner8f2718f2009-08-27 04:20:52 +0000376 // Keep track of the static allocas that we inline into the caller if the
377 // StaticAllocas pointer is non-null.
378 if (StaticAllocas) StaticAllocas->push_back(AI);
379
Chris Lattner135755d2009-08-27 03:51:50 +0000380 // Scan for the block of allocas that we can move over, and move them
381 // all at once.
382 while (isa<AllocaInst>(I) &&
Chris Lattner8f2718f2009-08-27 04:20:52 +0000383 isa<Constant>(cast<AllocaInst>(I)->getArraySize())) {
384 if (StaticAllocas) StaticAllocas->push_back(cast<AllocaInst>(I));
Chris Lattner135755d2009-08-27 03:51:50 +0000385 ++I;
Chris Lattner8f2718f2009-08-27 04:20:52 +0000386 }
Chris Lattner135755d2009-08-27 03:51:50 +0000387
388 // Transfer all of the allocas over in a block. Using splice means
389 // that the instructions aren't removed from the symbol table, then
390 // reinserted.
391 Caller->getEntryBlock().getInstList().splice(InsertPoint,
392 FirstNewBlock->getInstList(),
393 AI, I);
394 }
Chris Lattner80a38d22003-08-24 06:59:16 +0000395 }
Chris Lattnerca398dc2003-05-29 15:11:31 +0000396
Chris Lattnerbf229f42006-01-13 19:34:14 +0000397 // If the inlined code contained dynamic alloca instructions, wrap the inlined
398 // code with llvm.stacksave/llvm.stackrestore intrinsics.
399 if (InlinedFunctionInfo.ContainsDynamicAllocas) {
400 Module *M = Caller->getParent();
Chris Lattnerbf229f42006-01-13 19:34:14 +0000401 // Get the two intrinsics we care about.
Chris Lattner6128df52009-10-17 05:39:39 +0000402 Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
403 Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
Chris Lattnerd85340f2006-07-12 18:29:36 +0000404
405 // If we are preserving the callgraph, add edges to the stacksave/restore
406 // functions for the calls we insert.
Chris Lattner21ba23d2006-07-18 21:48:57 +0000407 CallGraphNode *StackSaveCGN = 0, *StackRestoreCGN = 0, *CallerNode = 0;
Chris Lattnerd85340f2006-07-12 18:29:36 +0000408 if (CG) {
Chris Lattner6128df52009-10-17 05:39:39 +0000409 StackSaveCGN = CG->getOrInsertFunction(StackSave);
410 StackRestoreCGN = CG->getOrInsertFunction(StackRestore);
Chris Lattnerd85340f2006-07-12 18:29:36 +0000411 CallerNode = (*CG)[Caller];
412 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000413
Chris Lattnerbf229f42006-01-13 19:34:14 +0000414 // Insert the llvm.stacksave.
Duncan Sandsa7212e52008-09-05 12:37:12 +0000415 CallInst *SavedPtr = CallInst::Create(StackSave, "savedstack",
Gabor Greif051a9502008-04-06 20:25:17 +0000416 FirstNewBlock->begin());
Chris Lattnerd85340f2006-07-12 18:29:36 +0000417 if (CG) CallerNode->addCalledFunction(SavedPtr, StackSaveCGN);
Duncan Sandsa7212e52008-09-05 12:37:12 +0000418
Chris Lattnerbf229f42006-01-13 19:34:14 +0000419 // Insert a call to llvm.stackrestore before any return instructions in the
420 // inlined function.
Chris Lattnerd85340f2006-07-12 18:29:36 +0000421 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
Gabor Greif051a9502008-04-06 20:25:17 +0000422 CallInst *CI = CallInst::Create(StackRestore, SavedPtr, "", Returns[i]);
Chris Lattnerd85340f2006-07-12 18:29:36 +0000423 if (CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
424 }
Chris Lattner468fb1d2006-01-14 20:07:50 +0000425
426 // Count the number of StackRestore calls we insert.
427 unsigned NumStackRestores = Returns.size();
Duncan Sandsa7212e52008-09-05 12:37:12 +0000428
Chris Lattnerbf229f42006-01-13 19:34:14 +0000429 // If we are inlining an invoke instruction, insert restores before each
430 // unwind. These unwinds will be rewritten into branches later.
431 if (InlinedFunctionInfo.ContainsUnwinds && isa<InvokeInst>(TheCall)) {
432 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
433 BB != E; ++BB)
Chris Lattner468fb1d2006-01-14 20:07:50 +0000434 if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
Chris Lattner6128df52009-10-17 05:39:39 +0000435 CallInst *CI = CallInst::Create(StackRestore, SavedPtr, "", UI);
436 if (CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
Chris Lattner468fb1d2006-01-14 20:07:50 +0000437 ++NumStackRestores;
438 }
439 }
Chris Lattnerbf229f42006-01-13 19:34:14 +0000440 }
441
Duncan Sandsa7212e52008-09-05 12:37:12 +0000442 // If we are inlining tail call instruction through a call site that isn't
Chris Lattner1fdf4a82006-01-13 19:18:11 +0000443 // marked 'tail', we must remove the tail marker for any calls in the inlined
Duncan Sandsf0c33542007-12-19 21:13:37 +0000444 // code. Also, calls inlined through a 'nounwind' call site should be marked
445 // 'nounwind'.
446 if (InlinedFunctionInfo.ContainsCalls &&
447 (MustClearTailCallFlags || MarkNoUnwind)) {
Chris Lattner1b491412005-05-06 06:47:52 +0000448 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
449 BB != E; ++BB)
450 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Duncan Sandsf0c33542007-12-19 21:13:37 +0000451 if (CallInst *CI = dyn_cast<CallInst>(I)) {
452 if (MustClearTailCallFlags)
453 CI->setTailCall(false);
454 if (MarkNoUnwind)
455 CI->setDoesNotThrow();
456 }
Chris Lattner1b491412005-05-06 06:47:52 +0000457 }
458
Duncan Sandsf0c33542007-12-19 21:13:37 +0000459 // If we are inlining through a 'nounwind' call site then any inlined 'unwind'
460 // instructions are unreachable.
461 if (InlinedFunctionInfo.ContainsUnwinds && MarkNoUnwind)
462 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
463 BB != E; ++BB) {
464 TerminatorInst *Term = BB->getTerminator();
465 if (isa<UnwindInst>(Term)) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000466 new UnreachableInst(Context, Term);
Duncan Sandsf0c33542007-12-19 21:13:37 +0000467 BB->getInstList().erase(Term);
468 }
469 }
470
Chris Lattner5e923de2004-02-04 02:51:48 +0000471 // If we are inlining for an invoke instruction, we must make sure to rewrite
472 // any inlined 'unwind' instructions into branches to the invoke exception
473 // destination, and call instructions into invoke instructions.
Chris Lattnercd4d3392006-01-13 19:05:59 +0000474 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
Chris Lattner81dfb382009-09-01 18:44:06 +0000475 HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
Chris Lattner5e923de2004-02-04 02:51:48 +0000476
Chris Lattner44a68072004-02-04 04:17:06 +0000477 // If we cloned in _exactly one_ basic block, and if that block ends in a
478 // return instruction, we splice the body of the inlined callee directly into
479 // the calling basic block.
480 if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
481 // Move all of the instructions right before the call.
482 OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
483 FirstNewBlock->begin(), FirstNewBlock->end());
484 // Remove the cloned basic block.
485 Caller->getBasicBlockList().pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +0000486
Chris Lattner44a68072004-02-04 04:17:06 +0000487 // If the call site was an invoke instruction, add a branch to the normal
488 // destination.
489 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
Gabor Greif051a9502008-04-06 20:25:17 +0000490 BranchInst::Create(II->getNormalDest(), TheCall);
Chris Lattner44a68072004-02-04 04:17:06 +0000491
492 // If the return instruction returned a value, replace uses of the call with
493 // uses of the returned value.
Devang Pateldc00d422008-03-04 21:15:15 +0000494 if (!TheCall->use_empty()) {
495 ReturnInst *R = Returns[0];
Eli Friedman5877ad72009-05-08 00:22:04 +0000496 if (TheCall == R->getReturnValue())
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000497 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Eli Friedman5877ad72009-05-08 00:22:04 +0000498 else
499 TheCall->replaceAllUsesWith(R->getReturnValue());
Devang Pateldc00d422008-03-04 21:15:15 +0000500 }
Chris Lattner44a68072004-02-04 04:17:06 +0000501 // Since we are now done with the Call/Invoke, we can delete it.
Dan Gohman1adec832008-06-21 22:08:46 +0000502 TheCall->eraseFromParent();
Chris Lattner44a68072004-02-04 04:17:06 +0000503
504 // Since we are now done with the return instruction, delete it also.
Dan Gohman1adec832008-06-21 22:08:46 +0000505 Returns[0]->eraseFromParent();
Chris Lattner44a68072004-02-04 04:17:06 +0000506
507 // We are now done with the inlining.
508 return true;
509 }
510
511 // Otherwise, we have the normal case, of more than one block to inline or
512 // multiple return sites.
513
Chris Lattner5e923de2004-02-04 02:51:48 +0000514 // We want to clone the entire callee function into the hole between the
515 // "starter" and "ender" blocks. How we accomplish this depends on whether
516 // this is an invoke instruction or a call instruction.
517 BasicBlock *AfterCallBB;
518 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
Misha Brukmanfd939082005-04-21 23:48:37 +0000519
Chris Lattner5e923de2004-02-04 02:51:48 +0000520 // Add an unconditional branch to make this look like the CallInst case...
Gabor Greif051a9502008-04-06 20:25:17 +0000521 BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
Misha Brukmanfd939082005-04-21 23:48:37 +0000522
Chris Lattner5e923de2004-02-04 02:51:48 +0000523 // Split the basic block. This guarantees that no PHI nodes will have to be
524 // updated due to new incoming edges, and make the invoke case more
525 // symmetric to the call case.
526 AfterCallBB = OrigBB->splitBasicBlock(NewBr,
Chris Lattner284d1b82004-12-11 16:59:54 +0000527 CalledFunc->getName()+".exit");
Misha Brukmanfd939082005-04-21 23:48:37 +0000528
Chris Lattner5e923de2004-02-04 02:51:48 +0000529 } else { // It's a call
Chris Lattner44a68072004-02-04 04:17:06 +0000530 // If this is a call instruction, we need to split the basic block that
531 // the call lives in.
Chris Lattner5e923de2004-02-04 02:51:48 +0000532 //
533 AfterCallBB = OrigBB->splitBasicBlock(TheCall,
Chris Lattner284d1b82004-12-11 16:59:54 +0000534 CalledFunc->getName()+".exit");
Chris Lattner5e923de2004-02-04 02:51:48 +0000535 }
536
Chris Lattner44a68072004-02-04 04:17:06 +0000537 // Change the branch that used to go to AfterCallBB to branch to the first
538 // basic block of the inlined function.
539 //
540 TerminatorInst *Br = OrigBB->getTerminator();
Misha Brukmanfd939082005-04-21 23:48:37 +0000541 assert(Br && Br->getOpcode() == Instruction::Br &&
Chris Lattner44a68072004-02-04 04:17:06 +0000542 "splitBasicBlock broken!");
543 Br->setOperand(0, FirstNewBlock);
544
545
546 // Now that the function is correct, make it a little bit nicer. In
547 // particular, move the basic blocks inserted from the end of the function
548 // into the space made by splitting the source basic block.
Chris Lattner44a68072004-02-04 04:17:06 +0000549 Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
550 FirstNewBlock, Caller->end());
551
Chris Lattner5e923de2004-02-04 02:51:48 +0000552 // Handle all of the return instructions that we just cloned in, and eliminate
553 // any users of the original call/invoke instruction.
Devang Patelb8f198a2008-03-10 18:34:00 +0000554 const Type *RTy = CalledFunc->getReturnType();
Dan Gohman2c317502008-06-20 01:03:44 +0000555
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000556 if (Returns.size() > 1) {
Chris Lattner5e923de2004-02-04 02:51:48 +0000557 // The PHI node should go at the front of the new basic block to merge all
558 // possible incoming values.
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000559 PHINode *PHI = 0;
Chris Lattner5e923de2004-02-04 02:51:48 +0000560 if (!TheCall->use_empty()) {
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000561 PHI = PHINode::Create(RTy, TheCall->getName(),
562 AfterCallBB->begin());
563 // Anything that used the result of the function call should now use the
564 // PHI node as their operand.
Duncan Sandsa7212e52008-09-05 12:37:12 +0000565 TheCall->replaceAllUsesWith(PHI);
Chris Lattner5e923de2004-02-04 02:51:48 +0000566 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000567
Gabor Greifc478e522009-01-15 18:40:09 +0000568 // Loop over all of the return instructions adding entries to the PHI node
569 // as appropriate.
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000570 if (PHI) {
571 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
572 ReturnInst *RI = Returns[i];
573 assert(RI->getReturnValue()->getType() == PHI->getType() &&
574 "Ret value not consistent in function!");
575 PHI->addIncoming(RI->getReturnValue(), RI->getParent());
Devang Patel12a466b2008-03-07 20:06:16 +0000576 }
Chris Lattnerc581acb2009-10-27 05:39:41 +0000577
578 // Now that we inserted the PHI, check to see if it has a single value
579 // (e.g. all the entries are the same or undef). If so, remove the PHI so
580 // it doesn't block other optimizations.
581 if (Value *V = PHI->hasConstantValue()) {
582 PHI->replaceAllUsesWith(V);
583 PHI->eraseFromParent();
584 }
Devang Patel12a466b2008-03-07 20:06:16 +0000585 }
586
Chris Lattnerc581acb2009-10-27 05:39:41 +0000587
Gabor Greifde62aea2009-01-16 23:08:50 +0000588 // Add a branch to the merge points and remove return instructions.
Chris Lattner5e923de2004-02-04 02:51:48 +0000589 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
590 ReturnInst *RI = Returns[i];
Dale Johannesen0744f092009-03-04 02:09:48 +0000591 BranchInst::Create(AfterCallBB, RI);
Devang Patelb8f198a2008-03-10 18:34:00 +0000592 RI->eraseFromParent();
Chris Lattner5e923de2004-02-04 02:51:48 +0000593 }
Devang Patelb8f198a2008-03-10 18:34:00 +0000594 } else if (!Returns.empty()) {
595 // Otherwise, if there is exactly one return value, just replace anything
596 // using the return value of the call with the computed value.
Eli Friedman5877ad72009-05-08 00:22:04 +0000597 if (!TheCall->use_empty()) {
598 if (TheCall == Returns[0]->getReturnValue())
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000599 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Eli Friedman5877ad72009-05-08 00:22:04 +0000600 else
601 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
602 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000603
Devang Patelb8f198a2008-03-10 18:34:00 +0000604 // Splice the code from the return block into the block that it will return
605 // to, which contains the code that was after the call.
606 BasicBlock *ReturnBB = Returns[0]->getParent();
607 AfterCallBB->getInstList().splice(AfterCallBB->begin(),
608 ReturnBB->getInstList());
Duncan Sandsa7212e52008-09-05 12:37:12 +0000609
Devang Patelb8f198a2008-03-10 18:34:00 +0000610 // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
611 ReturnBB->replaceAllUsesWith(AfterCallBB);
Duncan Sandsa7212e52008-09-05 12:37:12 +0000612
Devang Patelb8f198a2008-03-10 18:34:00 +0000613 // Delete the return instruction now and empty ReturnBB now.
614 Returns[0]->eraseFromParent();
615 ReturnBB->eraseFromParent();
Chris Lattner3787e762004-10-17 23:21:07 +0000616 } else if (!TheCall->use_empty()) {
617 // No returns, but something is using the return value of the call. Just
618 // nuke the result.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000619 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Chris Lattner5e923de2004-02-04 02:51:48 +0000620 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000621
Chris Lattner5e923de2004-02-04 02:51:48 +0000622 // Since we are now done with the Call/Invoke, we can delete it.
Chris Lattner3787e762004-10-17 23:21:07 +0000623 TheCall->eraseFromParent();
Chris Lattnerca398dc2003-05-29 15:11:31 +0000624
Chris Lattner7152c232003-08-24 04:06:56 +0000625 // We should always be able to fold the entry block of the function into the
626 // single predecessor of the block...
Chris Lattnercd01ae52004-04-16 05:17:59 +0000627 assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
Chris Lattner7152c232003-08-24 04:06:56 +0000628 BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
Chris Lattner44a68072004-02-04 04:17:06 +0000629
Chris Lattnercd01ae52004-04-16 05:17:59 +0000630 // Splice the code entry block into calling block, right before the
631 // unconditional branch.
632 OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
633 CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
634
635 // Remove the unconditional branch.
636 OrigBB->getInstList().erase(Br);
637
638 // Now we can remove the CalleeEntry block, which is now empty.
639 Caller->getBasicBlockList().erase(CalleeEntry);
Duncan Sandsa7212e52008-09-05 12:37:12 +0000640
Chris Lattnerca398dc2003-05-29 15:11:31 +0000641 return true;
642}