blob: 4a8298748326364c53c79d62d5bc4e58edb5da1f [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/// Replace all the instruction uses of a value with a different value.
136/// This has the advantage of not screwing up the CallGraph.
137static void replaceAllInsnUsesWith(Instruction *insn, Value *replacement) {
138 for (Value::use_iterator i = insn->use_begin(), e = insn->use_end();
139 i != e; ) {
140 Use &use = i.getUse();
141 ++i;
142 if (isa<Instruction>(use.getUser()))
143 use.set(replacement);
144 }
John McCalla3de16b2011-05-27 18:34:38 +0000145}
146
John McCalld7c10862011-05-28 07:45:59 +0000147/// Get or create a target for the branch out of rewritten calls to
148/// llvm.eh.resume.
149BasicBlock *InvokeInliningInfo::getInnerUnwindDest() {
150 if (InnerUnwindDest) return InnerUnwindDest;
151
152 // Find and hoist the llvm.eh.exception and llvm.eh.selector calls
153 // in the outer landing pad to immediately following the phis.
154 EHSelectorInst *selector = getOuterSelector();
155 if (!selector) return 0;
156
157 // The call to llvm.eh.exception *must* be in the landing pad.
158 Instruction *exn = cast<Instruction>(selector->getArgOperand(0));
159 assert(exn->getParent() == OuterUnwindDest);
160
161 // TODO: recognize when we've already done this, so that we don't
162 // get a linear number of these when inlining calls into lots of
163 // invokes with the same landing pad.
164
165 // Do the hoisting.
166 Instruction *splitPoint = exn->getParent()->getFirstNonPHI();
167 assert(splitPoint != selector && "selector-on-exception dominance broken!");
168 if (splitPoint == exn) {
169 selector->removeFromParent();
170 selector->insertAfter(exn);
171 splitPoint = selector->getNextNode();
172 } else {
173 exn->moveBefore(splitPoint);
174 selector->moveBefore(splitPoint);
175 }
176
177 // Split the landing pad.
178 InnerUnwindDest = OuterUnwindDest->splitBasicBlock(splitPoint,
179 OuterUnwindDest->getName() + ".body");
180
181 // The number of incoming edges we expect to the inner landing pad.
182 const unsigned phiCapacity = 2;
183
184 // Create corresponding new phis for all the phis in the outer landing pad.
185 BasicBlock::iterator insertPoint = InnerUnwindDest->begin();
186 BasicBlock::iterator I = OuterUnwindDest->begin();
187 for (unsigned i = 0, e = UnwindDestPHIValues.size(); i != e; ++i, ++I) {
188 PHINode *outerPhi = cast<PHINode>(I);
189 PHINode *innerPhi = PHINode::Create(outerPhi->getType(), phiCapacity,
190 outerPhi->getName() + ".lpad-body",
191 insertPoint);
John McCalla6d73452011-05-29 03:01:09 +0000192 outerPhi->replaceAllUsesWith(innerPhi);
John McCalld7c10862011-05-28 07:45:59 +0000193 innerPhi->addIncoming(outerPhi, OuterUnwindDest);
194 }
195
196 // Create a phi for the exception value...
197 InnerExceptionPHI = PHINode::Create(exn->getType(), phiCapacity,
198 "exn.lpad-body", insertPoint);
199 replaceAllInsnUsesWith(exn, InnerExceptionPHI);
200 selector->setArgOperand(0, exn); // restore this use
201 InnerExceptionPHI->addIncoming(exn, OuterUnwindDest);
202
203 // ...and the selector.
204 InnerSelectorPHI = PHINode::Create(selector->getType(), phiCapacity,
205 "selector.lpad-body", insertPoint);
206 replaceAllInsnUsesWith(selector, InnerSelectorPHI);
207 InnerSelectorPHI->addIncoming(selector, OuterUnwindDest);
208
209 // All done.
210 return InnerUnwindDest;
211}
212
213/// [LIBUNWIND] Try to forward the given call, which logically occurs
214/// at the end of the given block, as a branch to the inner unwind
215/// block. Returns true if the call was forwarded.
216bool InvokeInliningInfo::forwardEHResume(CallInst *call, BasicBlock *src) {
John McCall1edbd6f2011-06-01 02:17:11 +0000217 // First, check whether this is a call to the intrinsic.
John McCalld7c10862011-05-28 07:45:59 +0000218 Function *fn = dyn_cast<Function>(call->getCalledValue());
219 if (!fn || fn->getName() != "llvm.eh.resume")
220 return false;
John McCall1edbd6f2011-06-01 02:17:11 +0000221
222 // At this point, we need to return true on all paths, because
223 // otherwise we'll construct an invoke of the intrinsic, which is
224 // not well-formed.
John McCalld7c10862011-05-28 07:45:59 +0000225
John McCall1edbd6f2011-06-01 02:17:11 +0000226 // Try to find or make an inner unwind dest, which will fail if we
227 // can't find a selector call for the outer unwind dest.
John McCalld7c10862011-05-28 07:45:59 +0000228 BasicBlock *dest = getInnerUnwindDest();
John McCall1edbd6f2011-06-01 02:17:11 +0000229 bool hasSelector = (dest != 0);
230
231 // If we failed, just use the outer unwind dest, dropping the
232 // exception and selector on the floor.
233 if (!hasSelector)
234 dest = OuterUnwindDest;
John McCalld7c10862011-05-28 07:45:59 +0000235
236 // Make a branch.
237 BranchInst::Create(dest, src);
238
239 // Update the phis in the destination. They were inserted in an
240 // order which makes this work.
241 addIncomingPHIValuesForInto(src, dest);
John McCall1edbd6f2011-06-01 02:17:11 +0000242
243 if (hasSelector) {
244 InnerExceptionPHI->addIncoming(call->getArgOperand(0), src);
245 InnerSelectorPHI->addIncoming(call->getArgOperand(1), src);
246 }
John McCalld7c10862011-05-28 07:45:59 +0000247
248 return true;
John McCalla3de16b2011-05-27 18:34:38 +0000249}
250
251/// [LIBUNWIND] Check whether this selector is "only cleanups":
252/// call i32 @llvm.eh.selector(blah, blah, i32 0)
253static bool isCleanupOnlySelector(EHSelectorInst *selector) {
254 if (selector->getNumArgOperands() != 3) return false;
255 ConstantInt *val = dyn_cast<ConstantInt>(selector->getArgOperand(2));
256 return (val && val->isZero());
257}
Chris Lattner135755d2009-08-27 03:51:50 +0000258
259/// HandleCallsInBlockInlinedThroughInvoke - When we inline a basic block into
Eric Christopherf61f89a2009-09-06 22:20:54 +0000260/// an invoke, we have to turn all of the calls that can throw into
Chris Lattner135755d2009-08-27 03:51:50 +0000261/// invokes. This function analyze BB to see if there are any calls, and if so,
262/// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
Chris Lattner81dfb382009-09-01 18:44:06 +0000263/// nodes in that block with the values specified in InvokeDestPHIValues.
Chris Lattner135755d2009-08-27 03:51:50 +0000264///
John McCalla3de16b2011-05-27 18:34:38 +0000265/// Returns true to indicate that the next block should be skipped.
266static bool HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB,
267 InvokeInliningInfo &Invoke) {
Chris Lattner135755d2009-08-27 03:51:50 +0000268 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
269 Instruction *I = BBI++;
270
271 // We only need to check for function calls: inlined invoke
272 // instructions require no special handling.
273 CallInst *CI = dyn_cast<CallInst>(I);
274 if (CI == 0) continue;
John McCalla3de16b2011-05-27 18:34:38 +0000275
276 // LIBUNWIND: merge selector instructions.
277 if (EHSelectorInst *Inner = dyn_cast<EHSelectorInst>(CI)) {
John McCalld7c10862011-05-28 07:45:59 +0000278 EHSelectorInst *Outer = Invoke.getOuterSelector();
John McCalla3de16b2011-05-27 18:34:38 +0000279 if (!Outer) continue;
280
281 bool innerIsOnlyCleanup = isCleanupOnlySelector(Inner);
282 bool outerIsOnlyCleanup = isCleanupOnlySelector(Outer);
283
284 // If both selectors contain only cleanups, we don't need to do
285 // anything. TODO: this is really just a very specific instance
286 // of a much more general optimization.
287 if (innerIsOnlyCleanup && outerIsOnlyCleanup) continue;
288
289 // Otherwise, we just append the outer selector to the inner selector.
290 SmallVector<Value*, 16> NewSelector;
291 for (unsigned i = 0, e = Inner->getNumArgOperands(); i != e; ++i)
292 NewSelector.push_back(Inner->getArgOperand(i));
293 for (unsigned i = 2, e = Outer->getNumArgOperands(); i != e; ++i)
294 NewSelector.push_back(Outer->getArgOperand(i));
295
296 CallInst *NewInner = CallInst::Create(Inner->getCalledValue(),
297 NewSelector.begin(),
298 NewSelector.end(),
299 "",
300 Inner);
301 // No need to copy attributes, calling convention, etc.
302 NewInner->takeName(Inner);
303 Inner->replaceAllUsesWith(NewInner);
304 Inner->eraseFromParent();
305 continue;
306 }
Chris Lattner135755d2009-08-27 03:51:50 +0000307
308 // If this call cannot unwind, don't convert it to an invoke.
309 if (CI->doesNotThrow())
310 continue;
311
312 // Convert this function call into an invoke instruction.
313 // First, split the basic block.
314 BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
John McCalla3de16b2011-05-27 18:34:38 +0000315
John McCalld7c10862011-05-28 07:45:59 +0000316 // Delete the unconditional branch inserted by splitBasicBlock
317 BB->getInstList().pop_back();
John McCalla3de16b2011-05-27 18:34:38 +0000318
John McCalld7c10862011-05-28 07:45:59 +0000319 // LIBUNWIND: If this is a call to @llvm.eh.resume, just branch
John McCalla3de16b2011-05-27 18:34:38 +0000320 // directly to the new landing pad.
John McCalld7c10862011-05-28 07:45:59 +0000321 if (Invoke.forwardEHResume(CI, BB)) {
John McCalla3de16b2011-05-27 18:34:38 +0000322 // TODO: 'Split' is now unreachable; clean it up.
323
324 // We want to leave the original call intact so that the call
325 // graph and other structures won't get misled. We also have to
326 // avoid processing the next block, or we'll iterate here forever.
John McCalld7c10862011-05-28 07:45:59 +0000327 return true;
328 }
John McCalla3de16b2011-05-27 18:34:38 +0000329
330 // Otherwise, create the new invoke instruction.
John McCalld7c10862011-05-28 07:45:59 +0000331 ImmutableCallSite CS(CI);
332 SmallVector<Value*, 8> InvokeArgs(CS.arg_begin(), CS.arg_end());
333 InvokeInst *II =
334 InvokeInst::Create(CI->getCalledValue(), Split,
335 Invoke.getOuterUnwindDest(),
336 InvokeArgs.begin(), InvokeArgs.end(),
337 CI->getName(), BB);
338 II->setCallingConv(CI->getCallingConv());
339 II->setAttributes(CI->getAttributes());
Chris Lattner135755d2009-08-27 03:51:50 +0000340
John McCalld7c10862011-05-28 07:45:59 +0000341 // Make sure that anything using the call now uses the invoke! This also
342 // updates the CallGraph if present, because it uses a WeakVH.
343 CI->replaceAllUsesWith(II);
John McCalla3de16b2011-05-27 18:34:38 +0000344
John McCalld7c10862011-05-28 07:45:59 +0000345 Split->getInstList().pop_front(); // Delete the original call
346
Chris Lattner135755d2009-08-27 03:51:50 +0000347 // Update any PHI nodes in the exceptional block to indicate that
348 // there is now a new entry in them.
John McCalla3de16b2011-05-27 18:34:38 +0000349 Invoke.addIncomingPHIValuesFor(BB);
John McCalld7c10862011-05-28 07:45:59 +0000350 return false;
Chris Lattner135755d2009-08-27 03:51:50 +0000351 }
John McCalla3de16b2011-05-27 18:34:38 +0000352
353 return false;
Chris Lattner135755d2009-08-27 03:51:50 +0000354}
355
356
Chris Lattnercd4d3392006-01-13 19:05:59 +0000357/// HandleInlinedInvoke - If we inlined an invoke site, we need to convert calls
358/// in the body of the inlined function into invokes and turn unwind
359/// instructions into branches to the invoke unwind dest.
360///
Nick Lewyckydac5c4b2009-02-03 04:34:40 +0000361/// II is the invoke instruction being inlined. FirstNewBlock is the first
Chris Lattnercd4d3392006-01-13 19:05:59 +0000362/// block of the inlined code (the last block is the end of the function),
363/// and InlineCodeInfo is information about the code that got inlined.
364static void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
Chris Lattner81dfb382009-09-01 18:44:06 +0000365 ClonedCodeInfo &InlinedCodeInfo) {
Chris Lattnercd4d3392006-01-13 19:05:59 +0000366 BasicBlock *InvokeDest = II->getUnwindDest();
Chris Lattnercd4d3392006-01-13 19:05:59 +0000367
368 Function *Caller = FirstNewBlock->getParent();
Duncan Sandsa7212e52008-09-05 12:37:12 +0000369
Chris Lattnercd4d3392006-01-13 19:05:59 +0000370 // The inlined code is currently at the end of the function, scan from the
371 // start of the inlined code to its end, checking for stuff we need to
Chris Lattner135755d2009-08-27 03:51:50 +0000372 // rewrite. If the code doesn't have calls or unwinds, we know there is
373 // nothing to rewrite.
374 if (!InlinedCodeInfo.ContainsCalls && !InlinedCodeInfo.ContainsUnwinds) {
375 // Now that everything is happy, we have one final detail. The PHI nodes in
376 // the exception destination block still have entries due to the original
377 // invoke instruction. Eliminate these entries (which might even delete the
378 // PHI node) now.
379 InvokeDest->removePredecessor(II->getParent());
380 return;
381 }
John McCalla3de16b2011-05-27 18:34:38 +0000382
383 InvokeInliningInfo Invoke(II);
Chris Lattner135755d2009-08-27 03:51:50 +0000384
Chris Lattner135755d2009-08-27 03:51:50 +0000385 for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; ++BB){
386 if (InlinedCodeInfo.ContainsCalls)
John McCalla3de16b2011-05-27 18:34:38 +0000387 if (HandleCallsInBlockInlinedThroughInvoke(BB, Invoke)) {
388 // Honor a request to skip the next block. We don't need to
389 // consider UnwindInsts in this case either.
390 ++BB;
391 continue;
392 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000393
Chris Lattner135755d2009-08-27 03:51:50 +0000394 if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
395 // An UnwindInst requires special handling when it gets inlined into an
396 // invoke site. Once this happens, we know that the unwind would cause
397 // a control transfer to the invoke exception destination, so we can
398 // transform it into a direct branch to the exception destination.
399 BranchInst::Create(InvokeDest, UI);
Chris Lattnercd4d3392006-01-13 19:05:59 +0000400
Chris Lattner135755d2009-08-27 03:51:50 +0000401 // Delete the unwind instruction!
402 UI->eraseFromParent();
Duncan Sandsa3355ff2007-12-03 20:06:50 +0000403
Chris Lattner135755d2009-08-27 03:51:50 +0000404 // Update any PHI nodes in the exceptional block to indicate that
405 // there is now a new entry in them.
John McCalla3de16b2011-05-27 18:34:38 +0000406 Invoke.addIncomingPHIValuesFor(BB);
Chris Lattnercd4d3392006-01-13 19:05:59 +0000407 }
408 }
409
410 // Now that everything is happy, we have one final detail. The PHI nodes in
411 // the exception destination block still have entries due to the original
412 // invoke instruction. Eliminate these entries (which might even delete the
413 // PHI node) now.
414 InvokeDest->removePredecessor(II->getParent());
415}
416
Chris Lattnerd85340f2006-07-12 18:29:36 +0000417/// UpdateCallGraphAfterInlining - Once we have cloned code over from a callee
418/// into the caller, update the specified callgraph to reflect the changes we
419/// made. Note that it's possible that not all code was copied over, so only
Duncan Sandsd7b98512008-09-08 11:05:51 +0000420/// some edges of the callgraph may remain.
421static void UpdateCallGraphAfterInlining(CallSite CS,
Chris Lattnerd85340f2006-07-12 18:29:36 +0000422 Function::iterator FirstNewBlock,
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000423 ValueToValueMapTy &VMap,
Chris Lattnerfe9af3b2010-04-22 23:37:35 +0000424 InlineFunctionInfo &IFI) {
425 CallGraph &CG = *IFI.CG;
Duncan Sandsd7b98512008-09-08 11:05:51 +0000426 const Function *Caller = CS.getInstruction()->getParent()->getParent();
427 const Function *Callee = CS.getCalledFunction();
Chris Lattner468fb1d2006-01-14 20:07:50 +0000428 CallGraphNode *CalleeNode = CG[Callee];
429 CallGraphNode *CallerNode = CG[Caller];
Duncan Sandsa7212e52008-09-05 12:37:12 +0000430
Chris Lattnerd85340f2006-07-12 18:29:36 +0000431 // Since we inlined some uninlined call sites in the callee into the caller,
Chris Lattner468fb1d2006-01-14 20:07:50 +0000432 // add edges from the caller to all of the callees of the callee.
Gabor Greifc478e522009-01-15 18:40:09 +0000433 CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
434
435 // Consider the case where CalleeNode == CallerNode.
Gabor Greif12532982009-01-17 00:09:08 +0000436 CallGraphNode::CalledFunctionsVector CallCache;
Gabor Greifc478e522009-01-15 18:40:09 +0000437 if (CalleeNode == CallerNode) {
438 CallCache.assign(I, E);
439 I = CallCache.begin();
440 E = CallCache.end();
441 }
442
443 for (; I != E; ++I) {
Chris Lattnera541b0f2009-09-01 06:31:31 +0000444 const Value *OrigCall = I->first;
Duncan Sandsa7212e52008-09-05 12:37:12 +0000445
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000446 ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
Chris Lattner981418b2006-07-12 21:37:11 +0000447 // Only copy the edge if the call was inlined!
Devang Patel29d3dd82010-06-23 23:55:51 +0000448 if (VMI == VMap.end() || VMI->second == 0)
Chris Lattner135755d2009-08-27 03:51:50 +0000449 continue;
450
451 // If the call was inlined, but then constant folded, there is no edge to
452 // add. Check for this case.
Chris Lattnerb957a5e2010-04-22 21:31:00 +0000453 Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
454 if (NewCall == 0) continue;
Chris Lattner0ca2f282010-05-01 01:26:13 +0000455
456 // Remember that this call site got inlined for the client of
457 // InlineFunction.
458 IFI.InlinedCalls.push_back(NewCall);
459
Chris Lattnerb957a5e2010-04-22 21:31:00 +0000460 // It's possible that inlining the callsite will cause it to go from an
461 // indirect to a direct call by resolving a function pointer. If this
462 // happens, set the callee of the new call site to a more precise
463 // destination. This can also happen if the call graph node of the caller
464 // was just unnecessarily imprecise.
465 if (I->second->getFunction() == 0)
466 if (Function *F = CallSite(NewCall).getCalledFunction()) {
467 // Indirect call site resolved to direct call.
Gabor Greif86099342010-07-27 15:02:37 +0000468 CallerNode->addCalledFunction(CallSite(NewCall), CG[F]);
469
Chris Lattnerb957a5e2010-04-22 21:31:00 +0000470 continue;
471 }
Gabor Greif86099342010-07-27 15:02:37 +0000472
473 CallerNode->addCalledFunction(CallSite(NewCall), I->second);
Chris Lattnerd85340f2006-07-12 18:29:36 +0000474 }
Chris Lattner135755d2009-08-27 03:51:50 +0000475
Dale Johannesen39fa3242009-01-13 22:43:37 +0000476 // Update the call graph by deleting the edge from Callee to Caller. We must
477 // do this after the loop above in case Caller and Callee are the same.
478 CallerNode->removeCallEdgeFor(CS);
Chris Lattner468fb1d2006-01-14 20:07:50 +0000479}
480
Chris Lattner0b66f632010-12-20 08:10:40 +0000481/// HandleByValArgument - When inlining a call site that has a byval argument,
482/// we have to make the implicit memcpy explicit by adding it.
Chris Lattnere7ae7052010-12-20 07:57:41 +0000483static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
484 const Function *CalledFunc,
485 InlineFunctionInfo &IFI,
486 unsigned ByValAlignment) {
Chris Lattner0b66f632010-12-20 08:10:40 +0000487 const Type *AggTy = cast<PointerType>(Arg->getType())->getElementType();
488
489 // If the called function is readonly, then it could not mutate the caller's
490 // copy of the byval'd memory. In this case, it is safe to elide the copy and
491 // temporary.
492 if (CalledFunc->onlyReadsMemory()) {
493 // If the byval argument has a specified alignment that is greater than the
494 // passed in pointer, then we either have to round up the input pointer or
495 // give up on this transformation.
496 if (ByValAlignment <= 1) // 0 = unspecified, 1 = no particular alignment.
497 return Arg;
498
Chris Lattner7569d792010-12-25 20:42:38 +0000499 // If the pointer is already known to be sufficiently aligned, or if we can
500 // round it up to a larger alignment, then we don't need a temporary.
501 if (getOrEnforceKnownAlignment(Arg, ByValAlignment,
502 IFI.TD) >= ByValAlignment)
503 return Arg;
Chris Lattner0b66f632010-12-20 08:10:40 +0000504
Chris Lattner7569d792010-12-25 20:42:38 +0000505 // Otherwise, we have to make a memcpy to get a safe alignment. This is bad
506 // for code quality, but rarely happens and is required for correctness.
Chris Lattner0b66f632010-12-20 08:10:40 +0000507 }
Chris Lattnere7ae7052010-12-20 07:57:41 +0000508
509 LLVMContext &Context = Arg->getContext();
510
Chris Lattnere7ae7052010-12-20 07:57:41 +0000511 const Type *VoidPtrTy = Type::getInt8PtrTy(Context);
512
513 // Create the alloca. If we have TargetData, use nice alignment.
514 unsigned Align = 1;
515 if (IFI.TD)
516 Align = IFI.TD->getPrefTypeAlignment(AggTy);
517
518 // If the byval had an alignment specified, we *must* use at least that
519 // alignment, as it is required by the byval argument (and uses of the
520 // pointer inside the callee).
521 Align = std::max(Align, ByValAlignment);
522
523 Function *Caller = TheCall->getParent()->getParent();
524
525 Value *NewAlloca = new AllocaInst(AggTy, 0, Align, Arg->getName(),
526 &*Caller->begin()->begin());
527 // Emit a memcpy.
528 const Type *Tys[3] = {VoidPtrTy, VoidPtrTy, Type::getInt64Ty(Context)};
529 Function *MemCpyFn = Intrinsic::getDeclaration(Caller->getParent(),
530 Intrinsic::memcpy,
531 Tys, 3);
532 Value *DestCast = new BitCastInst(NewAlloca, VoidPtrTy, "tmp", TheCall);
533 Value *SrcCast = new BitCastInst(Arg, VoidPtrTy, "tmp", TheCall);
534
535 Value *Size;
536 if (IFI.TD == 0)
537 Size = ConstantExpr::getSizeOf(AggTy);
538 else
539 Size = ConstantInt::get(Type::getInt64Ty(Context),
540 IFI.TD->getTypeStoreSize(AggTy));
541
542 // Always generate a memcpy of alignment 1 here because we don't know
543 // the alignment of the src pointer. Other optimizations can infer
544 // better alignment.
545 Value *CallArgs[] = {
546 DestCast, SrcCast, Size,
547 ConstantInt::get(Type::getInt32Ty(Context), 1),
548 ConstantInt::getFalse(Context) // isVolatile
549 };
550 CallInst *TheMemCpy =
551 CallInst::Create(MemCpyFn, CallArgs, CallArgs+5, "", TheCall);
552
553 // If we have a call graph, update it.
554 if (CallGraph *CG = IFI.CG) {
555 CallGraphNode *MemCpyCGN = CG->getOrInsertFunction(MemCpyFn);
556 CallGraphNode *CallerNode = (*CG)[Caller];
557 CallerNode->addCalledFunction(TheMemCpy, MemCpyCGN);
558 }
559
560 // Uses of the argument in the function should use our new alloca
561 // instead.
562 return NewAlloca;
563}
564
Nick Lewycky6d55f222011-05-22 05:22:10 +0000565// isUsedByLifetimeMarker - Check whether this Value is used by a lifetime
566// intrinsic.
567static bool isUsedByLifetimeMarker(Value *V) {
568 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE;
569 ++UI) {
570 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*UI)) {
571 switch (II->getIntrinsicID()) {
572 default: break;
573 case Intrinsic::lifetime_start:
574 case Intrinsic::lifetime_end:
575 return true;
576 }
577 }
578 }
579 return false;
580}
581
582// hasLifetimeMarkers - Check whether the given alloca already has
583// lifetime.start or lifetime.end intrinsics.
584static bool hasLifetimeMarkers(AllocaInst *AI) {
585 const Type *Int8PtrTy = Type::getInt8PtrTy(AI->getType()->getContext());
586 if (AI->getType() == Int8PtrTy)
587 return isUsedByLifetimeMarker(AI);
588
589 // Do a scan to find all the bitcasts to i8*.
590 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end(); I != E;
591 ++I) {
592 if (I->getType() != Int8PtrTy) continue;
593 if (!isa<BitCastInst>(*I)) continue;
594 if (isUsedByLifetimeMarker(*I))
595 return true;
596 }
597 return false;
598}
599
Chris Lattnerca398dc2003-05-29 15:11:31 +0000600// InlineFunction - This function inlines the called function into the basic
601// block of the caller. This returns false if it is not possible to inline this
602// call. The program is still in a well defined state if this occurs though.
603//
Misha Brukmanfd939082005-04-21 23:48:37 +0000604// Note that this only does one level of inlining. For example, if the
605// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000606// exists in the instruction stream. Similarly this will inline a recursive
Chris Lattnerca398dc2003-05-29 15:11:31 +0000607// function by one level.
608//
Chris Lattner60915142010-04-22 23:07:58 +0000609bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI) {
Chris Lattner80a38d22003-08-24 06:59:16 +0000610 Instruction *TheCall = CS.getInstruction();
Owen Andersone922c022009-07-22 00:24:57 +0000611 LLVMContext &Context = TheCall->getContext();
Chris Lattner80a38d22003-08-24 06:59:16 +0000612 assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
613 "Instruction not in function!");
Chris Lattnerca398dc2003-05-29 15:11:31 +0000614
Chris Lattner60915142010-04-22 23:07:58 +0000615 // If IFI has any state in it, zap it before we fill it in.
616 IFI.reset();
617
Chris Lattner80a38d22003-08-24 06:59:16 +0000618 const Function *CalledFunc = CS.getCalledFunction();
Chris Lattnerca398dc2003-05-29 15:11:31 +0000619 if (CalledFunc == 0 || // Can't inline external function or indirect
Reid Spencer5cbf9852007-01-30 20:08:39 +0000620 CalledFunc->isDeclaration() || // call, or call to a vararg function!
Eric Christopher0623e902010-03-24 23:35:21 +0000621 CalledFunc->getFunctionType()->isVarArg()) return false;
Chris Lattnerca398dc2003-05-29 15:11:31 +0000622
Chris Lattneraf9985c2009-02-12 07:06:42 +0000623 // If the call to the callee is not a tail call, we must clear the 'tail'
Chris Lattner1b491412005-05-06 06:47:52 +0000624 // flags on any calls that we inline.
625 bool MustClearTailCallFlags =
Chris Lattneraf9985c2009-02-12 07:06:42 +0000626 !(isa<CallInst>(TheCall) && cast<CallInst>(TheCall)->isTailCall());
Chris Lattner1b491412005-05-06 06:47:52 +0000627
Duncan Sandsf0c33542007-12-19 21:13:37 +0000628 // If the call to the callee cannot throw, set the 'nounwind' flag on any
629 // calls that we inline.
630 bool MarkNoUnwind = CS.doesNotThrow();
631
Chris Lattner80a38d22003-08-24 06:59:16 +0000632 BasicBlock *OrigBB = TheCall->getParent();
Chris Lattnerca398dc2003-05-29 15:11:31 +0000633 Function *Caller = OrigBB->getParent();
634
Gordon Henriksen0e138212007-12-25 03:10:07 +0000635 // GC poses two hazards to inlining, which only occur when the callee has GC:
636 // 1. If the caller has no GC, then the callee's GC must be propagated to the
637 // caller.
638 // 2. If the caller has a differing GC, it is invalid to inline.
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000639 if (CalledFunc->hasGC()) {
640 if (!Caller->hasGC())
641 Caller->setGC(CalledFunc->getGC());
642 else if (CalledFunc->getGC() != Caller->getGC())
Gordon Henriksen0e138212007-12-25 03:10:07 +0000643 return false;
644 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000645
Chris Lattner5052c912004-02-04 01:41:09 +0000646 // Get an iterator to the last basic block in the function, which will have
647 // the new function inlined after it.
648 //
649 Function::iterator LastBlock = &Caller->back();
650
Chris Lattner5e923de2004-02-04 02:51:48 +0000651 // Make sure to capture all of the return instructions from the cloned
Chris Lattnerca398dc2003-05-29 15:11:31 +0000652 // function.
Chris Lattnerec1bea02009-08-27 04:02:30 +0000653 SmallVector<ReturnInst*, 8> Returns;
Chris Lattnercd4d3392006-01-13 19:05:59 +0000654 ClonedCodeInfo InlinedFunctionInfo;
Dale Johannesen0744f092009-03-04 02:09:48 +0000655 Function::iterator FirstNewBlock;
Duncan Sandsf0c33542007-12-19 21:13:37 +0000656
Devang Patel29d3dd82010-06-23 23:55:51 +0000657 { // Scope to destroy VMap after cloning.
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000658 ValueToValueMapTy VMap;
Chris Lattner5b5bc302006-05-27 01:28:04 +0000659
Dan Gohman9614fcc2008-06-20 17:11:32 +0000660 assert(CalledFunc->arg_size() == CS.arg_size() &&
Chris Lattner5e923de2004-02-04 02:51:48 +0000661 "No varargs calls can be inlined!");
Duncan Sandsa7212e52008-09-05 12:37:12 +0000662
Chris Lattnerc93adca2008-01-11 06:09:30 +0000663 // Calculate the vector of arguments to pass into the function cloner, which
664 // matches up the formal to the actual argument values.
Chris Lattner5e923de2004-02-04 02:51:48 +0000665 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattnerc93adca2008-01-11 06:09:30 +0000666 unsigned ArgNo = 0;
Chris Lattnere4d5c442005-03-15 04:54:21 +0000667 for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
Chris Lattnerc93adca2008-01-11 06:09:30 +0000668 E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
669 Value *ActualArg = *AI;
Duncan Sandsa7212e52008-09-05 12:37:12 +0000670
Duncan Sandsd82375c2008-01-27 18:12:58 +0000671 // When byval arguments actually inlined, we need to make the copy implied
672 // by them explicit. However, we don't do this if the callee is readonly
673 // or readnone, because the copy would be unneeded: the callee doesn't
674 // modify the struct.
Chris Lattnere7ae7052010-12-20 07:57:41 +0000675 if (CalledFunc->paramHasAttr(ArgNo+1, Attribute::ByVal)) {
676 ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
677 CalledFunc->getParamAlignment(ArgNo+1));
678
Duncan Sands2914ba62010-05-31 21:00:26 +0000679 // Calls that we inline may use the new alloca, so we need to clear
Chris Lattnere7ae7052010-12-20 07:57:41 +0000680 // their 'tail' flags if HandleByValArgument introduced a new alloca and
681 // the callee has calls.
682 MustClearTailCallFlags |= ActualArg != *AI;
Chris Lattnerc93adca2008-01-11 06:09:30 +0000683 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000684
Devang Patel29d3dd82010-06-23 23:55:51 +0000685 VMap[I] = ActualArg;
Chris Lattnerc93adca2008-01-11 06:09:30 +0000686 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000687
Chris Lattner5b5bc302006-05-27 01:28:04 +0000688 // We want the inliner to prune the code as it copies. We would LOVE to
689 // have no dead or constant instructions leftover after inlining occurs
690 // (which can happen, e.g., because an argument was constant), but we'll be
691 // happy with whatever the cloner can do.
Dan Gohman6cb8c232010-08-26 15:41:53 +0000692 CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
693 /*ModuleLevelChanges=*/false, Returns, ".i",
Chris Lattner60915142010-04-22 23:07:58 +0000694 &InlinedFunctionInfo, IFI.TD, TheCall);
Duncan Sandsa7212e52008-09-05 12:37:12 +0000695
Chris Lattnerd85340f2006-07-12 18:29:36 +0000696 // Remember the first block that is newly cloned over.
697 FirstNewBlock = LastBlock; ++FirstNewBlock;
Duncan Sandsa7212e52008-09-05 12:37:12 +0000698
Chris Lattnerd85340f2006-07-12 18:29:36 +0000699 // Update the callgraph if requested.
Chris Lattner60915142010-04-22 23:07:58 +0000700 if (IFI.CG)
Devang Patel29d3dd82010-06-23 23:55:51 +0000701 UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
Misha Brukmanfd939082005-04-21 23:48:37 +0000702 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000703
Chris Lattnerca398dc2003-05-29 15:11:31 +0000704 // If there are any alloca instructions in the block that used to be the entry
705 // block for the callee, move them to the entry block of the caller. First
706 // calculate which instruction they should be inserted before. We insert the
707 // instructions at the end of the current alloca list.
708 //
Chris Lattner21f20552006-01-13 18:16:48 +0000709 {
Chris Lattner80a38d22003-08-24 06:59:16 +0000710 BasicBlock::iterator InsertPoint = Caller->begin()->begin();
Chris Lattner5e923de2004-02-04 02:51:48 +0000711 for (BasicBlock::iterator I = FirstNewBlock->begin(),
Chris Lattner135755d2009-08-27 03:51:50 +0000712 E = FirstNewBlock->end(); I != E; ) {
713 AllocaInst *AI = dyn_cast<AllocaInst>(I++);
714 if (AI == 0) continue;
715
716 // If the alloca is now dead, remove it. This often occurs due to code
717 // specialization.
718 if (AI->use_empty()) {
719 AI->eraseFromParent();
720 continue;
Chris Lattner33bb3c82006-09-13 19:23:57 +0000721 }
Chris Lattner135755d2009-08-27 03:51:50 +0000722
723 if (!isa<Constant>(AI->getArraySize()))
724 continue;
725
Chris Lattner39add232010-12-06 07:43:04 +0000726 // Keep track of the static allocas that we inline into the caller.
Chris Lattner60915142010-04-22 23:07:58 +0000727 IFI.StaticAllocas.push_back(AI);
Chris Lattner8f2718f2009-08-27 04:20:52 +0000728
Chris Lattner135755d2009-08-27 03:51:50 +0000729 // Scan for the block of allocas that we can move over, and move them
730 // all at once.
731 while (isa<AllocaInst>(I) &&
Chris Lattner8f2718f2009-08-27 04:20:52 +0000732 isa<Constant>(cast<AllocaInst>(I)->getArraySize())) {
Chris Lattner60915142010-04-22 23:07:58 +0000733 IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
Chris Lattner135755d2009-08-27 03:51:50 +0000734 ++I;
Chris Lattner8f2718f2009-08-27 04:20:52 +0000735 }
Chris Lattner135755d2009-08-27 03:51:50 +0000736
737 // Transfer all of the allocas over in a block. Using splice means
738 // that the instructions aren't removed from the symbol table, then
739 // reinserted.
740 Caller->getEntryBlock().getInstList().splice(InsertPoint,
741 FirstNewBlock->getInstList(),
742 AI, I);
743 }
Chris Lattner80a38d22003-08-24 06:59:16 +0000744 }
Chris Lattnerca398dc2003-05-29 15:11:31 +0000745
Nick Lewycky6d55f222011-05-22 05:22:10 +0000746 // Leave lifetime markers for the static alloca's, scoping them to the
747 // function we just inlined.
748 if (!IFI.StaticAllocas.empty()) {
749 // Also preserve the call graph, if applicable.
750 CallGraphNode *StartCGN = 0, *EndCGN = 0, *CallerNode = 0;
751 if (CallGraph *CG = IFI.CG) {
752 Function *Start = Intrinsic::getDeclaration(Caller->getParent(),
753 Intrinsic::lifetime_start);
754 Function *End = Intrinsic::getDeclaration(Caller->getParent(),
755 Intrinsic::lifetime_end);
756 StartCGN = CG->getOrInsertFunction(Start);
757 EndCGN = CG->getOrInsertFunction(End);
758 CallerNode = (*CG)[Caller];
759 }
760
761 IRBuilder<> builder(FirstNewBlock->begin());
762 for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
763 AllocaInst *AI = IFI.StaticAllocas[ai];
764
765 // If the alloca is already scoped to something smaller than the whole
766 // function then there's no need to add redundant, less accurate markers.
767 if (hasLifetimeMarkers(AI))
768 continue;
769
770 CallInst *StartCall = builder.CreateLifetimeStart(AI);
771 if (IFI.CG) CallerNode->addCalledFunction(StartCall, StartCGN);
772 for (unsigned ri = 0, re = Returns.size(); ri != re; ++ri) {
773 IRBuilder<> builder(Returns[ri]);
774 CallInst *EndCall = builder.CreateLifetimeEnd(AI);
775 if (IFI.CG) CallerNode->addCalledFunction(EndCall, EndCGN);
776 }
777 }
778 }
779
Chris Lattnerbf229f42006-01-13 19:34:14 +0000780 // If the inlined code contained dynamic alloca instructions, wrap the inlined
781 // code with llvm.stacksave/llvm.stackrestore intrinsics.
782 if (InlinedFunctionInfo.ContainsDynamicAllocas) {
783 Module *M = Caller->getParent();
Chris Lattnerbf229f42006-01-13 19:34:14 +0000784 // Get the two intrinsics we care about.
Chris Lattner6128df52009-10-17 05:39:39 +0000785 Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
786 Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
Chris Lattnerd85340f2006-07-12 18:29:36 +0000787
788 // If we are preserving the callgraph, add edges to the stacksave/restore
789 // functions for the calls we insert.
Chris Lattner21ba23d2006-07-18 21:48:57 +0000790 CallGraphNode *StackSaveCGN = 0, *StackRestoreCGN = 0, *CallerNode = 0;
Chris Lattner60915142010-04-22 23:07:58 +0000791 if (CallGraph *CG = IFI.CG) {
Chris Lattner6128df52009-10-17 05:39:39 +0000792 StackSaveCGN = CG->getOrInsertFunction(StackSave);
793 StackRestoreCGN = CG->getOrInsertFunction(StackRestore);
Chris Lattnerd85340f2006-07-12 18:29:36 +0000794 CallerNode = (*CG)[Caller];
795 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000796
Chris Lattnerbf229f42006-01-13 19:34:14 +0000797 // Insert the llvm.stacksave.
Duncan Sandsa7212e52008-09-05 12:37:12 +0000798 CallInst *SavedPtr = CallInst::Create(StackSave, "savedstack",
Gabor Greif051a9502008-04-06 20:25:17 +0000799 FirstNewBlock->begin());
Chris Lattner60915142010-04-22 23:07:58 +0000800 if (IFI.CG) CallerNode->addCalledFunction(SavedPtr, StackSaveCGN);
Duncan Sandsa7212e52008-09-05 12:37:12 +0000801
Chris Lattnerbf229f42006-01-13 19:34:14 +0000802 // Insert a call to llvm.stackrestore before any return instructions in the
803 // inlined function.
Chris Lattnerd85340f2006-07-12 18:29:36 +0000804 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
Gabor Greif051a9502008-04-06 20:25:17 +0000805 CallInst *CI = CallInst::Create(StackRestore, SavedPtr, "", Returns[i]);
Chris Lattner60915142010-04-22 23:07:58 +0000806 if (IFI.CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
Chris Lattnerd85340f2006-07-12 18:29:36 +0000807 }
Chris Lattner468fb1d2006-01-14 20:07:50 +0000808
809 // Count the number of StackRestore calls we insert.
810 unsigned NumStackRestores = Returns.size();
Duncan Sandsa7212e52008-09-05 12:37:12 +0000811
Chris Lattnerbf229f42006-01-13 19:34:14 +0000812 // If we are inlining an invoke instruction, insert restores before each
813 // unwind. These unwinds will be rewritten into branches later.
814 if (InlinedFunctionInfo.ContainsUnwinds && isa<InvokeInst>(TheCall)) {
815 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
816 BB != E; ++BB)
Chris Lattner468fb1d2006-01-14 20:07:50 +0000817 if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
Chris Lattner6128df52009-10-17 05:39:39 +0000818 CallInst *CI = CallInst::Create(StackRestore, SavedPtr, "", UI);
Chris Lattner60915142010-04-22 23:07:58 +0000819 if (IFI.CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
Chris Lattner468fb1d2006-01-14 20:07:50 +0000820 ++NumStackRestores;
821 }
822 }
Chris Lattnerbf229f42006-01-13 19:34:14 +0000823 }
824
Duncan Sandsa7212e52008-09-05 12:37:12 +0000825 // If we are inlining tail call instruction through a call site that isn't
Chris Lattner1fdf4a82006-01-13 19:18:11 +0000826 // marked 'tail', we must remove the tail marker for any calls in the inlined
Duncan Sandsf0c33542007-12-19 21:13:37 +0000827 // code. Also, calls inlined through a 'nounwind' call site should be marked
828 // 'nounwind'.
829 if (InlinedFunctionInfo.ContainsCalls &&
830 (MustClearTailCallFlags || MarkNoUnwind)) {
Chris Lattner1b491412005-05-06 06:47:52 +0000831 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
832 BB != E; ++BB)
833 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Duncan Sandsf0c33542007-12-19 21:13:37 +0000834 if (CallInst *CI = dyn_cast<CallInst>(I)) {
835 if (MustClearTailCallFlags)
836 CI->setTailCall(false);
837 if (MarkNoUnwind)
838 CI->setDoesNotThrow();
839 }
Chris Lattner1b491412005-05-06 06:47:52 +0000840 }
841
Duncan Sandsf0c33542007-12-19 21:13:37 +0000842 // If we are inlining through a 'nounwind' call site then any inlined 'unwind'
843 // instructions are unreachable.
844 if (InlinedFunctionInfo.ContainsUnwinds && MarkNoUnwind)
845 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
846 BB != E; ++BB) {
847 TerminatorInst *Term = BB->getTerminator();
848 if (isa<UnwindInst>(Term)) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000849 new UnreachableInst(Context, Term);
Duncan Sandsf0c33542007-12-19 21:13:37 +0000850 BB->getInstList().erase(Term);
851 }
852 }
853
Chris Lattner5e923de2004-02-04 02:51:48 +0000854 // If we are inlining for an invoke instruction, we must make sure to rewrite
855 // any inlined 'unwind' instructions into branches to the invoke exception
856 // destination, and call instructions into invoke instructions.
Chris Lattnercd4d3392006-01-13 19:05:59 +0000857 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
Chris Lattner81dfb382009-09-01 18:44:06 +0000858 HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
Chris Lattner5e923de2004-02-04 02:51:48 +0000859
Chris Lattner44a68072004-02-04 04:17:06 +0000860 // If we cloned in _exactly one_ basic block, and if that block ends in a
861 // return instruction, we splice the body of the inlined callee directly into
862 // the calling basic block.
863 if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
864 // Move all of the instructions right before the call.
865 OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
866 FirstNewBlock->begin(), FirstNewBlock->end());
867 // Remove the cloned basic block.
868 Caller->getBasicBlockList().pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +0000869
Chris Lattner44a68072004-02-04 04:17:06 +0000870 // If the call site was an invoke instruction, add a branch to the normal
871 // destination.
872 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
Gabor Greif051a9502008-04-06 20:25:17 +0000873 BranchInst::Create(II->getNormalDest(), TheCall);
Chris Lattner44a68072004-02-04 04:17:06 +0000874
875 // If the return instruction returned a value, replace uses of the call with
876 // uses of the returned value.
Devang Pateldc00d422008-03-04 21:15:15 +0000877 if (!TheCall->use_empty()) {
878 ReturnInst *R = Returns[0];
Eli Friedman5877ad72009-05-08 00:22:04 +0000879 if (TheCall == R->getReturnValue())
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000880 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Eli Friedman5877ad72009-05-08 00:22:04 +0000881 else
882 TheCall->replaceAllUsesWith(R->getReturnValue());
Devang Pateldc00d422008-03-04 21:15:15 +0000883 }
Chris Lattner44a68072004-02-04 04:17:06 +0000884 // Since we are now done with the Call/Invoke, we can delete it.
Dan Gohman1adec832008-06-21 22:08:46 +0000885 TheCall->eraseFromParent();
Chris Lattner44a68072004-02-04 04:17:06 +0000886
887 // Since we are now done with the return instruction, delete it also.
Dan Gohman1adec832008-06-21 22:08:46 +0000888 Returns[0]->eraseFromParent();
Chris Lattner44a68072004-02-04 04:17:06 +0000889
890 // We are now done with the inlining.
891 return true;
892 }
893
894 // Otherwise, we have the normal case, of more than one block to inline or
895 // multiple return sites.
896
Chris Lattner5e923de2004-02-04 02:51:48 +0000897 // We want to clone the entire callee function into the hole between the
898 // "starter" and "ender" blocks. How we accomplish this depends on whether
899 // this is an invoke instruction or a call instruction.
900 BasicBlock *AfterCallBB;
901 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
Misha Brukmanfd939082005-04-21 23:48:37 +0000902
Chris Lattner5e923de2004-02-04 02:51:48 +0000903 // Add an unconditional branch to make this look like the CallInst case...
Gabor Greif051a9502008-04-06 20:25:17 +0000904 BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
Misha Brukmanfd939082005-04-21 23:48:37 +0000905
Chris Lattner5e923de2004-02-04 02:51:48 +0000906 // Split the basic block. This guarantees that no PHI nodes will have to be
907 // updated due to new incoming edges, and make the invoke case more
908 // symmetric to the call case.
909 AfterCallBB = OrigBB->splitBasicBlock(NewBr,
Chris Lattner284d1b82004-12-11 16:59:54 +0000910 CalledFunc->getName()+".exit");
Misha Brukmanfd939082005-04-21 23:48:37 +0000911
Chris Lattner5e923de2004-02-04 02:51:48 +0000912 } else { // It's a call
Chris Lattner44a68072004-02-04 04:17:06 +0000913 // If this is a call instruction, we need to split the basic block that
914 // the call lives in.
Chris Lattner5e923de2004-02-04 02:51:48 +0000915 //
916 AfterCallBB = OrigBB->splitBasicBlock(TheCall,
Chris Lattner284d1b82004-12-11 16:59:54 +0000917 CalledFunc->getName()+".exit");
Chris Lattner5e923de2004-02-04 02:51:48 +0000918 }
919
Chris Lattner44a68072004-02-04 04:17:06 +0000920 // Change the branch that used to go to AfterCallBB to branch to the first
921 // basic block of the inlined function.
922 //
923 TerminatorInst *Br = OrigBB->getTerminator();
Misha Brukmanfd939082005-04-21 23:48:37 +0000924 assert(Br && Br->getOpcode() == Instruction::Br &&
Chris Lattner44a68072004-02-04 04:17:06 +0000925 "splitBasicBlock broken!");
926 Br->setOperand(0, FirstNewBlock);
927
928
929 // Now that the function is correct, make it a little bit nicer. In
930 // particular, move the basic blocks inserted from the end of the function
931 // into the space made by splitting the source basic block.
Chris Lattner44a68072004-02-04 04:17:06 +0000932 Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
933 FirstNewBlock, Caller->end());
934
Chris Lattner5e923de2004-02-04 02:51:48 +0000935 // Handle all of the return instructions that we just cloned in, and eliminate
936 // any users of the original call/invoke instruction.
Devang Patelb8f198a2008-03-10 18:34:00 +0000937 const Type *RTy = CalledFunc->getReturnType();
Dan Gohman2c317502008-06-20 01:03:44 +0000938
Duncan Sands6fb881c2010-11-17 11:16:23 +0000939 PHINode *PHI = 0;
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000940 if (Returns.size() > 1) {
Chris Lattner5e923de2004-02-04 02:51:48 +0000941 // The PHI node should go at the front of the new basic block to merge all
942 // possible incoming values.
Chris Lattner5e923de2004-02-04 02:51:48 +0000943 if (!TheCall->use_empty()) {
Jay Foad3ecfc862011-03-30 11:28:46 +0000944 PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000945 AfterCallBB->begin());
946 // Anything that used the result of the function call should now use the
947 // PHI node as their operand.
Duncan Sandsa7212e52008-09-05 12:37:12 +0000948 TheCall->replaceAllUsesWith(PHI);
Chris Lattner5e923de2004-02-04 02:51:48 +0000949 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000950
Gabor Greifc478e522009-01-15 18:40:09 +0000951 // Loop over all of the return instructions adding entries to the PHI node
952 // as appropriate.
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000953 if (PHI) {
954 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
955 ReturnInst *RI = Returns[i];
956 assert(RI->getReturnValue()->getType() == PHI->getType() &&
957 "Ret value not consistent in function!");
958 PHI->addIncoming(RI->getReturnValue(), RI->getParent());
Devang Patel12a466b2008-03-07 20:06:16 +0000959 }
960 }
961
Chris Lattnerc581acb2009-10-27 05:39:41 +0000962
Gabor Greifde62aea2009-01-16 23:08:50 +0000963 // Add a branch to the merge points and remove return instructions.
Chris Lattner5e923de2004-02-04 02:51:48 +0000964 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
965 ReturnInst *RI = Returns[i];
Dale Johannesen0744f092009-03-04 02:09:48 +0000966 BranchInst::Create(AfterCallBB, RI);
Devang Patelb8f198a2008-03-10 18:34:00 +0000967 RI->eraseFromParent();
Chris Lattner5e923de2004-02-04 02:51:48 +0000968 }
Devang Patelb8f198a2008-03-10 18:34:00 +0000969 } else if (!Returns.empty()) {
970 // Otherwise, if there is exactly one return value, just replace anything
971 // using the return value of the call with the computed value.
Eli Friedman5877ad72009-05-08 00:22:04 +0000972 if (!TheCall->use_empty()) {
973 if (TheCall == Returns[0]->getReturnValue())
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000974 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Eli Friedman5877ad72009-05-08 00:22:04 +0000975 else
976 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
977 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000978
Devang Patelb8f198a2008-03-10 18:34:00 +0000979 // Splice the code from the return block into the block that it will return
980 // to, which contains the code that was after the call.
981 BasicBlock *ReturnBB = Returns[0]->getParent();
982 AfterCallBB->getInstList().splice(AfterCallBB->begin(),
983 ReturnBB->getInstList());
Duncan Sandsa7212e52008-09-05 12:37:12 +0000984
Devang Patelb8f198a2008-03-10 18:34:00 +0000985 // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
986 ReturnBB->replaceAllUsesWith(AfterCallBB);
Duncan Sandsa7212e52008-09-05 12:37:12 +0000987
Devang Patelb8f198a2008-03-10 18:34:00 +0000988 // Delete the return instruction now and empty ReturnBB now.
989 Returns[0]->eraseFromParent();
990 ReturnBB->eraseFromParent();
Chris Lattner3787e762004-10-17 23:21:07 +0000991 } else if (!TheCall->use_empty()) {
992 // No returns, but something is using the return value of the call. Just
993 // nuke the result.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000994 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Chris Lattner5e923de2004-02-04 02:51:48 +0000995 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000996
Chris Lattner5e923de2004-02-04 02:51:48 +0000997 // Since we are now done with the Call/Invoke, we can delete it.
Chris Lattner3787e762004-10-17 23:21:07 +0000998 TheCall->eraseFromParent();
Chris Lattnerca398dc2003-05-29 15:11:31 +0000999
Chris Lattner7152c232003-08-24 04:06:56 +00001000 // We should always be able to fold the entry block of the function into the
1001 // single predecessor of the block...
Chris Lattnercd01ae52004-04-16 05:17:59 +00001002 assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
Chris Lattner7152c232003-08-24 04:06:56 +00001003 BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
Chris Lattner44a68072004-02-04 04:17:06 +00001004
Chris Lattnercd01ae52004-04-16 05:17:59 +00001005 // Splice the code entry block into calling block, right before the
1006 // unconditional branch.
1007 OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
1008 CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
1009
1010 // Remove the unconditional branch.
1011 OrigBB->getInstList().erase(Br);
1012
1013 // Now we can remove the CalleeEntry block, which is now empty.
1014 Caller->getBasicBlockList().erase(CalleeEntry);
Duncan Sandsa7212e52008-09-05 12:37:12 +00001015
Duncan Sands6fb881c2010-11-17 11:16:23 +00001016 // If we inserted a phi node, check to see if it has a single value (e.g. all
1017 // the entries are the same or undef). If so, remove the PHI so it doesn't
1018 // block other optimizations.
1019 if (PHI)
1020 if (Value *V = SimplifyInstruction(PHI, IFI.TD)) {
1021 PHI->replaceAllUsesWith(V);
1022 PHI->eraseFromParent();
1023 }
1024
Chris Lattnerca398dc2003-05-29 15:11:31 +00001025 return true;
1026}