blob: e69dc89fd03fbb86dd6572e5594c4d84b43ca2cd [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 McCalld7c10862011-05-28 07:45:59 +000048/// [LIBUNWIND] Find the (possibly absent) call to @llvm.eh.selector in
49/// the given landing pad.
50static EHSelectorInst *findSelectorForLandingPad(BasicBlock *lpad) {
51 // The llvm.eh.exception call is required to be in the landing pad.
52 for (BasicBlock::iterator i = lpad->begin(), e = lpad->end(); i != e; i++) {
53 EHExceptionInst *exn = dyn_cast<EHExceptionInst>(i);
54 if (!exn) continue;
55
56 EHSelectorInst *selector = 0;
57 for (Instruction::use_iterator
58 ui = exn->use_begin(), ue = exn->use_end(); ui != ue; ++ui) {
59 EHSelectorInst *sel = dyn_cast<EHSelectorInst>(*ui);
60 if (!sel) continue;
61
62 // Immediately accept an eh.selector in the landing pad.
63 if (sel->getParent() == lpad) return sel;
64
65 // Otherwise, use the first selector we see.
66 if (!selector) selector = sel;
67 }
68
69 return selector;
70 }
71
72 return 0;
73}
74
John McCalla3de16b2011-05-27 18:34:38 +000075namespace {
76 /// A class for recording information about inlining through an invoke.
77 class InvokeInliningInfo {
John McCalld7c10862011-05-28 07:45:59 +000078 BasicBlock *OuterUnwindDest;
79 EHSelectorInst *OuterSelector;
80 BasicBlock *InnerUnwindDest;
81 PHINode *InnerExceptionPHI;
82 PHINode *InnerSelectorPHI;
John McCalla3de16b2011-05-27 18:34:38 +000083 SmallVector<Value*, 8> UnwindDestPHIValues;
84
85 public:
John McCalld7c10862011-05-28 07:45:59 +000086 InvokeInliningInfo(InvokeInst *II) :
87 OuterUnwindDest(II->getUnwindDest()), OuterSelector(0),
88 InnerUnwindDest(0), InnerExceptionPHI(0), InnerSelectorPHI(0) {
89
John McCalla3de16b2011-05-27 18:34:38 +000090 // If there are PHI nodes in the unwind destination block, we
91 // need to keep track of which values came into them from the
92 // invoke before removing the edge from this block.
John McCalld7c10862011-05-28 07:45:59 +000093 llvm::BasicBlock *invokeBB = II->getParent();
94 for (BasicBlock::iterator I = OuterUnwindDest->begin();
95 isa<PHINode>(I); ++I) {
John McCalla3de16b2011-05-27 18:34:38 +000096 // Save the value to use for this edge.
John McCalld7c10862011-05-28 07:45:59 +000097 PHINode *phi = cast<PHINode>(I);
98 UnwindDestPHIValues.push_back(phi->getIncomingValueForBlock(invokeBB));
John McCalla3de16b2011-05-27 18:34:38 +000099 }
100 }
101
John McCalld7c10862011-05-28 07:45:59 +0000102 /// The outer unwind destination is the target of unwind edges
103 /// introduced for calls within the inlined function.
104 BasicBlock *getOuterUnwindDest() const {
105 return OuterUnwindDest;
John McCalla3de16b2011-05-27 18:34:38 +0000106 }
107
John McCalld7c10862011-05-28 07:45:59 +0000108 EHSelectorInst *getOuterSelector() {
109 if (!OuterSelector)
110 OuterSelector = findSelectorForLandingPad(OuterUnwindDest);
111 return OuterSelector;
112 }
113
114 BasicBlock *getInnerUnwindDest();
115
116 bool forwardEHResume(CallInst *call, BasicBlock *src);
117
John McCalla3de16b2011-05-27 18:34:38 +0000118 /// Add incoming-PHI values to the unwind destination block for
119 /// the given basic block, using the values for the original
120 /// invoke's source block.
121 void addIncomingPHIValuesFor(BasicBlock *BB) const {
John McCalld7c10862011-05-28 07:45:59 +0000122 addIncomingPHIValuesForInto(BB, OuterUnwindDest);
123 }
124
125 void addIncomingPHIValuesForInto(BasicBlock *src, BasicBlock *dest) const {
126 BasicBlock::iterator I = dest->begin();
John McCalla3de16b2011-05-27 18:34:38 +0000127 for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
John McCalld7c10862011-05-28 07:45:59 +0000128 PHINode *phi = cast<PHINode>(I);
129 phi->addIncoming(UnwindDestPHIValues[i], src);
John McCalla3de16b2011-05-27 18:34:38 +0000130 }
131 }
132 };
133}
134
John McCalld7c10862011-05-28 07:45:59 +0000135/// Get or create a target for the branch out of rewritten calls to
136/// llvm.eh.resume.
137BasicBlock *InvokeInliningInfo::getInnerUnwindDest() {
138 if (InnerUnwindDest) return InnerUnwindDest;
139
140 // Find and hoist the llvm.eh.exception and llvm.eh.selector calls
141 // in the outer landing pad to immediately following the phis.
142 EHSelectorInst *selector = getOuterSelector();
143 if (!selector) return 0;
144
145 // The call to llvm.eh.exception *must* be in the landing pad.
146 Instruction *exn = cast<Instruction>(selector->getArgOperand(0));
147 assert(exn->getParent() == OuterUnwindDest);
148
149 // TODO: recognize when we've already done this, so that we don't
150 // get a linear number of these when inlining calls into lots of
151 // invokes with the same landing pad.
152
153 // Do the hoisting.
154 Instruction *splitPoint = exn->getParent()->getFirstNonPHI();
155 assert(splitPoint != selector && "selector-on-exception dominance broken!");
156 if (splitPoint == exn) {
157 selector->removeFromParent();
158 selector->insertAfter(exn);
159 splitPoint = selector->getNextNode();
160 } else {
161 exn->moveBefore(splitPoint);
162 selector->moveBefore(splitPoint);
163 }
164
165 // Split the landing pad.
166 InnerUnwindDest = OuterUnwindDest->splitBasicBlock(splitPoint,
167 OuterUnwindDest->getName() + ".body");
168
169 // The number of incoming edges we expect to the inner landing pad.
170 const unsigned phiCapacity = 2;
171
172 // Create corresponding new phis for all the phis in the outer landing pad.
173 BasicBlock::iterator insertPoint = InnerUnwindDest->begin();
174 BasicBlock::iterator I = OuterUnwindDest->begin();
175 for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
176 PHINode *outerPhi = cast<PHINode>(I);
177 PHINode *innerPhi = PHINode::Create(outerPhi->getType(), phiCapacity,
178 outerPhi->getName() + ".lpad-body",
179 insertPoint);
John McCalla6d73452011-05-29 03:01:09 +0000180 outerPhi->replaceAllUsesWith(innerPhi);
John McCalld7c10862011-05-28 07:45:59 +0000181 innerPhi->addIncoming(outerPhi, OuterUnwindDest);
182 }
183
184 // Create a phi for the exception value...
185 InnerExceptionPHI = PHINode::Create(exn->getType(), phiCapacity,
186 "exn.lpad-body", insertPoint);
John McCalle669d832011-06-09 19:46:27 +0000187 exn->replaceAllUsesWith(InnerExceptionPHI);
John McCalld7c10862011-05-28 07:45:59 +0000188 selector->setArgOperand(0, exn); // restore this use
189 InnerExceptionPHI->addIncoming(exn, OuterUnwindDest);
190
191 // ...and the selector.
192 InnerSelectorPHI = PHINode::Create(selector->getType(), phiCapacity,
193 "selector.lpad-body", insertPoint);
John McCalle669d832011-06-09 19:46:27 +0000194 selector->replaceAllUsesWith(InnerSelectorPHI);
John McCalld7c10862011-05-28 07:45:59 +0000195 InnerSelectorPHI->addIncoming(selector, OuterUnwindDest);
196
197 // All done.
198 return InnerUnwindDest;
199}
200
201/// [LIBUNWIND] Try to forward the given call, which logically occurs
202/// at the end of the given block, as a branch to the inner unwind
203/// block. Returns true if the call was forwarded.
204bool InvokeInliningInfo::forwardEHResume(CallInst *call, BasicBlock *src) {
John McCall1edbd6f2011-06-01 02:17:11 +0000205 // First, check whether this is a call to the intrinsic.
John McCalld7c10862011-05-28 07:45:59 +0000206 Function *fn = dyn_cast<Function>(call->getCalledValue());
207 if (!fn || fn->getName() != "llvm.eh.resume")
208 return false;
John McCall1edbd6f2011-06-01 02:17:11 +0000209
210 // At this point, we need to return true on all paths, because
211 // otherwise we'll construct an invoke of the intrinsic, which is
212 // not well-formed.
John McCalld7c10862011-05-28 07:45:59 +0000213
John McCall1edbd6f2011-06-01 02:17:11 +0000214 // Try to find or make an inner unwind dest, which will fail if we
215 // can't find a selector call for the outer unwind dest.
John McCalld7c10862011-05-28 07:45:59 +0000216 BasicBlock *dest = getInnerUnwindDest();
John McCall1edbd6f2011-06-01 02:17:11 +0000217 bool hasSelector = (dest != 0);
218
219 // If we failed, just use the outer unwind dest, dropping the
220 // exception and selector on the floor.
221 if (!hasSelector)
222 dest = OuterUnwindDest;
John McCalld7c10862011-05-28 07:45:59 +0000223
224 // Make a branch.
225 BranchInst::Create(dest, src);
226
227 // Update the phis in the destination. They were inserted in an
228 // order which makes this work.
229 addIncomingPHIValuesForInto(src, dest);
John McCall1edbd6f2011-06-01 02:17:11 +0000230
231 if (hasSelector) {
232 InnerExceptionPHI->addIncoming(call->getArgOperand(0), src);
233 InnerSelectorPHI->addIncoming(call->getArgOperand(1), src);
234 }
John McCalld7c10862011-05-28 07:45:59 +0000235
236 return true;
John McCalla3de16b2011-05-27 18:34:38 +0000237}
238
239/// [LIBUNWIND] Check whether this selector is "only cleanups":
240/// call i32 @llvm.eh.selector(blah, blah, i32 0)
241static bool isCleanupOnlySelector(EHSelectorInst *selector) {
242 if (selector->getNumArgOperands() != 3) return false;
243 ConstantInt *val = dyn_cast<ConstantInt>(selector->getArgOperand(2));
244 return (val && val->isZero());
245}
Chris Lattner135755d2009-08-27 03:51:50 +0000246
247/// HandleCallsInBlockInlinedThroughInvoke - When we inline a basic block into
Eric Christopherf61f89a2009-09-06 22:20:54 +0000248/// an invoke, we have to turn all of the calls that can throw into
Chris Lattner135755d2009-08-27 03:51:50 +0000249/// invokes. This function analyze BB to see if there are any calls, and if so,
250/// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
Chris Lattner81dfb382009-09-01 18:44:06 +0000251/// nodes in that block with the values specified in InvokeDestPHIValues.
Chris Lattner135755d2009-08-27 03:51:50 +0000252///
John McCalla3de16b2011-05-27 18:34:38 +0000253/// Returns true to indicate that the next block should be skipped.
254static bool HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB,
255 InvokeInliningInfo &Invoke) {
Chris Lattner135755d2009-08-27 03:51:50 +0000256 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
257 Instruction *I = BBI++;
258
259 // We only need to check for function calls: inlined invoke
260 // instructions require no special handling.
261 CallInst *CI = dyn_cast<CallInst>(I);
262 if (CI == 0) continue;
John McCalla3de16b2011-05-27 18:34:38 +0000263
264 // LIBUNWIND: merge selector instructions.
265 if (EHSelectorInst *Inner = dyn_cast<EHSelectorInst>(CI)) {
John McCalld7c10862011-05-28 07:45:59 +0000266 EHSelectorInst *Outer = Invoke.getOuterSelector();
John McCalla3de16b2011-05-27 18:34:38 +0000267 if (!Outer) continue;
268
269 bool innerIsOnlyCleanup = isCleanupOnlySelector(Inner);
270 bool outerIsOnlyCleanup = isCleanupOnlySelector(Outer);
271
272 // If both selectors contain only cleanups, we don't need to do
273 // anything. TODO: this is really just a very specific instance
274 // of a much more general optimization.
275 if (innerIsOnlyCleanup && outerIsOnlyCleanup) continue;
276
277 // Otherwise, we just append the outer selector to the inner selector.
278 SmallVector<Value*, 16> NewSelector;
279 for (unsigned i = 0, e = Inner->getNumArgOperands(); i != e; ++i)
280 NewSelector.push_back(Inner->getArgOperand(i));
281 for (unsigned i = 2, e = Outer->getNumArgOperands(); i != e; ++i)
282 NewSelector.push_back(Outer->getArgOperand(i));
283
284 CallInst *NewInner = CallInst::Create(Inner->getCalledValue(),
285 NewSelector.begin(),
286 NewSelector.end(),
287 "",
288 Inner);
289 // No need to copy attributes, calling convention, etc.
290 NewInner->takeName(Inner);
291 Inner->replaceAllUsesWith(NewInner);
292 Inner->eraseFromParent();
293 continue;
294 }
Chris Lattner135755d2009-08-27 03:51:50 +0000295
296 // If this call cannot unwind, don't convert it to an invoke.
297 if (CI->doesNotThrow())
298 continue;
299
300 // Convert this function call into an invoke instruction.
301 // First, split the basic block.
302 BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
John McCalla3de16b2011-05-27 18:34:38 +0000303
John McCalld7c10862011-05-28 07:45:59 +0000304 // Delete the unconditional branch inserted by splitBasicBlock
305 BB->getInstList().pop_back();
John McCalla3de16b2011-05-27 18:34:38 +0000306
John McCalld7c10862011-05-28 07:45:59 +0000307 // LIBUNWIND: If this is a call to @llvm.eh.resume, just branch
John McCalla3de16b2011-05-27 18:34:38 +0000308 // directly to the new landing pad.
John McCalld7c10862011-05-28 07:45:59 +0000309 if (Invoke.forwardEHResume(CI, BB)) {
John McCalla3de16b2011-05-27 18:34:38 +0000310 // TODO: 'Split' is now unreachable; clean it up.
311
312 // We want to leave the original call intact so that the call
313 // graph and other structures won't get misled. We also have to
314 // avoid processing the next block, or we'll iterate here forever.
John McCalld7c10862011-05-28 07:45:59 +0000315 return true;
316 }
John McCalla3de16b2011-05-27 18:34:38 +0000317
318 // Otherwise, create the new invoke instruction.
John McCalld7c10862011-05-28 07:45:59 +0000319 ImmutableCallSite CS(CI);
320 SmallVector<Value*, 8> InvokeArgs(CS.arg_begin(), CS.arg_end());
321 InvokeInst *II =
322 InvokeInst::Create(CI->getCalledValue(), Split,
323 Invoke.getOuterUnwindDest(),
324 InvokeArgs.begin(), InvokeArgs.end(),
325 CI->getName(), BB);
326 II->setCallingConv(CI->getCallingConv());
327 II->setAttributes(CI->getAttributes());
Chris Lattner135755d2009-08-27 03:51:50 +0000328
John McCalld7c10862011-05-28 07:45:59 +0000329 // Make sure that anything using the call now uses the invoke! This also
330 // updates the CallGraph if present, because it uses a WeakVH.
331 CI->replaceAllUsesWith(II);
John McCalla3de16b2011-05-27 18:34:38 +0000332
John McCalld7c10862011-05-28 07:45:59 +0000333 Split->getInstList().pop_front(); // Delete the original call
334
Chris Lattner135755d2009-08-27 03:51:50 +0000335 // Update any PHI nodes in the exceptional block to indicate that
336 // there is now a new entry in them.
John McCalla3de16b2011-05-27 18:34:38 +0000337 Invoke.addIncomingPHIValuesFor(BB);
John McCalld7c10862011-05-28 07:45:59 +0000338 return false;
Chris Lattner135755d2009-08-27 03:51:50 +0000339 }
John McCalla3de16b2011-05-27 18:34:38 +0000340
341 return false;
Chris Lattner135755d2009-08-27 03:51:50 +0000342}
343
344
Chris Lattnercd4d3392006-01-13 19:05:59 +0000345/// HandleInlinedInvoke - If we inlined an invoke site, we need to convert calls
346/// in the body of the inlined function into invokes and turn unwind
347/// instructions into branches to the invoke unwind dest.
348///
Nick Lewyckydac5c4b2009-02-03 04:34:40 +0000349/// II is the invoke instruction being inlined. FirstNewBlock is the first
Chris Lattnercd4d3392006-01-13 19:05:59 +0000350/// block of the inlined code (the last block is the end of the function),
351/// and InlineCodeInfo is information about the code that got inlined.
352static void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
Chris Lattner81dfb382009-09-01 18:44:06 +0000353 ClonedCodeInfo &InlinedCodeInfo) {
Chris Lattnercd4d3392006-01-13 19:05:59 +0000354 BasicBlock *InvokeDest = II->getUnwindDest();
Chris Lattnercd4d3392006-01-13 19:05:59 +0000355
356 Function *Caller = FirstNewBlock->getParent();
Duncan Sandsa7212e52008-09-05 12:37:12 +0000357
Chris Lattnercd4d3392006-01-13 19:05:59 +0000358 // The inlined code is currently at the end of the function, scan from the
359 // start of the inlined code to its end, checking for stuff we need to
Chris Lattner135755d2009-08-27 03:51:50 +0000360 // rewrite. If the code doesn't have calls or unwinds, we know there is
361 // nothing to rewrite.
362 if (!InlinedCodeInfo.ContainsCalls && !InlinedCodeInfo.ContainsUnwinds) {
363 // Now that everything is happy, we have one final detail. The PHI nodes in
364 // the exception destination block still have entries due to the original
365 // invoke instruction. Eliminate these entries (which might even delete the
366 // PHI node) now.
367 InvokeDest->removePredecessor(II->getParent());
368 return;
369 }
John McCalla3de16b2011-05-27 18:34:38 +0000370
371 InvokeInliningInfo Invoke(II);
Chris Lattner135755d2009-08-27 03:51:50 +0000372
Chris Lattner135755d2009-08-27 03:51:50 +0000373 for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; ++BB){
374 if (InlinedCodeInfo.ContainsCalls)
John McCalla3de16b2011-05-27 18:34:38 +0000375 if (HandleCallsInBlockInlinedThroughInvoke(BB, Invoke)) {
376 // Honor a request to skip the next block. We don't need to
377 // consider UnwindInsts in this case either.
378 ++BB;
379 continue;
380 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000381
Chris Lattner135755d2009-08-27 03:51:50 +0000382 if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
383 // An UnwindInst requires special handling when it gets inlined into an
384 // invoke site. Once this happens, we know that the unwind would cause
385 // a control transfer to the invoke exception destination, so we can
386 // transform it into a direct branch to the exception destination.
387 BranchInst::Create(InvokeDest, UI);
Chris Lattnercd4d3392006-01-13 19:05:59 +0000388
Chris Lattner135755d2009-08-27 03:51:50 +0000389 // Delete the unwind instruction!
390 UI->eraseFromParent();
Duncan Sandsa3355ff2007-12-03 20:06:50 +0000391
Chris Lattner135755d2009-08-27 03:51:50 +0000392 // Update any PHI nodes in the exceptional block to indicate that
393 // there is now a new entry in them.
John McCalla3de16b2011-05-27 18:34:38 +0000394 Invoke.addIncomingPHIValuesFor(BB);
Chris Lattnercd4d3392006-01-13 19:05:59 +0000395 }
396 }
397
398 // Now that everything is happy, we have one final detail. The PHI nodes in
399 // the exception destination block still have entries due to the original
400 // invoke instruction. Eliminate these entries (which might even delete the
401 // PHI node) now.
402 InvokeDest->removePredecessor(II->getParent());
403}
404
Chris Lattnerd85340f2006-07-12 18:29:36 +0000405/// UpdateCallGraphAfterInlining - Once we have cloned code over from a callee
406/// into the caller, update the specified callgraph to reflect the changes we
407/// made. Note that it's possible that not all code was copied over, so only
Duncan Sandsd7b98512008-09-08 11:05:51 +0000408/// some edges of the callgraph may remain.
409static void UpdateCallGraphAfterInlining(CallSite CS,
Chris Lattnerd85340f2006-07-12 18:29:36 +0000410 Function::iterator FirstNewBlock,
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000411 ValueToValueMapTy &VMap,
Chris Lattnerfe9af3b2010-04-22 23:37:35 +0000412 InlineFunctionInfo &IFI) {
413 CallGraph &CG = *IFI.CG;
Duncan Sandsd7b98512008-09-08 11:05:51 +0000414 const Function *Caller = CS.getInstruction()->getParent()->getParent();
415 const Function *Callee = CS.getCalledFunction();
Chris Lattner468fb1d2006-01-14 20:07:50 +0000416 CallGraphNode *CalleeNode = CG[Callee];
417 CallGraphNode *CallerNode = CG[Caller];
Duncan Sandsa7212e52008-09-05 12:37:12 +0000418
Chris Lattnerd85340f2006-07-12 18:29:36 +0000419 // Since we inlined some uninlined call sites in the callee into the caller,
Chris Lattner468fb1d2006-01-14 20:07:50 +0000420 // add edges from the caller to all of the callees of the callee.
Gabor Greifc478e522009-01-15 18:40:09 +0000421 CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
422
423 // Consider the case where CalleeNode == CallerNode.
Gabor Greif12532982009-01-17 00:09:08 +0000424 CallGraphNode::CalledFunctionsVector CallCache;
Gabor Greifc478e522009-01-15 18:40:09 +0000425 if (CalleeNode == CallerNode) {
426 CallCache.assign(I, E);
427 I = CallCache.begin();
428 E = CallCache.end();
429 }
430
431 for (; I != E; ++I) {
Chris Lattnera541b0f2009-09-01 06:31:31 +0000432 const Value *OrigCall = I->first;
Duncan Sandsa7212e52008-09-05 12:37:12 +0000433
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000434 ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
Chris Lattner981418b2006-07-12 21:37:11 +0000435 // Only copy the edge if the call was inlined!
Devang Patel29d3dd82010-06-23 23:55:51 +0000436 if (VMI == VMap.end() || VMI->second == 0)
Chris Lattner135755d2009-08-27 03:51:50 +0000437 continue;
438
439 // If the call was inlined, but then constant folded, there is no edge to
440 // add. Check for this case.
Chris Lattnerb957a5e2010-04-22 21:31:00 +0000441 Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
442 if (NewCall == 0) continue;
Chris Lattner0ca2f282010-05-01 01:26:13 +0000443
444 // Remember that this call site got inlined for the client of
445 // InlineFunction.
446 IFI.InlinedCalls.push_back(NewCall);
447
Chris Lattnerb957a5e2010-04-22 21:31:00 +0000448 // It's possible that inlining the callsite will cause it to go from an
449 // indirect to a direct call by resolving a function pointer. If this
450 // happens, set the callee of the new call site to a more precise
451 // destination. This can also happen if the call graph node of the caller
452 // was just unnecessarily imprecise.
453 if (I->second->getFunction() == 0)
454 if (Function *F = CallSite(NewCall).getCalledFunction()) {
455 // Indirect call site resolved to direct call.
Gabor Greif86099342010-07-27 15:02:37 +0000456 CallerNode->addCalledFunction(CallSite(NewCall), CG[F]);
457
Chris Lattnerb957a5e2010-04-22 21:31:00 +0000458 continue;
459 }
Gabor Greif86099342010-07-27 15:02:37 +0000460
461 CallerNode->addCalledFunction(CallSite(NewCall), I->second);
Chris Lattnerd85340f2006-07-12 18:29:36 +0000462 }
Chris Lattner135755d2009-08-27 03:51:50 +0000463
Dale Johannesen39fa3242009-01-13 22:43:37 +0000464 // Update the call graph by deleting the edge from Callee to Caller. We must
465 // do this after the loop above in case Caller and Callee are the same.
466 CallerNode->removeCallEdgeFor(CS);
Chris Lattner468fb1d2006-01-14 20:07:50 +0000467}
468
Chris Lattner0b66f632010-12-20 08:10:40 +0000469/// HandleByValArgument - When inlining a call site that has a byval argument,
470/// we have to make the implicit memcpy explicit by adding it.
Chris Lattnere7ae7052010-12-20 07:57:41 +0000471static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
472 const Function *CalledFunc,
473 InlineFunctionInfo &IFI,
474 unsigned ByValAlignment) {
Chris Lattner0b66f632010-12-20 08:10:40 +0000475 const Type *AggTy = cast<PointerType>(Arg->getType())->getElementType();
476
477 // If the called function is readonly, then it could not mutate the caller's
478 // copy of the byval'd memory. In this case, it is safe to elide the copy and
479 // temporary.
480 if (CalledFunc->onlyReadsMemory()) {
481 // If the byval argument has a specified alignment that is greater than the
482 // passed in pointer, then we either have to round up the input pointer or
483 // give up on this transformation.
484 if (ByValAlignment <= 1) // 0 = unspecified, 1 = no particular alignment.
485 return Arg;
486
Chris Lattner7569d792010-12-25 20:42:38 +0000487 // If the pointer is already known to be sufficiently aligned, or if we can
488 // round it up to a larger alignment, then we don't need a temporary.
489 if (getOrEnforceKnownAlignment(Arg, ByValAlignment,
490 IFI.TD) >= ByValAlignment)
491 return Arg;
Chris Lattner0b66f632010-12-20 08:10:40 +0000492
Chris Lattner7569d792010-12-25 20:42:38 +0000493 // Otherwise, we have to make a memcpy to get a safe alignment. This is bad
494 // for code quality, but rarely happens and is required for correctness.
Chris Lattner0b66f632010-12-20 08:10:40 +0000495 }
Chris Lattnere7ae7052010-12-20 07:57:41 +0000496
497 LLVMContext &Context = Arg->getContext();
498
Chris Lattnere7ae7052010-12-20 07:57:41 +0000499 const Type *VoidPtrTy = Type::getInt8PtrTy(Context);
500
501 // Create the alloca. If we have TargetData, use nice alignment.
502 unsigned Align = 1;
503 if (IFI.TD)
504 Align = IFI.TD->getPrefTypeAlignment(AggTy);
505
506 // If the byval had an alignment specified, we *must* use at least that
507 // alignment, as it is required by the byval argument (and uses of the
508 // pointer inside the callee).
509 Align = std::max(Align, ByValAlignment);
510
511 Function *Caller = TheCall->getParent()->getParent();
512
513 Value *NewAlloca = new AllocaInst(AggTy, 0, Align, Arg->getName(),
514 &*Caller->begin()->begin());
515 // Emit a memcpy.
516 const Type *Tys[3] = {VoidPtrTy, VoidPtrTy, Type::getInt64Ty(Context)};
517 Function *MemCpyFn = Intrinsic::getDeclaration(Caller->getParent(),
518 Intrinsic::memcpy,
519 Tys, 3);
520 Value *DestCast = new BitCastInst(NewAlloca, VoidPtrTy, "tmp", TheCall);
521 Value *SrcCast = new BitCastInst(Arg, VoidPtrTy, "tmp", TheCall);
522
523 Value *Size;
524 if (IFI.TD == 0)
525 Size = ConstantExpr::getSizeOf(AggTy);
526 else
527 Size = ConstantInt::get(Type::getInt64Ty(Context),
528 IFI.TD->getTypeStoreSize(AggTy));
529
530 // Always generate a memcpy of alignment 1 here because we don't know
531 // the alignment of the src pointer. Other optimizations can infer
532 // better alignment.
533 Value *CallArgs[] = {
534 DestCast, SrcCast, Size,
535 ConstantInt::get(Type::getInt32Ty(Context), 1),
536 ConstantInt::getFalse(Context) // isVolatile
537 };
John McCalle669d832011-06-09 19:46:27 +0000538 CallInst::Create(MemCpyFn, CallArgs, CallArgs+5, "", TheCall);
Chris Lattnere7ae7052010-12-20 07:57:41 +0000539
540 // Uses of the argument in the function should use our new alloca
541 // instead.
542 return NewAlloca;
543}
544
Nick Lewycky6d55f222011-05-22 05:22:10 +0000545// isUsedByLifetimeMarker - Check whether this Value is used by a lifetime
546// intrinsic.
547static bool isUsedByLifetimeMarker(Value *V) {
548 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE;
549 ++UI) {
550 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*UI)) {
551 switch (II->getIntrinsicID()) {
552 default: break;
553 case Intrinsic::lifetime_start:
554 case Intrinsic::lifetime_end:
555 return true;
556 }
557 }
558 }
559 return false;
560}
561
562// hasLifetimeMarkers - Check whether the given alloca already has
563// lifetime.start or lifetime.end intrinsics.
564static bool hasLifetimeMarkers(AllocaInst *AI) {
565 const Type *Int8PtrTy = Type::getInt8PtrTy(AI->getType()->getContext());
566 if (AI->getType() == Int8PtrTy)
567 return isUsedByLifetimeMarker(AI);
568
569 // Do a scan to find all the bitcasts to i8*.
570 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end(); I != E;
571 ++I) {
572 if (I->getType() != Int8PtrTy) continue;
573 if (!isa<BitCastInst>(*I)) continue;
574 if (isUsedByLifetimeMarker(*I))
575 return true;
576 }
577 return false;
578}
579
Chris Lattnerca398dc2003-05-29 15:11:31 +0000580// InlineFunction - This function inlines the called function into the basic
581// block of the caller. This returns false if it is not possible to inline this
582// call. The program is still in a well defined state if this occurs though.
583//
Misha Brukmanfd939082005-04-21 23:48:37 +0000584// Note that this only does one level of inlining. For example, if the
585// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000586// exists in the instruction stream. Similarly this will inline a recursive
Chris Lattnerca398dc2003-05-29 15:11:31 +0000587// function by one level.
588//
Chris Lattner60915142010-04-22 23:07:58 +0000589bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI) {
Chris Lattner80a38d22003-08-24 06:59:16 +0000590 Instruction *TheCall = CS.getInstruction();
Owen Andersone922c022009-07-22 00:24:57 +0000591 LLVMContext &Context = TheCall->getContext();
Chris Lattner80a38d22003-08-24 06:59:16 +0000592 assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
593 "Instruction not in function!");
Chris Lattnerca398dc2003-05-29 15:11:31 +0000594
Chris Lattner60915142010-04-22 23:07:58 +0000595 // If IFI has any state in it, zap it before we fill it in.
596 IFI.reset();
597
Chris Lattner80a38d22003-08-24 06:59:16 +0000598 const Function *CalledFunc = CS.getCalledFunction();
Chris Lattnerca398dc2003-05-29 15:11:31 +0000599 if (CalledFunc == 0 || // Can't inline external function or indirect
Reid Spencer5cbf9852007-01-30 20:08:39 +0000600 CalledFunc->isDeclaration() || // call, or call to a vararg function!
Eric Christopher0623e902010-03-24 23:35:21 +0000601 CalledFunc->getFunctionType()->isVarArg()) return false;
Chris Lattnerca398dc2003-05-29 15:11:31 +0000602
Chris Lattneraf9985c2009-02-12 07:06:42 +0000603 // If the call to the callee is not a tail call, we must clear the 'tail'
Chris Lattner1b491412005-05-06 06:47:52 +0000604 // flags on any calls that we inline.
605 bool MustClearTailCallFlags =
Chris Lattneraf9985c2009-02-12 07:06:42 +0000606 !(isa<CallInst>(TheCall) && cast<CallInst>(TheCall)->isTailCall());
Chris Lattner1b491412005-05-06 06:47:52 +0000607
Duncan Sandsf0c33542007-12-19 21:13:37 +0000608 // If the call to the callee cannot throw, set the 'nounwind' flag on any
609 // calls that we inline.
610 bool MarkNoUnwind = CS.doesNotThrow();
611
Chris Lattner80a38d22003-08-24 06:59:16 +0000612 BasicBlock *OrigBB = TheCall->getParent();
Chris Lattnerca398dc2003-05-29 15:11:31 +0000613 Function *Caller = OrigBB->getParent();
614
Gordon Henriksen0e138212007-12-25 03:10:07 +0000615 // GC poses two hazards to inlining, which only occur when the callee has GC:
616 // 1. If the caller has no GC, then the callee's GC must be propagated to the
617 // caller.
618 // 2. If the caller has a differing GC, it is invalid to inline.
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000619 if (CalledFunc->hasGC()) {
620 if (!Caller->hasGC())
621 Caller->setGC(CalledFunc->getGC());
622 else if (CalledFunc->getGC() != Caller->getGC())
Gordon Henriksen0e138212007-12-25 03:10:07 +0000623 return false;
624 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000625
Chris Lattner5052c912004-02-04 01:41:09 +0000626 // Get an iterator to the last basic block in the function, which will have
627 // the new function inlined after it.
628 //
629 Function::iterator LastBlock = &Caller->back();
630
Chris Lattner5e923de2004-02-04 02:51:48 +0000631 // Make sure to capture all of the return instructions from the cloned
Chris Lattnerca398dc2003-05-29 15:11:31 +0000632 // function.
Chris Lattnerec1bea02009-08-27 04:02:30 +0000633 SmallVector<ReturnInst*, 8> Returns;
Chris Lattnercd4d3392006-01-13 19:05:59 +0000634 ClonedCodeInfo InlinedFunctionInfo;
Dale Johannesen0744f092009-03-04 02:09:48 +0000635 Function::iterator FirstNewBlock;
Duncan Sandsf0c33542007-12-19 21:13:37 +0000636
Devang Patel29d3dd82010-06-23 23:55:51 +0000637 { // Scope to destroy VMap after cloning.
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000638 ValueToValueMapTy VMap;
Chris Lattner5b5bc302006-05-27 01:28:04 +0000639
Dan Gohman9614fcc2008-06-20 17:11:32 +0000640 assert(CalledFunc->arg_size() == CS.arg_size() &&
Chris Lattner5e923de2004-02-04 02:51:48 +0000641 "No varargs calls can be inlined!");
Duncan Sandsa7212e52008-09-05 12:37:12 +0000642
Chris Lattnerc93adca2008-01-11 06:09:30 +0000643 // Calculate the vector of arguments to pass into the function cloner, which
644 // matches up the formal to the actual argument values.
Chris Lattner5e923de2004-02-04 02:51:48 +0000645 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattnerc93adca2008-01-11 06:09:30 +0000646 unsigned ArgNo = 0;
Chris Lattnere4d5c442005-03-15 04:54:21 +0000647 for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
Chris Lattnerc93adca2008-01-11 06:09:30 +0000648 E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
649 Value *ActualArg = *AI;
Duncan Sandsa7212e52008-09-05 12:37:12 +0000650
Duncan Sandsd82375c2008-01-27 18:12:58 +0000651 // When byval arguments actually inlined, we need to make the copy implied
652 // by them explicit. However, we don't do this if the callee is readonly
653 // or readnone, because the copy would be unneeded: the callee doesn't
654 // modify the struct.
Chris Lattnere7ae7052010-12-20 07:57:41 +0000655 if (CalledFunc->paramHasAttr(ArgNo+1, Attribute::ByVal)) {
656 ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
657 CalledFunc->getParamAlignment(ArgNo+1));
658
Duncan Sands2914ba62010-05-31 21:00:26 +0000659 // Calls that we inline may use the new alloca, so we need to clear
Chris Lattnere7ae7052010-12-20 07:57:41 +0000660 // their 'tail' flags if HandleByValArgument introduced a new alloca and
661 // the callee has calls.
662 MustClearTailCallFlags |= ActualArg != *AI;
Chris Lattnerc93adca2008-01-11 06:09:30 +0000663 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000664
Devang Patel29d3dd82010-06-23 23:55:51 +0000665 VMap[I] = ActualArg;
Chris Lattnerc93adca2008-01-11 06:09:30 +0000666 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000667
Chris Lattner5b5bc302006-05-27 01:28:04 +0000668 // We want the inliner to prune the code as it copies. We would LOVE to
669 // have no dead or constant instructions leftover after inlining occurs
670 // (which can happen, e.g., because an argument was constant), but we'll be
671 // happy with whatever the cloner can do.
Dan Gohman6cb8c232010-08-26 15:41:53 +0000672 CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
673 /*ModuleLevelChanges=*/false, Returns, ".i",
Chris Lattner60915142010-04-22 23:07:58 +0000674 &InlinedFunctionInfo, IFI.TD, TheCall);
Duncan Sandsa7212e52008-09-05 12:37:12 +0000675
Chris Lattnerd85340f2006-07-12 18:29:36 +0000676 // Remember the first block that is newly cloned over.
677 FirstNewBlock = LastBlock; ++FirstNewBlock;
Duncan Sandsa7212e52008-09-05 12:37:12 +0000678
Chris Lattnerd85340f2006-07-12 18:29:36 +0000679 // Update the callgraph if requested.
Chris Lattner60915142010-04-22 23:07:58 +0000680 if (IFI.CG)
Devang Patel29d3dd82010-06-23 23:55:51 +0000681 UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
Misha Brukmanfd939082005-04-21 23:48:37 +0000682 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000683
Chris Lattnerca398dc2003-05-29 15:11:31 +0000684 // If there are any alloca instructions in the block that used to be the entry
685 // block for the callee, move them to the entry block of the caller. First
686 // calculate which instruction they should be inserted before. We insert the
687 // instructions at the end of the current alloca list.
688 //
Chris Lattner21f20552006-01-13 18:16:48 +0000689 {
Chris Lattner80a38d22003-08-24 06:59:16 +0000690 BasicBlock::iterator InsertPoint = Caller->begin()->begin();
Chris Lattner5e923de2004-02-04 02:51:48 +0000691 for (BasicBlock::iterator I = FirstNewBlock->begin(),
Chris Lattner135755d2009-08-27 03:51:50 +0000692 E = FirstNewBlock->end(); I != E; ) {
693 AllocaInst *AI = dyn_cast<AllocaInst>(I++);
694 if (AI == 0) continue;
695
696 // If the alloca is now dead, remove it. This often occurs due to code
697 // specialization.
698 if (AI->use_empty()) {
699 AI->eraseFromParent();
700 continue;
Chris Lattner33bb3c82006-09-13 19:23:57 +0000701 }
Chris Lattner135755d2009-08-27 03:51:50 +0000702
703 if (!isa<Constant>(AI->getArraySize()))
704 continue;
705
Chris Lattner39add232010-12-06 07:43:04 +0000706 // Keep track of the static allocas that we inline into the caller.
Chris Lattner60915142010-04-22 23:07:58 +0000707 IFI.StaticAllocas.push_back(AI);
Chris Lattner8f2718f2009-08-27 04:20:52 +0000708
Chris Lattner135755d2009-08-27 03:51:50 +0000709 // Scan for the block of allocas that we can move over, and move them
710 // all at once.
711 while (isa<AllocaInst>(I) &&
Chris Lattner8f2718f2009-08-27 04:20:52 +0000712 isa<Constant>(cast<AllocaInst>(I)->getArraySize())) {
Chris Lattner60915142010-04-22 23:07:58 +0000713 IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
Chris Lattner135755d2009-08-27 03:51:50 +0000714 ++I;
Chris Lattner8f2718f2009-08-27 04:20:52 +0000715 }
Chris Lattner135755d2009-08-27 03:51:50 +0000716
717 // Transfer all of the allocas over in a block. Using splice means
718 // that the instructions aren't removed from the symbol table, then
719 // reinserted.
720 Caller->getEntryBlock().getInstList().splice(InsertPoint,
721 FirstNewBlock->getInstList(),
722 AI, I);
723 }
Chris Lattner80a38d22003-08-24 06:59:16 +0000724 }
Chris Lattnerca398dc2003-05-29 15:11:31 +0000725
Nick Lewycky6d55f222011-05-22 05:22:10 +0000726 // Leave lifetime markers for the static alloca's, scoping them to the
727 // function we just inlined.
728 if (!IFI.StaticAllocas.empty()) {
729 // Also preserve the call graph, if applicable.
730 CallGraphNode *StartCGN = 0, *EndCGN = 0, *CallerNode = 0;
731 if (CallGraph *CG = IFI.CG) {
732 Function *Start = Intrinsic::getDeclaration(Caller->getParent(),
733 Intrinsic::lifetime_start);
734 Function *End = Intrinsic::getDeclaration(Caller->getParent(),
735 Intrinsic::lifetime_end);
736 StartCGN = CG->getOrInsertFunction(Start);
737 EndCGN = CG->getOrInsertFunction(End);
738 CallerNode = (*CG)[Caller];
739 }
740
741 IRBuilder<> builder(FirstNewBlock->begin());
742 for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
743 AllocaInst *AI = IFI.StaticAllocas[ai];
744
745 // If the alloca is already scoped to something smaller than the whole
746 // function then there's no need to add redundant, less accurate markers.
747 if (hasLifetimeMarkers(AI))
748 continue;
749
John McCalle669d832011-06-09 19:46:27 +0000750 builder.CreateLifetimeStart(AI);
Nick Lewycky6d55f222011-05-22 05:22:10 +0000751 for (unsigned ri = 0, re = Returns.size(); ri != re; ++ri) {
752 IRBuilder<> builder(Returns[ri]);
John McCalle669d832011-06-09 19:46:27 +0000753 builder.CreateLifetimeEnd(AI);
Nick Lewycky6d55f222011-05-22 05:22:10 +0000754 }
755 }
756 }
757
Chris Lattnerbf229f42006-01-13 19:34:14 +0000758 // If the inlined code contained dynamic alloca instructions, wrap the inlined
759 // code with llvm.stacksave/llvm.stackrestore intrinsics.
760 if (InlinedFunctionInfo.ContainsDynamicAllocas) {
761 Module *M = Caller->getParent();
Chris Lattnerbf229f42006-01-13 19:34:14 +0000762 // Get the two intrinsics we care about.
Chris Lattner6128df52009-10-17 05:39:39 +0000763 Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
764 Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
Chris Lattnerd85340f2006-07-12 18:29:36 +0000765
Chris Lattnerbf229f42006-01-13 19:34:14 +0000766 // Insert the llvm.stacksave.
Duncan Sandsa7212e52008-09-05 12:37:12 +0000767 CallInst *SavedPtr = CallInst::Create(StackSave, "savedstack",
Gabor Greif051a9502008-04-06 20:25:17 +0000768 FirstNewBlock->begin());
Duncan Sandsa7212e52008-09-05 12:37:12 +0000769
Chris Lattnerbf229f42006-01-13 19:34:14 +0000770 // Insert a call to llvm.stackrestore before any return instructions in the
771 // inlined function.
Chris Lattnerd85340f2006-07-12 18:29:36 +0000772 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
John McCalle669d832011-06-09 19:46:27 +0000773 CallInst::Create(StackRestore, SavedPtr, "", Returns[i]);
Chris Lattnerd85340f2006-07-12 18:29:36 +0000774 }
Chris Lattner468fb1d2006-01-14 20:07:50 +0000775
776 // Count the number of StackRestore calls we insert.
777 unsigned NumStackRestores = Returns.size();
Duncan Sandsa7212e52008-09-05 12:37:12 +0000778
Chris Lattnerbf229f42006-01-13 19:34:14 +0000779 // If we are inlining an invoke instruction, insert restores before each
780 // unwind. These unwinds will be rewritten into branches later.
781 if (InlinedFunctionInfo.ContainsUnwinds && isa<InvokeInst>(TheCall)) {
782 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
783 BB != E; ++BB)
Chris Lattner468fb1d2006-01-14 20:07:50 +0000784 if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
John McCalle669d832011-06-09 19:46:27 +0000785 CallInst::Create(StackRestore, SavedPtr, "", UI);
Chris Lattner468fb1d2006-01-14 20:07:50 +0000786 ++NumStackRestores;
787 }
788 }
Chris Lattnerbf229f42006-01-13 19:34:14 +0000789 }
790
Duncan Sandsa7212e52008-09-05 12:37:12 +0000791 // If we are inlining tail call instruction through a call site that isn't
Chris Lattner1fdf4a82006-01-13 19:18:11 +0000792 // marked 'tail', we must remove the tail marker for any calls in the inlined
Duncan Sandsf0c33542007-12-19 21:13:37 +0000793 // code. Also, calls inlined through a 'nounwind' call site should be marked
794 // 'nounwind'.
795 if (InlinedFunctionInfo.ContainsCalls &&
796 (MustClearTailCallFlags || MarkNoUnwind)) {
Chris Lattner1b491412005-05-06 06:47:52 +0000797 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
798 BB != E; ++BB)
799 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Duncan Sandsf0c33542007-12-19 21:13:37 +0000800 if (CallInst *CI = dyn_cast<CallInst>(I)) {
801 if (MustClearTailCallFlags)
802 CI->setTailCall(false);
803 if (MarkNoUnwind)
804 CI->setDoesNotThrow();
805 }
Chris Lattner1b491412005-05-06 06:47:52 +0000806 }
807
Duncan Sandsf0c33542007-12-19 21:13:37 +0000808 // If we are inlining through a 'nounwind' call site then any inlined 'unwind'
809 // instructions are unreachable.
810 if (InlinedFunctionInfo.ContainsUnwinds && MarkNoUnwind)
811 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
812 BB != E; ++BB) {
813 TerminatorInst *Term = BB->getTerminator();
814 if (isa<UnwindInst>(Term)) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000815 new UnreachableInst(Context, Term);
Duncan Sandsf0c33542007-12-19 21:13:37 +0000816 BB->getInstList().erase(Term);
817 }
818 }
819
Chris Lattner5e923de2004-02-04 02:51:48 +0000820 // If we are inlining for an invoke instruction, we must make sure to rewrite
821 // any inlined 'unwind' instructions into branches to the invoke exception
822 // destination, and call instructions into invoke instructions.
Chris Lattnercd4d3392006-01-13 19:05:59 +0000823 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
Chris Lattner81dfb382009-09-01 18:44:06 +0000824 HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
Chris Lattner5e923de2004-02-04 02:51:48 +0000825
Chris Lattner44a68072004-02-04 04:17:06 +0000826 // If we cloned in _exactly one_ basic block, and if that block ends in a
827 // return instruction, we splice the body of the inlined callee directly into
828 // the calling basic block.
829 if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
830 // Move all of the instructions right before the call.
831 OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
832 FirstNewBlock->begin(), FirstNewBlock->end());
833 // Remove the cloned basic block.
834 Caller->getBasicBlockList().pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +0000835
Chris Lattner44a68072004-02-04 04:17:06 +0000836 // If the call site was an invoke instruction, add a branch to the normal
837 // destination.
838 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
Gabor Greif051a9502008-04-06 20:25:17 +0000839 BranchInst::Create(II->getNormalDest(), TheCall);
Chris Lattner44a68072004-02-04 04:17:06 +0000840
841 // If the return instruction returned a value, replace uses of the call with
842 // uses of the returned value.
Devang Pateldc00d422008-03-04 21:15:15 +0000843 if (!TheCall->use_empty()) {
844 ReturnInst *R = Returns[0];
Eli Friedman5877ad72009-05-08 00:22:04 +0000845 if (TheCall == R->getReturnValue())
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000846 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Eli Friedman5877ad72009-05-08 00:22:04 +0000847 else
848 TheCall->replaceAllUsesWith(R->getReturnValue());
Devang Pateldc00d422008-03-04 21:15:15 +0000849 }
Chris Lattner44a68072004-02-04 04:17:06 +0000850 // Since we are now done with the Call/Invoke, we can delete it.
Dan Gohman1adec832008-06-21 22:08:46 +0000851 TheCall->eraseFromParent();
Chris Lattner44a68072004-02-04 04:17:06 +0000852
853 // Since we are now done with the return instruction, delete it also.
Dan Gohman1adec832008-06-21 22:08:46 +0000854 Returns[0]->eraseFromParent();
Chris Lattner44a68072004-02-04 04:17:06 +0000855
856 // We are now done with the inlining.
857 return true;
858 }
859
860 // Otherwise, we have the normal case, of more than one block to inline or
861 // multiple return sites.
862
Chris Lattner5e923de2004-02-04 02:51:48 +0000863 // We want to clone the entire callee function into the hole between the
864 // "starter" and "ender" blocks. How we accomplish this depends on whether
865 // this is an invoke instruction or a call instruction.
866 BasicBlock *AfterCallBB;
867 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
Misha Brukmanfd939082005-04-21 23:48:37 +0000868
Chris Lattner5e923de2004-02-04 02:51:48 +0000869 // Add an unconditional branch to make this look like the CallInst case...
Gabor Greif051a9502008-04-06 20:25:17 +0000870 BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
Misha Brukmanfd939082005-04-21 23:48:37 +0000871
Chris Lattner5e923de2004-02-04 02:51:48 +0000872 // Split the basic block. This guarantees that no PHI nodes will have to be
873 // updated due to new incoming edges, and make the invoke case more
874 // symmetric to the call case.
875 AfterCallBB = OrigBB->splitBasicBlock(NewBr,
Chris Lattner284d1b82004-12-11 16:59:54 +0000876 CalledFunc->getName()+".exit");
Misha Brukmanfd939082005-04-21 23:48:37 +0000877
Chris Lattner5e923de2004-02-04 02:51:48 +0000878 } else { // It's a call
Chris Lattner44a68072004-02-04 04:17:06 +0000879 // If this is a call instruction, we need to split the basic block that
880 // the call lives in.
Chris Lattner5e923de2004-02-04 02:51:48 +0000881 //
882 AfterCallBB = OrigBB->splitBasicBlock(TheCall,
Chris Lattner284d1b82004-12-11 16:59:54 +0000883 CalledFunc->getName()+".exit");
Chris Lattner5e923de2004-02-04 02:51:48 +0000884 }
885
Chris Lattner44a68072004-02-04 04:17:06 +0000886 // Change the branch that used to go to AfterCallBB to branch to the first
887 // basic block of the inlined function.
888 //
889 TerminatorInst *Br = OrigBB->getTerminator();
Misha Brukmanfd939082005-04-21 23:48:37 +0000890 assert(Br && Br->getOpcode() == Instruction::Br &&
Chris Lattner44a68072004-02-04 04:17:06 +0000891 "splitBasicBlock broken!");
892 Br->setOperand(0, FirstNewBlock);
893
894
895 // Now that the function is correct, make it a little bit nicer. In
896 // particular, move the basic blocks inserted from the end of the function
897 // into the space made by splitting the source basic block.
Chris Lattner44a68072004-02-04 04:17:06 +0000898 Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
899 FirstNewBlock, Caller->end());
900
Chris Lattner5e923de2004-02-04 02:51:48 +0000901 // Handle all of the return instructions that we just cloned in, and eliminate
902 // any users of the original call/invoke instruction.
Devang Patelb8f198a2008-03-10 18:34:00 +0000903 const Type *RTy = CalledFunc->getReturnType();
Dan Gohman2c317502008-06-20 01:03:44 +0000904
Duncan Sands6fb881c2010-11-17 11:16:23 +0000905 PHINode *PHI = 0;
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000906 if (Returns.size() > 1) {
Chris Lattner5e923de2004-02-04 02:51:48 +0000907 // The PHI node should go at the front of the new basic block to merge all
908 // possible incoming values.
Chris Lattner5e923de2004-02-04 02:51:48 +0000909 if (!TheCall->use_empty()) {
Jay Foad3ecfc862011-03-30 11:28:46 +0000910 PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000911 AfterCallBB->begin());
912 // Anything that used the result of the function call should now use the
913 // PHI node as their operand.
Duncan Sandsa7212e52008-09-05 12:37:12 +0000914 TheCall->replaceAllUsesWith(PHI);
Chris Lattner5e923de2004-02-04 02:51:48 +0000915 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000916
Gabor Greifc478e522009-01-15 18:40:09 +0000917 // Loop over all of the return instructions adding entries to the PHI node
918 // as appropriate.
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000919 if (PHI) {
920 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
921 ReturnInst *RI = Returns[i];
922 assert(RI->getReturnValue()->getType() == PHI->getType() &&
923 "Ret value not consistent in function!");
924 PHI->addIncoming(RI->getReturnValue(), RI->getParent());
Devang Patel12a466b2008-03-07 20:06:16 +0000925 }
926 }
927
Chris Lattnerc581acb2009-10-27 05:39:41 +0000928
Gabor Greifde62aea2009-01-16 23:08:50 +0000929 // Add a branch to the merge points and remove return instructions.
Chris Lattner5e923de2004-02-04 02:51:48 +0000930 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
931 ReturnInst *RI = Returns[i];
Dale Johannesen0744f092009-03-04 02:09:48 +0000932 BranchInst::Create(AfterCallBB, RI);
Devang Patelb8f198a2008-03-10 18:34:00 +0000933 RI->eraseFromParent();
Chris Lattner5e923de2004-02-04 02:51:48 +0000934 }
Devang Patelb8f198a2008-03-10 18:34:00 +0000935 } else if (!Returns.empty()) {
936 // Otherwise, if there is exactly one return value, just replace anything
937 // using the return value of the call with the computed value.
Eli Friedman5877ad72009-05-08 00:22:04 +0000938 if (!TheCall->use_empty()) {
939 if (TheCall == Returns[0]->getReturnValue())
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000940 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Eli Friedman5877ad72009-05-08 00:22:04 +0000941 else
942 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
943 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000944
Devang Patelb8f198a2008-03-10 18:34:00 +0000945 // Splice the code from the return block into the block that it will return
946 // to, which contains the code that was after the call.
947 BasicBlock *ReturnBB = Returns[0]->getParent();
948 AfterCallBB->getInstList().splice(AfterCallBB->begin(),
949 ReturnBB->getInstList());
Duncan Sandsa7212e52008-09-05 12:37:12 +0000950
Devang Patelb8f198a2008-03-10 18:34:00 +0000951 // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
952 ReturnBB->replaceAllUsesWith(AfterCallBB);
Duncan Sandsa7212e52008-09-05 12:37:12 +0000953
Devang Patelb8f198a2008-03-10 18:34:00 +0000954 // Delete the return instruction now and empty ReturnBB now.
955 Returns[0]->eraseFromParent();
956 ReturnBB->eraseFromParent();
Chris Lattner3787e762004-10-17 23:21:07 +0000957 } else if (!TheCall->use_empty()) {
958 // No returns, but something is using the return value of the call. Just
959 // nuke the result.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000960 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Chris Lattner5e923de2004-02-04 02:51:48 +0000961 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000962
Chris Lattner5e923de2004-02-04 02:51:48 +0000963 // Since we are now done with the Call/Invoke, we can delete it.
Chris Lattner3787e762004-10-17 23:21:07 +0000964 TheCall->eraseFromParent();
Chris Lattnerca398dc2003-05-29 15:11:31 +0000965
Chris Lattner7152c232003-08-24 04:06:56 +0000966 // We should always be able to fold the entry block of the function into the
967 // single predecessor of the block...
Chris Lattnercd01ae52004-04-16 05:17:59 +0000968 assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
Chris Lattner7152c232003-08-24 04:06:56 +0000969 BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
Chris Lattner44a68072004-02-04 04:17:06 +0000970
Chris Lattnercd01ae52004-04-16 05:17:59 +0000971 // Splice the code entry block into calling block, right before the
972 // unconditional branch.
973 OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
974 CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
975
976 // Remove the unconditional branch.
977 OrigBB->getInstList().erase(Br);
978
979 // Now we can remove the CalleeEntry block, which is now empty.
980 Caller->getBasicBlockList().erase(CalleeEntry);
Duncan Sandsa7212e52008-09-05 12:37:12 +0000981
Duncan Sands6fb881c2010-11-17 11:16:23 +0000982 // If we inserted a phi node, check to see if it has a single value (e.g. all
983 // the entries are the same or undef). If so, remove the PHI so it doesn't
984 // block other optimizations.
985 if (PHI)
986 if (Value *V = SimplifyInstruction(PHI, IFI.TD)) {
987 PHI->replaceAllUsesWith(V);
988 PHI->eraseFromParent();
989 }
990
Chris Lattnerca398dc2003-05-29 15:11:31 +0000991 return true;
992}