blob: 69793ab8361de59ec36e2985d3d1cd5b32ff53bf [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//
John McCalla3de16b2011-05-27 18:34:38 +000013// 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].
19//
Chris Lattnerca398dc2003-05-29 15:11:31 +000020//===----------------------------------------------------------------------===//
21
22#include "llvm/Transforms/Utils/Cloning.h"
Chris Lattner3787e762004-10-17 23:21:07 +000023#include "llvm/Constants.h"
Chris Lattner7152c232003-08-24 04:06:56 +000024#include "llvm/DerivedTypes.h"
Chris Lattnerca398dc2003-05-29 15:11:31 +000025#include "llvm/Module.h"
Chris Lattner80a38d22003-08-24 06:59:16 +000026#include "llvm/Instructions.h"
Devang Patel517576d2009-04-15 00:17:06 +000027#include "llvm/IntrinsicInst.h"
Chris Lattner80a38d22003-08-24 06:59:16 +000028#include "llvm/Intrinsics.h"
Devang Pateleaf42ab2008-09-23 23:03:40 +000029#include "llvm/Attributes.h"
Chris Lattner468fb1d2006-01-14 20:07:50 +000030#include "llvm/Analysis/CallGraph.h"
Devang Patel517576d2009-04-15 00:17:06 +000031#include "llvm/Analysis/DebugInfo.h"
Duncan Sands6fb881c2010-11-17 11:16:23 +000032#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattnerc93adca2008-01-11 06:09:30 +000033#include "llvm/Target/TargetData.h"
Chris Lattner7569d792010-12-25 20:42:38 +000034#include "llvm/Transforms/Utils/Local.h"
Chris Lattner93e985f2007-02-13 02:10:56 +000035#include "llvm/ADT/SmallVector.h"
Devang Patel641ca932008-03-10 18:22:16 +000036#include "llvm/ADT/StringExtras.h"
Chris Lattner80a38d22003-08-24 06:59:16 +000037#include "llvm/Support/CallSite.h"
Nick Lewycky6d55f222011-05-22 05:22:10 +000038#include "llvm/Support/IRBuilder.h"
Chris Lattnerf7703df2004-01-09 06:12:26 +000039using namespace llvm;
Chris Lattnerca398dc2003-05-29 15:11:31 +000040
Chris Lattner60915142010-04-22 23:07:58 +000041bool llvm::InlineFunction(CallInst *CI, InlineFunctionInfo &IFI) {
42 return InlineFunction(CallSite(CI), IFI);
Chris Lattner468fb1d2006-01-14 20:07:50 +000043}
Chris Lattner60915142010-04-22 23:07:58 +000044bool llvm::InlineFunction(InvokeInst *II, InlineFunctionInfo &IFI) {
45 return InlineFunction(CallSite(II), IFI);
Chris Lattner468fb1d2006-01-14 20:07:50 +000046}
Chris Lattner80a38d22003-08-24 06:59:16 +000047
John McCalla3de16b2011-05-27 18:34:38 +000048namespace {
49 /// A class for recording information about inlining through an invoke.
50 class InvokeInliningInfo {
51 BasicBlock *UnwindDest;
52 SmallVector<Value*, 8> UnwindDestPHIValues;
53
54 public:
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);
65 }
66 }
67
68 BasicBlock *getUnwindDest() const {
69 return UnwindDest;
70 }
71
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);
80 }
81 }
82 };
83}
84
85/// [LIBUNWIND] Check whether the given value is the _Unwind_Resume
86/// function specified by the Itanium EH ABI.
87static bool isUnwindResume(Value *value) {
88 Function *fn = dyn_cast<Function>(value);
89 if (!fn) return false;
90
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));
99}
100
101/// [LIBUNWIND] Find the (possibly absent) call to @llvm.eh.selector in
102/// the given landing pad.
103static 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))
106 return selector;
107 return 0;
108}
109
110/// [LIBUNWIND] Check whether this selector is "only cleanups":
111/// call i32 @llvm.eh.selector(blah, blah, i32 0)
112static 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());
116}
Chris Lattner135755d2009-08-27 03:51:50 +0000117
118/// HandleCallsInBlockInlinedThroughInvoke - When we inline a basic block into
Eric Christopherf61f89a2009-09-06 22:20:54 +0000119/// an invoke, we have to turn all of the calls that can throw into
Chris Lattner135755d2009-08-27 03:51:50 +0000120/// 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
Chris Lattner81dfb382009-09-01 18:44:06 +0000122/// nodes in that block with the values specified in InvokeDestPHIValues.
Chris Lattner135755d2009-08-27 03:51:50 +0000123///
John McCalla3de16b2011-05-27 18:34:38 +0000124/// Returns true to indicate that the next block should be skipped.
125static bool HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB,
126 InvokeInliningInfo &Invoke) {
Chris Lattner135755d2009-08-27 03:51:50 +0000127 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
128 Instruction *I = BBI++;
129
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;
John McCalla3de16b2011-05-27 18:34:38 +0000134
135 // LIBUNWIND: merge selector instructions.
136 if (EHSelectorInst *Inner = dyn_cast<EHSelectorInst>(CI)) {
137 EHSelectorInst *Outer = findSelectorForLandingPad(Invoke.getUnwindDest());
138 if (!Outer) continue;
139
140 bool innerIsOnlyCleanup = isCleanupOnlySelector(Inner);
141 bool outerIsOnlyCleanup = isCleanupOnlySelector(Outer);
142
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;
147
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));
154
155 CallInst *NewInner = CallInst::Create(Inner->getCalledValue(),
156 NewSelector.begin(),
157 NewSelector.end(),
158 "",
159 Inner);
160 // No need to copy attributes, calling convention, etc.
161 NewInner->takeName(Inner);
162 Inner->replaceAllUsesWith(NewInner);
163 Inner->eraseFromParent();
164 continue;
165 }
Chris Lattner135755d2009-08-27 03:51:50 +0000166
167 // If this call cannot unwind, don't convert it to an invoke.
168 if (CI->doesNotThrow())
169 continue;
170
171 // Convert this function call into an invoke instruction.
172 // First, split the basic block.
173 BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
John McCalla3de16b2011-05-27 18:34:38 +0000174
175 bool skipNextBlock = false;
176
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());
181
182 // TODO: 'Split' is now unreachable; clean it up.
183
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;
188
189 // Otherwise, create the new invoke instruction.
190 } else {
191 ImmutableCallSite CS(CI);
192 SmallVector<Value*, 8> InvokeArgs(CS.arg_begin(), CS.arg_end());
193 InvokeInst *II =
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());
Chris Lattner135755d2009-08-27 03:51:50 +0000199
John McCalla3de16b2011-05-27 18:34:38 +0000200 // 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);
203
204 Split->getInstList().pop_front(); // Delete the original call
205 }
Chris Lattner135755d2009-08-27 03:51:50 +0000206
Chris Lattner135755d2009-08-27 03:51:50 +0000207 // Delete the unconditional branch inserted by splitBasicBlock
208 BB->getInstList().pop_back();
Chris Lattner135755d2009-08-27 03:51:50 +0000209
210 // Update any PHI nodes in the exceptional block to indicate that
211 // there is now a new entry in them.
John McCalla3de16b2011-05-27 18:34:38 +0000212 Invoke.addIncomingPHIValuesFor(BB);
Chris Lattner135755d2009-08-27 03:51:50 +0000213
214 // This basic block is now complete, the caller will continue scanning the
215 // next one.
John McCalla3de16b2011-05-27 18:34:38 +0000216 return skipNextBlock;
Chris Lattner135755d2009-08-27 03:51:50 +0000217 }
John McCalla3de16b2011-05-27 18:34:38 +0000218
219 return false;
Chris Lattner135755d2009-08-27 03:51:50 +0000220}
221
222
Chris Lattnercd4d3392006-01-13 19:05:59 +0000223/// 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.
226///
Nick Lewyckydac5c4b2009-02-03 04:34:40 +0000227/// II is the invoke instruction being inlined. FirstNewBlock is the first
Chris Lattnercd4d3392006-01-13 19:05:59 +0000228/// 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.
230static void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
Chris Lattner81dfb382009-09-01 18:44:06 +0000231 ClonedCodeInfo &InlinedCodeInfo) {
Chris Lattnercd4d3392006-01-13 19:05:59 +0000232 BasicBlock *InvokeDest = II->getUnwindDest();
Chris Lattnercd4d3392006-01-13 19:05:59 +0000233
234 Function *Caller = FirstNewBlock->getParent();
Duncan Sandsa7212e52008-09-05 12:37:12 +0000235
Chris Lattnercd4d3392006-01-13 19:05:59 +0000236 // 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
Chris Lattner135755d2009-08-27 03:51:50 +0000238 // 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
244 // PHI node) now.
245 InvokeDest->removePredecessor(II->getParent());
246 return;
247 }
John McCalla3de16b2011-05-27 18:34:38 +0000248
249 InvokeInliningInfo Invoke(II);
Chris Lattner135755d2009-08-27 03:51:50 +0000250
Chris Lattner135755d2009-08-27 03:51:50 +0000251 for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; ++BB){
252 if (InlinedCodeInfo.ContainsCalls)
John McCalla3de16b2011-05-27 18:34:38 +0000253 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.
256 ++BB;
257 continue;
258 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000259
Chris Lattner135755d2009-08-27 03:51:50 +0000260 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);
Chris Lattnercd4d3392006-01-13 19:05:59 +0000266
Chris Lattner135755d2009-08-27 03:51:50 +0000267 // Delete the unwind instruction!
268 UI->eraseFromParent();
Duncan Sandsa3355ff2007-12-03 20:06:50 +0000269
Chris Lattner135755d2009-08-27 03:51:50 +0000270 // Update any PHI nodes in the exceptional block to indicate that
271 // there is now a new entry in them.
John McCalla3de16b2011-05-27 18:34:38 +0000272 Invoke.addIncomingPHIValuesFor(BB);
Chris Lattnercd4d3392006-01-13 19:05:59 +0000273 }
274 }
275
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
279 // PHI node) now.
280 InvokeDest->removePredecessor(II->getParent());
281}
282
Chris Lattnerd85340f2006-07-12 18:29:36 +0000283/// 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
Duncan Sandsd7b98512008-09-08 11:05:51 +0000286/// some edges of the callgraph may remain.
287static void UpdateCallGraphAfterInlining(CallSite CS,
Chris Lattnerd85340f2006-07-12 18:29:36 +0000288 Function::iterator FirstNewBlock,
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000289 ValueToValueMapTy &VMap,
Chris Lattnerfe9af3b2010-04-22 23:37:35 +0000290 InlineFunctionInfo &IFI) {
291 CallGraph &CG = *IFI.CG;
Duncan Sandsd7b98512008-09-08 11:05:51 +0000292 const Function *Caller = CS.getInstruction()->getParent()->getParent();
293 const Function *Callee = CS.getCalledFunction();
Chris Lattner468fb1d2006-01-14 20:07:50 +0000294 CallGraphNode *CalleeNode = CG[Callee];
295 CallGraphNode *CallerNode = CG[Caller];
Duncan Sandsa7212e52008-09-05 12:37:12 +0000296
Chris Lattnerd85340f2006-07-12 18:29:36 +0000297 // Since we inlined some uninlined call sites in the callee into the caller,
Chris Lattner468fb1d2006-01-14 20:07:50 +0000298 // add edges from the caller to all of the callees of the callee.
Gabor Greifc478e522009-01-15 18:40:09 +0000299 CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
300
301 // Consider the case where CalleeNode == CallerNode.
Gabor Greif12532982009-01-17 00:09:08 +0000302 CallGraphNode::CalledFunctionsVector CallCache;
Gabor Greifc478e522009-01-15 18:40:09 +0000303 if (CalleeNode == CallerNode) {
304 CallCache.assign(I, E);
305 I = CallCache.begin();
306 E = CallCache.end();
307 }
308
309 for (; I != E; ++I) {
Chris Lattnera541b0f2009-09-01 06:31:31 +0000310 const Value *OrigCall = I->first;
Duncan Sandsa7212e52008-09-05 12:37:12 +0000311
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000312 ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
Chris Lattner981418b2006-07-12 21:37:11 +0000313 // Only copy the edge if the call was inlined!
Devang Patel29d3dd82010-06-23 23:55:51 +0000314 if (VMI == VMap.end() || VMI->second == 0)
Chris Lattner135755d2009-08-27 03:51:50 +0000315 continue;
316
317 // If the call was inlined, but then constant folded, there is no edge to
318 // add. Check for this case.
Chris Lattnerb957a5e2010-04-22 21:31:00 +0000319 Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
320 if (NewCall == 0) continue;
Chris Lattner0ca2f282010-05-01 01:26:13 +0000321
322 // Remember that this call site got inlined for the client of
323 // InlineFunction.
324 IFI.InlinedCalls.push_back(NewCall);
325
Chris Lattnerb957a5e2010-04-22 21:31:00 +0000326 // 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.
Gabor Greif86099342010-07-27 15:02:37 +0000334 CallerNode->addCalledFunction(CallSite(NewCall), CG[F]);
335
Chris Lattnerb957a5e2010-04-22 21:31:00 +0000336 continue;
337 }
Gabor Greif86099342010-07-27 15:02:37 +0000338
339 CallerNode->addCalledFunction(CallSite(NewCall), I->second);
Chris Lattnerd85340f2006-07-12 18:29:36 +0000340 }
Chris Lattner135755d2009-08-27 03:51:50 +0000341
Dale Johannesen39fa3242009-01-13 22:43:37 +0000342 // 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);
Chris Lattner468fb1d2006-01-14 20:07:50 +0000345}
346
Chris Lattner0b66f632010-12-20 08:10:40 +0000347/// HandleByValArgument - When inlining a call site that has a byval argument,
348/// we have to make the implicit memcpy explicit by adding it.
Chris Lattnere7ae7052010-12-20 07:57:41 +0000349static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
350 const Function *CalledFunc,
351 InlineFunctionInfo &IFI,
352 unsigned ByValAlignment) {
Chris Lattner0b66f632010-12-20 08:10:40 +0000353 const Type *AggTy = cast<PointerType>(Arg->getType())->getElementType();
354
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
357 // temporary.
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.
363 return Arg;
364
Chris Lattner7569d792010-12-25 20:42:38 +0000365 // 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)
369 return Arg;
Chris Lattner0b66f632010-12-20 08:10:40 +0000370
Chris Lattner7569d792010-12-25 20:42:38 +0000371 // 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.
Chris Lattner0b66f632010-12-20 08:10:40 +0000373 }
Chris Lattnere7ae7052010-12-20 07:57:41 +0000374
375 LLVMContext &Context = Arg->getContext();
376
Chris Lattnere7ae7052010-12-20 07:57:41 +0000377 const Type *VoidPtrTy = Type::getInt8PtrTy(Context);
378
379 // Create the alloca. If we have TargetData, use nice alignment.
380 unsigned Align = 1;
381 if (IFI.TD)
382 Align = IFI.TD->getPrefTypeAlignment(AggTy);
383
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);
388
389 Function *Caller = TheCall->getParent()->getParent();
390
391 Value *NewAlloca = new AllocaInst(AggTy, 0, Align, Arg->getName(),
392 &*Caller->begin()->begin());
393 // Emit a memcpy.
394 const Type *Tys[3] = {VoidPtrTy, VoidPtrTy, Type::getInt64Ty(Context)};
395 Function *MemCpyFn = Intrinsic::getDeclaration(Caller->getParent(),
396 Intrinsic::memcpy,
397 Tys, 3);
398 Value *DestCast = new BitCastInst(NewAlloca, VoidPtrTy, "tmp", TheCall);
399 Value *SrcCast = new BitCastInst(Arg, VoidPtrTy, "tmp", TheCall);
400
401 Value *Size;
402 if (IFI.TD == 0)
403 Size = ConstantExpr::getSizeOf(AggTy);
404 else
405 Size = ConstantInt::get(Type::getInt64Ty(Context),
406 IFI.TD->getTypeStoreSize(AggTy));
407
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
410 // better alignment.
411 Value *CallArgs[] = {
412 DestCast, SrcCast, Size,
413 ConstantInt::get(Type::getInt32Ty(Context), 1),
414 ConstantInt::getFalse(Context) // isVolatile
415 };
416 CallInst *TheMemCpy =
417 CallInst::Create(MemCpyFn, CallArgs, CallArgs+5, "", TheCall);
418
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);
424 }
425
426 // Uses of the argument in the function should use our new alloca
427 // instead.
428 return NewAlloca;
429}
430
Nick Lewycky6d55f222011-05-22 05:22:10 +0000431// isUsedByLifetimeMarker - Check whether this Value is used by a lifetime
432// intrinsic.
433static bool isUsedByLifetimeMarker(Value *V) {
434 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE;
435 ++UI) {
436 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*UI)) {
437 switch (II->getIntrinsicID()) {
438 default: break;
439 case Intrinsic::lifetime_start:
440 case Intrinsic::lifetime_end:
441 return true;
442 }
443 }
444 }
445 return false;
446}
447
448// hasLifetimeMarkers - Check whether the given alloca already has
449// lifetime.start or lifetime.end intrinsics.
450static bool hasLifetimeMarkers(AllocaInst *AI) {
451 const Type *Int8PtrTy = Type::getInt8PtrTy(AI->getType()->getContext());
452 if (AI->getType() == Int8PtrTy)
453 return isUsedByLifetimeMarker(AI);
454
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;
457 ++I) {
458 if (I->getType() != Int8PtrTy) continue;
459 if (!isa<BitCastInst>(*I)) continue;
460 if (isUsedByLifetimeMarker(*I))
461 return true;
462 }
463 return false;
464}
465
Chris Lattnerca398dc2003-05-29 15:11:31 +0000466// 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.
469//
Misha Brukmanfd939082005-04-21 23:48:37 +0000470// 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
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000472// exists in the instruction stream. Similarly this will inline a recursive
Chris Lattnerca398dc2003-05-29 15:11:31 +0000473// function by one level.
474//
Chris Lattner60915142010-04-22 23:07:58 +0000475bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI) {
Chris Lattner80a38d22003-08-24 06:59:16 +0000476 Instruction *TheCall = CS.getInstruction();
Owen Andersone922c022009-07-22 00:24:57 +0000477 LLVMContext &Context = TheCall->getContext();
Chris Lattner80a38d22003-08-24 06:59:16 +0000478 assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
479 "Instruction not in function!");
Chris Lattnerca398dc2003-05-29 15:11:31 +0000480
Chris Lattner60915142010-04-22 23:07:58 +0000481 // If IFI has any state in it, zap it before we fill it in.
482 IFI.reset();
483
Chris Lattner80a38d22003-08-24 06:59:16 +0000484 const Function *CalledFunc = CS.getCalledFunction();
Chris Lattnerca398dc2003-05-29 15:11:31 +0000485 if (CalledFunc == 0 || // Can't inline external function or indirect
Reid Spencer5cbf9852007-01-30 20:08:39 +0000486 CalledFunc->isDeclaration() || // call, or call to a vararg function!
Eric Christopher0623e902010-03-24 23:35:21 +0000487 CalledFunc->getFunctionType()->isVarArg()) return false;
Chris Lattnerca398dc2003-05-29 15:11:31 +0000488
Chris Lattneraf9985c2009-02-12 07:06:42 +0000489 // If the call to the callee is not a tail call, we must clear the 'tail'
Chris Lattner1b491412005-05-06 06:47:52 +0000490 // flags on any calls that we inline.
491 bool MustClearTailCallFlags =
Chris Lattneraf9985c2009-02-12 07:06:42 +0000492 !(isa<CallInst>(TheCall) && cast<CallInst>(TheCall)->isTailCall());
Chris Lattner1b491412005-05-06 06:47:52 +0000493
Duncan Sandsf0c33542007-12-19 21:13:37 +0000494 // If the call to the callee cannot throw, set the 'nounwind' flag on any
495 // calls that we inline.
496 bool MarkNoUnwind = CS.doesNotThrow();
497
Chris Lattner80a38d22003-08-24 06:59:16 +0000498 BasicBlock *OrigBB = TheCall->getParent();
Chris Lattnerca398dc2003-05-29 15:11:31 +0000499 Function *Caller = OrigBB->getParent();
500
Gordon Henriksen0e138212007-12-25 03:10:07 +0000501 // 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
503 // caller.
504 // 2. If the caller has a differing GC, it is invalid to inline.
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000505 if (CalledFunc->hasGC()) {
506 if (!Caller->hasGC())
507 Caller->setGC(CalledFunc->getGC());
508 else if (CalledFunc->getGC() != Caller->getGC())
Gordon Henriksen0e138212007-12-25 03:10:07 +0000509 return false;
510 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000511
Chris Lattner5052c912004-02-04 01:41:09 +0000512 // Get an iterator to the last basic block in the function, which will have
513 // the new function inlined after it.
514 //
515 Function::iterator LastBlock = &Caller->back();
516
Chris Lattner5e923de2004-02-04 02:51:48 +0000517 // Make sure to capture all of the return instructions from the cloned
Chris Lattnerca398dc2003-05-29 15:11:31 +0000518 // function.
Chris Lattnerec1bea02009-08-27 04:02:30 +0000519 SmallVector<ReturnInst*, 8> Returns;
Chris Lattnercd4d3392006-01-13 19:05:59 +0000520 ClonedCodeInfo InlinedFunctionInfo;
Dale Johannesen0744f092009-03-04 02:09:48 +0000521 Function::iterator FirstNewBlock;
Duncan Sandsf0c33542007-12-19 21:13:37 +0000522
Devang Patel29d3dd82010-06-23 23:55:51 +0000523 { // Scope to destroy VMap after cloning.
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000524 ValueToValueMapTy VMap;
Chris Lattner5b5bc302006-05-27 01:28:04 +0000525
Dan Gohman9614fcc2008-06-20 17:11:32 +0000526 assert(CalledFunc->arg_size() == CS.arg_size() &&
Chris Lattner5e923de2004-02-04 02:51:48 +0000527 "No varargs calls can be inlined!");
Duncan Sandsa7212e52008-09-05 12:37:12 +0000528
Chris Lattnerc93adca2008-01-11 06:09:30 +0000529 // Calculate the vector of arguments to pass into the function cloner, which
530 // matches up the formal to the actual argument values.
Chris Lattner5e923de2004-02-04 02:51:48 +0000531 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattnerc93adca2008-01-11 06:09:30 +0000532 unsigned ArgNo = 0;
Chris Lattnere4d5c442005-03-15 04:54:21 +0000533 for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
Chris Lattnerc93adca2008-01-11 06:09:30 +0000534 E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
535 Value *ActualArg = *AI;
Duncan Sandsa7212e52008-09-05 12:37:12 +0000536
Duncan Sandsd82375c2008-01-27 18:12:58 +0000537 // 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.
Chris Lattnere7ae7052010-12-20 07:57:41 +0000541 if (CalledFunc->paramHasAttr(ArgNo+1, Attribute::ByVal)) {
542 ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
543 CalledFunc->getParamAlignment(ArgNo+1));
544
Duncan Sands2914ba62010-05-31 21:00:26 +0000545 // Calls that we inline may use the new alloca, so we need to clear
Chris Lattnere7ae7052010-12-20 07:57:41 +0000546 // their 'tail' flags if HandleByValArgument introduced a new alloca and
547 // the callee has calls.
548 MustClearTailCallFlags |= ActualArg != *AI;
Chris Lattnerc93adca2008-01-11 06:09:30 +0000549 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000550
Devang Patel29d3dd82010-06-23 23:55:51 +0000551 VMap[I] = ActualArg;
Chris Lattnerc93adca2008-01-11 06:09:30 +0000552 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000553
Chris Lattner5b5bc302006-05-27 01:28:04 +0000554 // 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.
Dan Gohman6cb8c232010-08-26 15:41:53 +0000558 CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
559 /*ModuleLevelChanges=*/false, Returns, ".i",
Chris Lattner60915142010-04-22 23:07:58 +0000560 &InlinedFunctionInfo, IFI.TD, TheCall);
Duncan Sandsa7212e52008-09-05 12:37:12 +0000561
Chris Lattnerd85340f2006-07-12 18:29:36 +0000562 // Remember the first block that is newly cloned over.
563 FirstNewBlock = LastBlock; ++FirstNewBlock;
Duncan Sandsa7212e52008-09-05 12:37:12 +0000564
Chris Lattnerd85340f2006-07-12 18:29:36 +0000565 // Update the callgraph if requested.
Chris Lattner60915142010-04-22 23:07:58 +0000566 if (IFI.CG)
Devang Patel29d3dd82010-06-23 23:55:51 +0000567 UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
Misha Brukmanfd939082005-04-21 23:48:37 +0000568 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000569
Chris Lattnerca398dc2003-05-29 15:11:31 +0000570 // 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.
574 //
Chris Lattner21f20552006-01-13 18:16:48 +0000575 {
Chris Lattner80a38d22003-08-24 06:59:16 +0000576 BasicBlock::iterator InsertPoint = Caller->begin()->begin();
Chris Lattner5e923de2004-02-04 02:51:48 +0000577 for (BasicBlock::iterator I = FirstNewBlock->begin(),
Chris Lattner135755d2009-08-27 03:51:50 +0000578 E = FirstNewBlock->end(); I != E; ) {
579 AllocaInst *AI = dyn_cast<AllocaInst>(I++);
580 if (AI == 0) continue;
581
582 // If the alloca is now dead, remove it. This often occurs due to code
583 // specialization.
584 if (AI->use_empty()) {
585 AI->eraseFromParent();
586 continue;
Chris Lattner33bb3c82006-09-13 19:23:57 +0000587 }
Chris Lattner135755d2009-08-27 03:51:50 +0000588
589 if (!isa<Constant>(AI->getArraySize()))
590 continue;
591
Chris Lattner39add232010-12-06 07:43:04 +0000592 // Keep track of the static allocas that we inline into the caller.
Chris Lattner60915142010-04-22 23:07:58 +0000593 IFI.StaticAllocas.push_back(AI);
Chris Lattner8f2718f2009-08-27 04:20:52 +0000594
Chris Lattner135755d2009-08-27 03:51:50 +0000595 // Scan for the block of allocas that we can move over, and move them
596 // all at once.
597 while (isa<AllocaInst>(I) &&
Chris Lattner8f2718f2009-08-27 04:20:52 +0000598 isa<Constant>(cast<AllocaInst>(I)->getArraySize())) {
Chris Lattner60915142010-04-22 23:07:58 +0000599 IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
Chris Lattner135755d2009-08-27 03:51:50 +0000600 ++I;
Chris Lattner8f2718f2009-08-27 04:20:52 +0000601 }
Chris Lattner135755d2009-08-27 03:51:50 +0000602
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
605 // reinserted.
606 Caller->getEntryBlock().getInstList().splice(InsertPoint,
607 FirstNewBlock->getInstList(),
608 AI, I);
609 }
Chris Lattner80a38d22003-08-24 06:59:16 +0000610 }
Chris Lattnerca398dc2003-05-29 15:11:31 +0000611
Nick Lewycky6d55f222011-05-22 05:22:10 +0000612 // 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];
625 }
626
627 IRBuilder<> builder(FirstNewBlock->begin());
628 for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
629 AllocaInst *AI = IFI.StaticAllocas[ai];
630
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))
634 continue;
635
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);
642 }
643 }
644 }
645
Chris Lattnerbf229f42006-01-13 19:34:14 +0000646 // 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();
Chris Lattnerbf229f42006-01-13 19:34:14 +0000650 // Get the two intrinsics we care about.
Chris Lattner6128df52009-10-17 05:39:39 +0000651 Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
652 Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
Chris Lattnerd85340f2006-07-12 18:29:36 +0000653
654 // If we are preserving the callgraph, add edges to the stacksave/restore
655 // functions for the calls we insert.
Chris Lattner21ba23d2006-07-18 21:48:57 +0000656 CallGraphNode *StackSaveCGN = 0, *StackRestoreCGN = 0, *CallerNode = 0;
Chris Lattner60915142010-04-22 23:07:58 +0000657 if (CallGraph *CG = IFI.CG) {
Chris Lattner6128df52009-10-17 05:39:39 +0000658 StackSaveCGN = CG->getOrInsertFunction(StackSave);
659 StackRestoreCGN = CG->getOrInsertFunction(StackRestore);
Chris Lattnerd85340f2006-07-12 18:29:36 +0000660 CallerNode = (*CG)[Caller];
661 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000662
Chris Lattnerbf229f42006-01-13 19:34:14 +0000663 // Insert the llvm.stacksave.
Duncan Sandsa7212e52008-09-05 12:37:12 +0000664 CallInst *SavedPtr = CallInst::Create(StackSave, "savedstack",
Gabor Greif051a9502008-04-06 20:25:17 +0000665 FirstNewBlock->begin());
Chris Lattner60915142010-04-22 23:07:58 +0000666 if (IFI.CG) CallerNode->addCalledFunction(SavedPtr, StackSaveCGN);
Duncan Sandsa7212e52008-09-05 12:37:12 +0000667
Chris Lattnerbf229f42006-01-13 19:34:14 +0000668 // Insert a call to llvm.stackrestore before any return instructions in the
669 // inlined function.
Chris Lattnerd85340f2006-07-12 18:29:36 +0000670 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
Gabor Greif051a9502008-04-06 20:25:17 +0000671 CallInst *CI = CallInst::Create(StackRestore, SavedPtr, "", Returns[i]);
Chris Lattner60915142010-04-22 23:07:58 +0000672 if (IFI.CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
Chris Lattnerd85340f2006-07-12 18:29:36 +0000673 }
Chris Lattner468fb1d2006-01-14 20:07:50 +0000674
675 // Count the number of StackRestore calls we insert.
676 unsigned NumStackRestores = Returns.size();
Duncan Sandsa7212e52008-09-05 12:37:12 +0000677
Chris Lattnerbf229f42006-01-13 19:34:14 +0000678 // 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();
682 BB != E; ++BB)
Chris Lattner468fb1d2006-01-14 20:07:50 +0000683 if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
Chris Lattner6128df52009-10-17 05:39:39 +0000684 CallInst *CI = CallInst::Create(StackRestore, SavedPtr, "", UI);
Chris Lattner60915142010-04-22 23:07:58 +0000685 if (IFI.CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
Chris Lattner468fb1d2006-01-14 20:07:50 +0000686 ++NumStackRestores;
687 }
688 }
Chris Lattnerbf229f42006-01-13 19:34:14 +0000689 }
690
Duncan Sandsa7212e52008-09-05 12:37:12 +0000691 // If we are inlining tail call instruction through a call site that isn't
Chris Lattner1fdf4a82006-01-13 19:18:11 +0000692 // marked 'tail', we must remove the tail marker for any calls in the inlined
Duncan Sandsf0c33542007-12-19 21:13:37 +0000693 // code. Also, calls inlined through a 'nounwind' call site should be marked
694 // 'nounwind'.
695 if (InlinedFunctionInfo.ContainsCalls &&
696 (MustClearTailCallFlags || MarkNoUnwind)) {
Chris Lattner1b491412005-05-06 06:47:52 +0000697 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
698 BB != E; ++BB)
699 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Duncan Sandsf0c33542007-12-19 21:13:37 +0000700 if (CallInst *CI = dyn_cast<CallInst>(I)) {
701 if (MustClearTailCallFlags)
702 CI->setTailCall(false);
703 if (MarkNoUnwind)
704 CI->setDoesNotThrow();
705 }
Chris Lattner1b491412005-05-06 06:47:52 +0000706 }
707
Duncan Sandsf0c33542007-12-19 21:13:37 +0000708 // 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();
712 BB != E; ++BB) {
713 TerminatorInst *Term = BB->getTerminator();
714 if (isa<UnwindInst>(Term)) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000715 new UnreachableInst(Context, Term);
Duncan Sandsf0c33542007-12-19 21:13:37 +0000716 BB->getInstList().erase(Term);
717 }
718 }
719
Chris Lattner5e923de2004-02-04 02:51:48 +0000720 // 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.
Chris Lattnercd4d3392006-01-13 19:05:59 +0000723 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
Chris Lattner81dfb382009-09-01 18:44:06 +0000724 HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
Chris Lattner5e923de2004-02-04 02:51:48 +0000725
Chris Lattner44a68072004-02-04 04:17:06 +0000726 // 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();
Misha Brukmanfd939082005-04-21 23:48:37 +0000735
Chris Lattner44a68072004-02-04 04:17:06 +0000736 // If the call site was an invoke instruction, add a branch to the normal
737 // destination.
738 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
Gabor Greif051a9502008-04-06 20:25:17 +0000739 BranchInst::Create(II->getNormalDest(), TheCall);
Chris Lattner44a68072004-02-04 04:17:06 +0000740
741 // If the return instruction returned a value, replace uses of the call with
742 // uses of the returned value.
Devang Pateldc00d422008-03-04 21:15:15 +0000743 if (!TheCall->use_empty()) {
744 ReturnInst *R = Returns[0];
Eli Friedman5877ad72009-05-08 00:22:04 +0000745 if (TheCall == R->getReturnValue())
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000746 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Eli Friedman5877ad72009-05-08 00:22:04 +0000747 else
748 TheCall->replaceAllUsesWith(R->getReturnValue());
Devang Pateldc00d422008-03-04 21:15:15 +0000749 }
Chris Lattner44a68072004-02-04 04:17:06 +0000750 // Since we are now done with the Call/Invoke, we can delete it.
Dan Gohman1adec832008-06-21 22:08:46 +0000751 TheCall->eraseFromParent();
Chris Lattner44a68072004-02-04 04:17:06 +0000752
753 // Since we are now done with the return instruction, delete it also.
Dan Gohman1adec832008-06-21 22:08:46 +0000754 Returns[0]->eraseFromParent();
Chris Lattner44a68072004-02-04 04:17:06 +0000755
756 // We are now done with the inlining.
757 return true;
758 }
759
760 // Otherwise, we have the normal case, of more than one block to inline or
761 // multiple return sites.
762
Chris Lattner5e923de2004-02-04 02:51:48 +0000763 // 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)) {
Misha Brukmanfd939082005-04-21 23:48:37 +0000768
Chris Lattner5e923de2004-02-04 02:51:48 +0000769 // Add an unconditional branch to make this look like the CallInst case...
Gabor Greif051a9502008-04-06 20:25:17 +0000770 BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
Misha Brukmanfd939082005-04-21 23:48:37 +0000771
Chris Lattner5e923de2004-02-04 02:51:48 +0000772 // 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,
Chris Lattner284d1b82004-12-11 16:59:54 +0000776 CalledFunc->getName()+".exit");
Misha Brukmanfd939082005-04-21 23:48:37 +0000777
Chris Lattner5e923de2004-02-04 02:51:48 +0000778 } else { // It's a call
Chris Lattner44a68072004-02-04 04:17:06 +0000779 // If this is a call instruction, we need to split the basic block that
780 // the call lives in.
Chris Lattner5e923de2004-02-04 02:51:48 +0000781 //
782 AfterCallBB = OrigBB->splitBasicBlock(TheCall,
Chris Lattner284d1b82004-12-11 16:59:54 +0000783 CalledFunc->getName()+".exit");
Chris Lattner5e923de2004-02-04 02:51:48 +0000784 }
785
Chris Lattner44a68072004-02-04 04:17:06 +0000786 // Change the branch that used to go to AfterCallBB to branch to the first
787 // basic block of the inlined function.
788 //
789 TerminatorInst *Br = OrigBB->getTerminator();
Misha Brukmanfd939082005-04-21 23:48:37 +0000790 assert(Br && Br->getOpcode() == Instruction::Br &&
Chris Lattner44a68072004-02-04 04:17:06 +0000791 "splitBasicBlock broken!");
792 Br->setOperand(0, FirstNewBlock);
793
794
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.
Chris Lattner44a68072004-02-04 04:17:06 +0000798 Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
799 FirstNewBlock, Caller->end());
800
Chris Lattner5e923de2004-02-04 02:51:48 +0000801 // Handle all of the return instructions that we just cloned in, and eliminate
802 // any users of the original call/invoke instruction.
Devang Patelb8f198a2008-03-10 18:34:00 +0000803 const Type *RTy = CalledFunc->getReturnType();
Dan Gohman2c317502008-06-20 01:03:44 +0000804
Duncan Sands6fb881c2010-11-17 11:16:23 +0000805 PHINode *PHI = 0;
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000806 if (Returns.size() > 1) {
Chris Lattner5e923de2004-02-04 02:51:48 +0000807 // The PHI node should go at the front of the new basic block to merge all
808 // possible incoming values.
Chris Lattner5e923de2004-02-04 02:51:48 +0000809 if (!TheCall->use_empty()) {
Jay Foad3ecfc862011-03-30 11:28:46 +0000810 PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000811 AfterCallBB->begin());
812 // Anything that used the result of the function call should now use the
813 // PHI node as their operand.
Duncan Sandsa7212e52008-09-05 12:37:12 +0000814 TheCall->replaceAllUsesWith(PHI);
Chris Lattner5e923de2004-02-04 02:51:48 +0000815 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000816
Gabor Greifc478e522009-01-15 18:40:09 +0000817 // Loop over all of the return instructions adding entries to the PHI node
818 // as appropriate.
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000819 if (PHI) {
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());
Devang Patel12a466b2008-03-07 20:06:16 +0000825 }
826 }
827
Chris Lattnerc581acb2009-10-27 05:39:41 +0000828
Gabor Greifde62aea2009-01-16 23:08:50 +0000829 // Add a branch to the merge points and remove return instructions.
Chris Lattner5e923de2004-02-04 02:51:48 +0000830 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
831 ReturnInst *RI = Returns[i];
Dale Johannesen0744f092009-03-04 02:09:48 +0000832 BranchInst::Create(AfterCallBB, RI);
Devang Patelb8f198a2008-03-10 18:34:00 +0000833 RI->eraseFromParent();
Chris Lattner5e923de2004-02-04 02:51:48 +0000834 }
Devang Patelb8f198a2008-03-10 18:34:00 +0000835 } 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.
Eli Friedman5877ad72009-05-08 00:22:04 +0000838 if (!TheCall->use_empty()) {
839 if (TheCall == Returns[0]->getReturnValue())
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000840 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Eli Friedman5877ad72009-05-08 00:22:04 +0000841 else
842 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
843 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000844
Devang Patelb8f198a2008-03-10 18:34:00 +0000845 // 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());
Duncan Sandsa7212e52008-09-05 12:37:12 +0000850
Devang Patelb8f198a2008-03-10 18:34:00 +0000851 // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
852 ReturnBB->replaceAllUsesWith(AfterCallBB);
Duncan Sandsa7212e52008-09-05 12:37:12 +0000853
Devang Patelb8f198a2008-03-10 18:34:00 +0000854 // Delete the return instruction now and empty ReturnBB now.
855 Returns[0]->eraseFromParent();
856 ReturnBB->eraseFromParent();
Chris Lattner3787e762004-10-17 23:21:07 +0000857 } else if (!TheCall->use_empty()) {
858 // No returns, but something is using the return value of the call. Just
859 // nuke the result.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000860 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Chris Lattner5e923de2004-02-04 02:51:48 +0000861 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000862
Chris Lattner5e923de2004-02-04 02:51:48 +0000863 // Since we are now done with the Call/Invoke, we can delete it.
Chris Lattner3787e762004-10-17 23:21:07 +0000864 TheCall->eraseFromParent();
Chris Lattnerca398dc2003-05-29 15:11:31 +0000865
Chris Lattner7152c232003-08-24 04:06:56 +0000866 // We should always be able to fold the entry block of the function into the
867 // single predecessor of the block...
Chris Lattnercd01ae52004-04-16 05:17:59 +0000868 assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
Chris Lattner7152c232003-08-24 04:06:56 +0000869 BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
Chris Lattner44a68072004-02-04 04:17:06 +0000870
Chris Lattnercd01ae52004-04-16 05:17:59 +0000871 // 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
875
876 // Remove the unconditional branch.
877 OrigBB->getInstList().erase(Br);
878
879 // Now we can remove the CalleeEntry block, which is now empty.
880 Caller->getBasicBlockList().erase(CalleeEntry);
Duncan Sandsa7212e52008-09-05 12:37:12 +0000881
Duncan Sands6fb881c2010-11-17 11:16:23 +0000882 // 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.
885 if (PHI)
886 if (Value *V = SimplifyInstruction(PHI, IFI.TD)) {
887 PHI->replaceAllUsesWith(V);
888 PHI->eraseFromParent();
889 }
890
Chris Lattnerca398dc2003-05-29 15:11:31 +0000891 return true;
892}