blob: d2fd07aed10cbebdf01fb7a8e2374c544ae6450d [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) {
217 Function *fn = dyn_cast<Function>(call->getCalledValue());
218 if (!fn || fn->getName() != "llvm.eh.resume")
219 return false;
220
221 // If this fails, maybe it should be a fatal error.
222 BasicBlock *dest = getInnerUnwindDest();
223 if (!dest) return false;
224
225 // Make a branch.
226 BranchInst::Create(dest, src);
227
228 // Update the phis in the destination. They were inserted in an
229 // order which makes this work.
230 addIncomingPHIValuesForInto(src, dest);
231 InnerExceptionPHI->addIncoming(call->getArgOperand(0), src);
232 InnerSelectorPHI->addIncoming(call->getArgOperand(1), src);
233
234 return true;
John McCalla3de16b2011-05-27 18:34:38 +0000235}
236
237/// [LIBUNWIND] Check whether this selector is "only cleanups":
238/// call i32 @llvm.eh.selector(blah, blah, i32 0)
239static bool isCleanupOnlySelector(EHSelectorInst *selector) {
240 if (selector->getNumArgOperands() != 3) return false;
241 ConstantInt *val = dyn_cast<ConstantInt>(selector->getArgOperand(2));
242 return (val && val->isZero());
243}
Chris Lattner135755d2009-08-27 03:51:50 +0000244
245/// HandleCallsInBlockInlinedThroughInvoke - When we inline a basic block into
Eric Christopherf61f89a2009-09-06 22:20:54 +0000246/// an invoke, we have to turn all of the calls that can throw into
Chris Lattner135755d2009-08-27 03:51:50 +0000247/// invokes. This function analyze BB to see if there are any calls, and if so,
248/// it rewrites them to be invokes that jump to InvokeDest and fills in the PHI
Chris Lattner81dfb382009-09-01 18:44:06 +0000249/// nodes in that block with the values specified in InvokeDestPHIValues.
Chris Lattner135755d2009-08-27 03:51:50 +0000250///
John McCalla3de16b2011-05-27 18:34:38 +0000251/// Returns true to indicate that the next block should be skipped.
252static bool HandleCallsInBlockInlinedThroughInvoke(BasicBlock *BB,
253 InvokeInliningInfo &Invoke) {
Chris Lattner135755d2009-08-27 03:51:50 +0000254 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
255 Instruction *I = BBI++;
256
257 // We only need to check for function calls: inlined invoke
258 // instructions require no special handling.
259 CallInst *CI = dyn_cast<CallInst>(I);
260 if (CI == 0) continue;
John McCalla3de16b2011-05-27 18:34:38 +0000261
262 // LIBUNWIND: merge selector instructions.
263 if (EHSelectorInst *Inner = dyn_cast<EHSelectorInst>(CI)) {
John McCalld7c10862011-05-28 07:45:59 +0000264 EHSelectorInst *Outer = Invoke.getOuterSelector();
John McCalla3de16b2011-05-27 18:34:38 +0000265 if (!Outer) continue;
266
267 bool innerIsOnlyCleanup = isCleanupOnlySelector(Inner);
268 bool outerIsOnlyCleanup = isCleanupOnlySelector(Outer);
269
270 // If both selectors contain only cleanups, we don't need to do
271 // anything. TODO: this is really just a very specific instance
272 // of a much more general optimization.
273 if (innerIsOnlyCleanup && outerIsOnlyCleanup) continue;
274
275 // Otherwise, we just append the outer selector to the inner selector.
276 SmallVector<Value*, 16> NewSelector;
277 for (unsigned i = 0, e = Inner->getNumArgOperands(); i != e; ++i)
278 NewSelector.push_back(Inner->getArgOperand(i));
279 for (unsigned i = 2, e = Outer->getNumArgOperands(); i != e; ++i)
280 NewSelector.push_back(Outer->getArgOperand(i));
281
282 CallInst *NewInner = CallInst::Create(Inner->getCalledValue(),
283 NewSelector.begin(),
284 NewSelector.end(),
285 "",
286 Inner);
287 // No need to copy attributes, calling convention, etc.
288 NewInner->takeName(Inner);
289 Inner->replaceAllUsesWith(NewInner);
290 Inner->eraseFromParent();
291 continue;
292 }
Chris Lattner135755d2009-08-27 03:51:50 +0000293
294 // If this call cannot unwind, don't convert it to an invoke.
295 if (CI->doesNotThrow())
296 continue;
297
298 // Convert this function call into an invoke instruction.
299 // First, split the basic block.
300 BasicBlock *Split = BB->splitBasicBlock(CI, CI->getName()+".noexc");
John McCalla3de16b2011-05-27 18:34:38 +0000301
John McCalld7c10862011-05-28 07:45:59 +0000302 // Delete the unconditional branch inserted by splitBasicBlock
303 BB->getInstList().pop_back();
John McCalla3de16b2011-05-27 18:34:38 +0000304
John McCalld7c10862011-05-28 07:45:59 +0000305 // LIBUNWIND: If this is a call to @llvm.eh.resume, just branch
John McCalla3de16b2011-05-27 18:34:38 +0000306 // directly to the new landing pad.
John McCalld7c10862011-05-28 07:45:59 +0000307 if (Invoke.forwardEHResume(CI, BB)) {
John McCalla3de16b2011-05-27 18:34:38 +0000308 // TODO: 'Split' is now unreachable; clean it up.
309
310 // We want to leave the original call intact so that the call
311 // graph and other structures won't get misled. We also have to
312 // avoid processing the next block, or we'll iterate here forever.
John McCalld7c10862011-05-28 07:45:59 +0000313 return true;
314 }
John McCalla3de16b2011-05-27 18:34:38 +0000315
316 // Otherwise, create the new invoke instruction.
John McCalld7c10862011-05-28 07:45:59 +0000317 ImmutableCallSite CS(CI);
318 SmallVector<Value*, 8> InvokeArgs(CS.arg_begin(), CS.arg_end());
319 InvokeInst *II =
320 InvokeInst::Create(CI->getCalledValue(), Split,
321 Invoke.getOuterUnwindDest(),
322 InvokeArgs.begin(), InvokeArgs.end(),
323 CI->getName(), BB);
324 II->setCallingConv(CI->getCallingConv());
325 II->setAttributes(CI->getAttributes());
Chris Lattner135755d2009-08-27 03:51:50 +0000326
John McCalld7c10862011-05-28 07:45:59 +0000327 // Make sure that anything using the call now uses the invoke! This also
328 // updates the CallGraph if present, because it uses a WeakVH.
329 CI->replaceAllUsesWith(II);
John McCalla3de16b2011-05-27 18:34:38 +0000330
John McCalld7c10862011-05-28 07:45:59 +0000331 Split->getInstList().pop_front(); // Delete the original call
332
Chris Lattner135755d2009-08-27 03:51:50 +0000333 // Update any PHI nodes in the exceptional block to indicate that
334 // there is now a new entry in them.
John McCalla3de16b2011-05-27 18:34:38 +0000335 Invoke.addIncomingPHIValuesFor(BB);
John McCalld7c10862011-05-28 07:45:59 +0000336 return false;
Chris Lattner135755d2009-08-27 03:51:50 +0000337 }
John McCalla3de16b2011-05-27 18:34:38 +0000338
339 return false;
Chris Lattner135755d2009-08-27 03:51:50 +0000340}
341
342
Chris Lattnercd4d3392006-01-13 19:05:59 +0000343/// HandleInlinedInvoke - If we inlined an invoke site, we need to convert calls
344/// in the body of the inlined function into invokes and turn unwind
345/// instructions into branches to the invoke unwind dest.
346///
Nick Lewyckydac5c4b2009-02-03 04:34:40 +0000347/// II is the invoke instruction being inlined. FirstNewBlock is the first
Chris Lattnercd4d3392006-01-13 19:05:59 +0000348/// block of the inlined code (the last block is the end of the function),
349/// and InlineCodeInfo is information about the code that got inlined.
350static void HandleInlinedInvoke(InvokeInst *II, BasicBlock *FirstNewBlock,
Chris Lattner81dfb382009-09-01 18:44:06 +0000351 ClonedCodeInfo &InlinedCodeInfo) {
Chris Lattnercd4d3392006-01-13 19:05:59 +0000352 BasicBlock *InvokeDest = II->getUnwindDest();
Chris Lattnercd4d3392006-01-13 19:05:59 +0000353
354 Function *Caller = FirstNewBlock->getParent();
Duncan Sandsa7212e52008-09-05 12:37:12 +0000355
Chris Lattnercd4d3392006-01-13 19:05:59 +0000356 // The inlined code is currently at the end of the function, scan from the
357 // start of the inlined code to its end, checking for stuff we need to
Chris Lattner135755d2009-08-27 03:51:50 +0000358 // rewrite. If the code doesn't have calls or unwinds, we know there is
359 // nothing to rewrite.
360 if (!InlinedCodeInfo.ContainsCalls && !InlinedCodeInfo.ContainsUnwinds) {
361 // Now that everything is happy, we have one final detail. The PHI nodes in
362 // the exception destination block still have entries due to the original
363 // invoke instruction. Eliminate these entries (which might even delete the
364 // PHI node) now.
365 InvokeDest->removePredecessor(II->getParent());
366 return;
367 }
John McCalla3de16b2011-05-27 18:34:38 +0000368
369 InvokeInliningInfo Invoke(II);
Chris Lattner135755d2009-08-27 03:51:50 +0000370
Chris Lattner135755d2009-08-27 03:51:50 +0000371 for (Function::iterator BB = FirstNewBlock, E = Caller->end(); BB != E; ++BB){
372 if (InlinedCodeInfo.ContainsCalls)
John McCalla3de16b2011-05-27 18:34:38 +0000373 if (HandleCallsInBlockInlinedThroughInvoke(BB, Invoke)) {
374 // Honor a request to skip the next block. We don't need to
375 // consider UnwindInsts in this case either.
376 ++BB;
377 continue;
378 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000379
Chris Lattner135755d2009-08-27 03:51:50 +0000380 if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
381 // An UnwindInst requires special handling when it gets inlined into an
382 // invoke site. Once this happens, we know that the unwind would cause
383 // a control transfer to the invoke exception destination, so we can
384 // transform it into a direct branch to the exception destination.
385 BranchInst::Create(InvokeDest, UI);
Chris Lattnercd4d3392006-01-13 19:05:59 +0000386
Chris Lattner135755d2009-08-27 03:51:50 +0000387 // Delete the unwind instruction!
388 UI->eraseFromParent();
Duncan Sandsa3355ff2007-12-03 20:06:50 +0000389
Chris Lattner135755d2009-08-27 03:51:50 +0000390 // Update any PHI nodes in the exceptional block to indicate that
391 // there is now a new entry in them.
John McCalla3de16b2011-05-27 18:34:38 +0000392 Invoke.addIncomingPHIValuesFor(BB);
Chris Lattnercd4d3392006-01-13 19:05:59 +0000393 }
394 }
395
396 // Now that everything is happy, we have one final detail. The PHI nodes in
397 // the exception destination block still have entries due to the original
398 // invoke instruction. Eliminate these entries (which might even delete the
399 // PHI node) now.
400 InvokeDest->removePredecessor(II->getParent());
401}
402
Chris Lattnerd85340f2006-07-12 18:29:36 +0000403/// UpdateCallGraphAfterInlining - Once we have cloned code over from a callee
404/// into the caller, update the specified callgraph to reflect the changes we
405/// made. Note that it's possible that not all code was copied over, so only
Duncan Sandsd7b98512008-09-08 11:05:51 +0000406/// some edges of the callgraph may remain.
407static void UpdateCallGraphAfterInlining(CallSite CS,
Chris Lattnerd85340f2006-07-12 18:29:36 +0000408 Function::iterator FirstNewBlock,
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000409 ValueToValueMapTy &VMap,
Chris Lattnerfe9af3b2010-04-22 23:37:35 +0000410 InlineFunctionInfo &IFI) {
411 CallGraph &CG = *IFI.CG;
Duncan Sandsd7b98512008-09-08 11:05:51 +0000412 const Function *Caller = CS.getInstruction()->getParent()->getParent();
413 const Function *Callee = CS.getCalledFunction();
Chris Lattner468fb1d2006-01-14 20:07:50 +0000414 CallGraphNode *CalleeNode = CG[Callee];
415 CallGraphNode *CallerNode = CG[Caller];
Duncan Sandsa7212e52008-09-05 12:37:12 +0000416
Chris Lattnerd85340f2006-07-12 18:29:36 +0000417 // Since we inlined some uninlined call sites in the callee into the caller,
Chris Lattner468fb1d2006-01-14 20:07:50 +0000418 // add edges from the caller to all of the callees of the callee.
Gabor Greifc478e522009-01-15 18:40:09 +0000419 CallGraphNode::iterator I = CalleeNode->begin(), E = CalleeNode->end();
420
421 // Consider the case where CalleeNode == CallerNode.
Gabor Greif12532982009-01-17 00:09:08 +0000422 CallGraphNode::CalledFunctionsVector CallCache;
Gabor Greifc478e522009-01-15 18:40:09 +0000423 if (CalleeNode == CallerNode) {
424 CallCache.assign(I, E);
425 I = CallCache.begin();
426 E = CallCache.end();
427 }
428
429 for (; I != E; ++I) {
Chris Lattnera541b0f2009-09-01 06:31:31 +0000430 const Value *OrigCall = I->first;
Duncan Sandsa7212e52008-09-05 12:37:12 +0000431
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000432 ValueToValueMapTy::iterator VMI = VMap.find(OrigCall);
Chris Lattner981418b2006-07-12 21:37:11 +0000433 // Only copy the edge if the call was inlined!
Devang Patel29d3dd82010-06-23 23:55:51 +0000434 if (VMI == VMap.end() || VMI->second == 0)
Chris Lattner135755d2009-08-27 03:51:50 +0000435 continue;
436
437 // If the call was inlined, but then constant folded, there is no edge to
438 // add. Check for this case.
Chris Lattnerb957a5e2010-04-22 21:31:00 +0000439 Instruction *NewCall = dyn_cast<Instruction>(VMI->second);
440 if (NewCall == 0) continue;
Chris Lattner0ca2f282010-05-01 01:26:13 +0000441
442 // Remember that this call site got inlined for the client of
443 // InlineFunction.
444 IFI.InlinedCalls.push_back(NewCall);
445
Chris Lattnerb957a5e2010-04-22 21:31:00 +0000446 // It's possible that inlining the callsite will cause it to go from an
447 // indirect to a direct call by resolving a function pointer. If this
448 // happens, set the callee of the new call site to a more precise
449 // destination. This can also happen if the call graph node of the caller
450 // was just unnecessarily imprecise.
451 if (I->second->getFunction() == 0)
452 if (Function *F = CallSite(NewCall).getCalledFunction()) {
453 // Indirect call site resolved to direct call.
Gabor Greif86099342010-07-27 15:02:37 +0000454 CallerNode->addCalledFunction(CallSite(NewCall), CG[F]);
455
Chris Lattnerb957a5e2010-04-22 21:31:00 +0000456 continue;
457 }
Gabor Greif86099342010-07-27 15:02:37 +0000458
459 CallerNode->addCalledFunction(CallSite(NewCall), I->second);
Chris Lattnerd85340f2006-07-12 18:29:36 +0000460 }
Chris Lattner135755d2009-08-27 03:51:50 +0000461
Dale Johannesen39fa3242009-01-13 22:43:37 +0000462 // Update the call graph by deleting the edge from Callee to Caller. We must
463 // do this after the loop above in case Caller and Callee are the same.
464 CallerNode->removeCallEdgeFor(CS);
Chris Lattner468fb1d2006-01-14 20:07:50 +0000465}
466
Chris Lattner0b66f632010-12-20 08:10:40 +0000467/// HandleByValArgument - When inlining a call site that has a byval argument,
468/// we have to make the implicit memcpy explicit by adding it.
Chris Lattnere7ae7052010-12-20 07:57:41 +0000469static Value *HandleByValArgument(Value *Arg, Instruction *TheCall,
470 const Function *CalledFunc,
471 InlineFunctionInfo &IFI,
472 unsigned ByValAlignment) {
Chris Lattner0b66f632010-12-20 08:10:40 +0000473 const Type *AggTy = cast<PointerType>(Arg->getType())->getElementType();
474
475 // If the called function is readonly, then it could not mutate the caller's
476 // copy of the byval'd memory. In this case, it is safe to elide the copy and
477 // temporary.
478 if (CalledFunc->onlyReadsMemory()) {
479 // If the byval argument has a specified alignment that is greater than the
480 // passed in pointer, then we either have to round up the input pointer or
481 // give up on this transformation.
482 if (ByValAlignment <= 1) // 0 = unspecified, 1 = no particular alignment.
483 return Arg;
484
Chris Lattner7569d792010-12-25 20:42:38 +0000485 // If the pointer is already known to be sufficiently aligned, or if we can
486 // round it up to a larger alignment, then we don't need a temporary.
487 if (getOrEnforceKnownAlignment(Arg, ByValAlignment,
488 IFI.TD) >= ByValAlignment)
489 return Arg;
Chris Lattner0b66f632010-12-20 08:10:40 +0000490
Chris Lattner7569d792010-12-25 20:42:38 +0000491 // Otherwise, we have to make a memcpy to get a safe alignment. This is bad
492 // for code quality, but rarely happens and is required for correctness.
Chris Lattner0b66f632010-12-20 08:10:40 +0000493 }
Chris Lattnere7ae7052010-12-20 07:57:41 +0000494
495 LLVMContext &Context = Arg->getContext();
496
Chris Lattnere7ae7052010-12-20 07:57:41 +0000497 const Type *VoidPtrTy = Type::getInt8PtrTy(Context);
498
499 // Create the alloca. If we have TargetData, use nice alignment.
500 unsigned Align = 1;
501 if (IFI.TD)
502 Align = IFI.TD->getPrefTypeAlignment(AggTy);
503
504 // If the byval had an alignment specified, we *must* use at least that
505 // alignment, as it is required by the byval argument (and uses of the
506 // pointer inside the callee).
507 Align = std::max(Align, ByValAlignment);
508
509 Function *Caller = TheCall->getParent()->getParent();
510
511 Value *NewAlloca = new AllocaInst(AggTy, 0, Align, Arg->getName(),
512 &*Caller->begin()->begin());
513 // Emit a memcpy.
514 const Type *Tys[3] = {VoidPtrTy, VoidPtrTy, Type::getInt64Ty(Context)};
515 Function *MemCpyFn = Intrinsic::getDeclaration(Caller->getParent(),
516 Intrinsic::memcpy,
517 Tys, 3);
518 Value *DestCast = new BitCastInst(NewAlloca, VoidPtrTy, "tmp", TheCall);
519 Value *SrcCast = new BitCastInst(Arg, VoidPtrTy, "tmp", TheCall);
520
521 Value *Size;
522 if (IFI.TD == 0)
523 Size = ConstantExpr::getSizeOf(AggTy);
524 else
525 Size = ConstantInt::get(Type::getInt64Ty(Context),
526 IFI.TD->getTypeStoreSize(AggTy));
527
528 // Always generate a memcpy of alignment 1 here because we don't know
529 // the alignment of the src pointer. Other optimizations can infer
530 // better alignment.
531 Value *CallArgs[] = {
532 DestCast, SrcCast, Size,
533 ConstantInt::get(Type::getInt32Ty(Context), 1),
534 ConstantInt::getFalse(Context) // isVolatile
535 };
536 CallInst *TheMemCpy =
537 CallInst::Create(MemCpyFn, CallArgs, CallArgs+5, "", TheCall);
538
539 // If we have a call graph, update it.
540 if (CallGraph *CG = IFI.CG) {
541 CallGraphNode *MemCpyCGN = CG->getOrInsertFunction(MemCpyFn);
542 CallGraphNode *CallerNode = (*CG)[Caller];
543 CallerNode->addCalledFunction(TheMemCpy, MemCpyCGN);
544 }
545
546 // Uses of the argument in the function should use our new alloca
547 // instead.
548 return NewAlloca;
549}
550
Nick Lewycky6d55f222011-05-22 05:22:10 +0000551// isUsedByLifetimeMarker - Check whether this Value is used by a lifetime
552// intrinsic.
553static bool isUsedByLifetimeMarker(Value *V) {
554 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end(); UI != UE;
555 ++UI) {
556 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*UI)) {
557 switch (II->getIntrinsicID()) {
558 default: break;
559 case Intrinsic::lifetime_start:
560 case Intrinsic::lifetime_end:
561 return true;
562 }
563 }
564 }
565 return false;
566}
567
568// hasLifetimeMarkers - Check whether the given alloca already has
569// lifetime.start or lifetime.end intrinsics.
570static bool hasLifetimeMarkers(AllocaInst *AI) {
571 const Type *Int8PtrTy = Type::getInt8PtrTy(AI->getType()->getContext());
572 if (AI->getType() == Int8PtrTy)
573 return isUsedByLifetimeMarker(AI);
574
575 // Do a scan to find all the bitcasts to i8*.
576 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end(); I != E;
577 ++I) {
578 if (I->getType() != Int8PtrTy) continue;
579 if (!isa<BitCastInst>(*I)) continue;
580 if (isUsedByLifetimeMarker(*I))
581 return true;
582 }
583 return false;
584}
585
Chris Lattnerca398dc2003-05-29 15:11:31 +0000586// InlineFunction - This function inlines the called function into the basic
587// block of the caller. This returns false if it is not possible to inline this
588// call. The program is still in a well defined state if this occurs though.
589//
Misha Brukmanfd939082005-04-21 23:48:37 +0000590// Note that this only does one level of inlining. For example, if the
591// instruction 'call B' is inlined, and 'B' calls 'C', then the call to 'C' now
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000592// exists in the instruction stream. Similarly this will inline a recursive
Chris Lattnerca398dc2003-05-29 15:11:31 +0000593// function by one level.
594//
Chris Lattner60915142010-04-22 23:07:58 +0000595bool llvm::InlineFunction(CallSite CS, InlineFunctionInfo &IFI) {
Chris Lattner80a38d22003-08-24 06:59:16 +0000596 Instruction *TheCall = CS.getInstruction();
Owen Andersone922c022009-07-22 00:24:57 +0000597 LLVMContext &Context = TheCall->getContext();
Chris Lattner80a38d22003-08-24 06:59:16 +0000598 assert(TheCall->getParent() && TheCall->getParent()->getParent() &&
599 "Instruction not in function!");
Chris Lattnerca398dc2003-05-29 15:11:31 +0000600
Chris Lattner60915142010-04-22 23:07:58 +0000601 // If IFI has any state in it, zap it before we fill it in.
602 IFI.reset();
603
Chris Lattner80a38d22003-08-24 06:59:16 +0000604 const Function *CalledFunc = CS.getCalledFunction();
Chris Lattnerca398dc2003-05-29 15:11:31 +0000605 if (CalledFunc == 0 || // Can't inline external function or indirect
Reid Spencer5cbf9852007-01-30 20:08:39 +0000606 CalledFunc->isDeclaration() || // call, or call to a vararg function!
Eric Christopher0623e902010-03-24 23:35:21 +0000607 CalledFunc->getFunctionType()->isVarArg()) return false;
Chris Lattnerca398dc2003-05-29 15:11:31 +0000608
Chris Lattneraf9985c2009-02-12 07:06:42 +0000609 // If the call to the callee is not a tail call, we must clear the 'tail'
Chris Lattner1b491412005-05-06 06:47:52 +0000610 // flags on any calls that we inline.
611 bool MustClearTailCallFlags =
Chris Lattneraf9985c2009-02-12 07:06:42 +0000612 !(isa<CallInst>(TheCall) && cast<CallInst>(TheCall)->isTailCall());
Chris Lattner1b491412005-05-06 06:47:52 +0000613
Duncan Sandsf0c33542007-12-19 21:13:37 +0000614 // If the call to the callee cannot throw, set the 'nounwind' flag on any
615 // calls that we inline.
616 bool MarkNoUnwind = CS.doesNotThrow();
617
Chris Lattner80a38d22003-08-24 06:59:16 +0000618 BasicBlock *OrigBB = TheCall->getParent();
Chris Lattnerca398dc2003-05-29 15:11:31 +0000619 Function *Caller = OrigBB->getParent();
620
Gordon Henriksen0e138212007-12-25 03:10:07 +0000621 // GC poses two hazards to inlining, which only occur when the callee has GC:
622 // 1. If the caller has no GC, then the callee's GC must be propagated to the
623 // caller.
624 // 2. If the caller has a differing GC, it is invalid to inline.
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000625 if (CalledFunc->hasGC()) {
626 if (!Caller->hasGC())
627 Caller->setGC(CalledFunc->getGC());
628 else if (CalledFunc->getGC() != Caller->getGC())
Gordon Henriksen0e138212007-12-25 03:10:07 +0000629 return false;
630 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000631
Chris Lattner5052c912004-02-04 01:41:09 +0000632 // Get an iterator to the last basic block in the function, which will have
633 // the new function inlined after it.
634 //
635 Function::iterator LastBlock = &Caller->back();
636
Chris Lattner5e923de2004-02-04 02:51:48 +0000637 // Make sure to capture all of the return instructions from the cloned
Chris Lattnerca398dc2003-05-29 15:11:31 +0000638 // function.
Chris Lattnerec1bea02009-08-27 04:02:30 +0000639 SmallVector<ReturnInst*, 8> Returns;
Chris Lattnercd4d3392006-01-13 19:05:59 +0000640 ClonedCodeInfo InlinedFunctionInfo;
Dale Johannesen0744f092009-03-04 02:09:48 +0000641 Function::iterator FirstNewBlock;
Duncan Sandsf0c33542007-12-19 21:13:37 +0000642
Devang Patel29d3dd82010-06-23 23:55:51 +0000643 { // Scope to destroy VMap after cloning.
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000644 ValueToValueMapTy VMap;
Chris Lattner5b5bc302006-05-27 01:28:04 +0000645
Dan Gohman9614fcc2008-06-20 17:11:32 +0000646 assert(CalledFunc->arg_size() == CS.arg_size() &&
Chris Lattner5e923de2004-02-04 02:51:48 +0000647 "No varargs calls can be inlined!");
Duncan Sandsa7212e52008-09-05 12:37:12 +0000648
Chris Lattnerc93adca2008-01-11 06:09:30 +0000649 // Calculate the vector of arguments to pass into the function cloner, which
650 // matches up the formal to the actual argument values.
Chris Lattner5e923de2004-02-04 02:51:48 +0000651 CallSite::arg_iterator AI = CS.arg_begin();
Chris Lattnerc93adca2008-01-11 06:09:30 +0000652 unsigned ArgNo = 0;
Chris Lattnere4d5c442005-03-15 04:54:21 +0000653 for (Function::const_arg_iterator I = CalledFunc->arg_begin(),
Chris Lattnerc93adca2008-01-11 06:09:30 +0000654 E = CalledFunc->arg_end(); I != E; ++I, ++AI, ++ArgNo) {
655 Value *ActualArg = *AI;
Duncan Sandsa7212e52008-09-05 12:37:12 +0000656
Duncan Sandsd82375c2008-01-27 18:12:58 +0000657 // When byval arguments actually inlined, we need to make the copy implied
658 // by them explicit. However, we don't do this if the callee is readonly
659 // or readnone, because the copy would be unneeded: the callee doesn't
660 // modify the struct.
Chris Lattnere7ae7052010-12-20 07:57:41 +0000661 if (CalledFunc->paramHasAttr(ArgNo+1, Attribute::ByVal)) {
662 ActualArg = HandleByValArgument(ActualArg, TheCall, CalledFunc, IFI,
663 CalledFunc->getParamAlignment(ArgNo+1));
664
Duncan Sands2914ba62010-05-31 21:00:26 +0000665 // Calls that we inline may use the new alloca, so we need to clear
Chris Lattnere7ae7052010-12-20 07:57:41 +0000666 // their 'tail' flags if HandleByValArgument introduced a new alloca and
667 // the callee has calls.
668 MustClearTailCallFlags |= ActualArg != *AI;
Chris Lattnerc93adca2008-01-11 06:09:30 +0000669 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000670
Devang Patel29d3dd82010-06-23 23:55:51 +0000671 VMap[I] = ActualArg;
Chris Lattnerc93adca2008-01-11 06:09:30 +0000672 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000673
Chris Lattner5b5bc302006-05-27 01:28:04 +0000674 // We want the inliner to prune the code as it copies. We would LOVE to
675 // have no dead or constant instructions leftover after inlining occurs
676 // (which can happen, e.g., because an argument was constant), but we'll be
677 // happy with whatever the cloner can do.
Dan Gohman6cb8c232010-08-26 15:41:53 +0000678 CloneAndPruneFunctionInto(Caller, CalledFunc, VMap,
679 /*ModuleLevelChanges=*/false, Returns, ".i",
Chris Lattner60915142010-04-22 23:07:58 +0000680 &InlinedFunctionInfo, IFI.TD, TheCall);
Duncan Sandsa7212e52008-09-05 12:37:12 +0000681
Chris Lattnerd85340f2006-07-12 18:29:36 +0000682 // Remember the first block that is newly cloned over.
683 FirstNewBlock = LastBlock; ++FirstNewBlock;
Duncan Sandsa7212e52008-09-05 12:37:12 +0000684
Chris Lattnerd85340f2006-07-12 18:29:36 +0000685 // Update the callgraph if requested.
Chris Lattner60915142010-04-22 23:07:58 +0000686 if (IFI.CG)
Devang Patel29d3dd82010-06-23 23:55:51 +0000687 UpdateCallGraphAfterInlining(CS, FirstNewBlock, VMap, IFI);
Misha Brukmanfd939082005-04-21 23:48:37 +0000688 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000689
Chris Lattnerca398dc2003-05-29 15:11:31 +0000690 // If there are any alloca instructions in the block that used to be the entry
691 // block for the callee, move them to the entry block of the caller. First
692 // calculate which instruction they should be inserted before. We insert the
693 // instructions at the end of the current alloca list.
694 //
Chris Lattner21f20552006-01-13 18:16:48 +0000695 {
Chris Lattner80a38d22003-08-24 06:59:16 +0000696 BasicBlock::iterator InsertPoint = Caller->begin()->begin();
Chris Lattner5e923de2004-02-04 02:51:48 +0000697 for (BasicBlock::iterator I = FirstNewBlock->begin(),
Chris Lattner135755d2009-08-27 03:51:50 +0000698 E = FirstNewBlock->end(); I != E; ) {
699 AllocaInst *AI = dyn_cast<AllocaInst>(I++);
700 if (AI == 0) continue;
701
702 // If the alloca is now dead, remove it. This often occurs due to code
703 // specialization.
704 if (AI->use_empty()) {
705 AI->eraseFromParent();
706 continue;
Chris Lattner33bb3c82006-09-13 19:23:57 +0000707 }
Chris Lattner135755d2009-08-27 03:51:50 +0000708
709 if (!isa<Constant>(AI->getArraySize()))
710 continue;
711
Chris Lattner39add232010-12-06 07:43:04 +0000712 // Keep track of the static allocas that we inline into the caller.
Chris Lattner60915142010-04-22 23:07:58 +0000713 IFI.StaticAllocas.push_back(AI);
Chris Lattner8f2718f2009-08-27 04:20:52 +0000714
Chris Lattner135755d2009-08-27 03:51:50 +0000715 // Scan for the block of allocas that we can move over, and move them
716 // all at once.
717 while (isa<AllocaInst>(I) &&
Chris Lattner8f2718f2009-08-27 04:20:52 +0000718 isa<Constant>(cast<AllocaInst>(I)->getArraySize())) {
Chris Lattner60915142010-04-22 23:07:58 +0000719 IFI.StaticAllocas.push_back(cast<AllocaInst>(I));
Chris Lattner135755d2009-08-27 03:51:50 +0000720 ++I;
Chris Lattner8f2718f2009-08-27 04:20:52 +0000721 }
Chris Lattner135755d2009-08-27 03:51:50 +0000722
723 // Transfer all of the allocas over in a block. Using splice means
724 // that the instructions aren't removed from the symbol table, then
725 // reinserted.
726 Caller->getEntryBlock().getInstList().splice(InsertPoint,
727 FirstNewBlock->getInstList(),
728 AI, I);
729 }
Chris Lattner80a38d22003-08-24 06:59:16 +0000730 }
Chris Lattnerca398dc2003-05-29 15:11:31 +0000731
Nick Lewycky6d55f222011-05-22 05:22:10 +0000732 // Leave lifetime markers for the static alloca's, scoping them to the
733 // function we just inlined.
734 if (!IFI.StaticAllocas.empty()) {
735 // Also preserve the call graph, if applicable.
736 CallGraphNode *StartCGN = 0, *EndCGN = 0, *CallerNode = 0;
737 if (CallGraph *CG = IFI.CG) {
738 Function *Start = Intrinsic::getDeclaration(Caller->getParent(),
739 Intrinsic::lifetime_start);
740 Function *End = Intrinsic::getDeclaration(Caller->getParent(),
741 Intrinsic::lifetime_end);
742 StartCGN = CG->getOrInsertFunction(Start);
743 EndCGN = CG->getOrInsertFunction(End);
744 CallerNode = (*CG)[Caller];
745 }
746
747 IRBuilder<> builder(FirstNewBlock->begin());
748 for (unsigned ai = 0, ae = IFI.StaticAllocas.size(); ai != ae; ++ai) {
749 AllocaInst *AI = IFI.StaticAllocas[ai];
750
751 // If the alloca is already scoped to something smaller than the whole
752 // function then there's no need to add redundant, less accurate markers.
753 if (hasLifetimeMarkers(AI))
754 continue;
755
756 CallInst *StartCall = builder.CreateLifetimeStart(AI);
757 if (IFI.CG) CallerNode->addCalledFunction(StartCall, StartCGN);
758 for (unsigned ri = 0, re = Returns.size(); ri != re; ++ri) {
759 IRBuilder<> builder(Returns[ri]);
760 CallInst *EndCall = builder.CreateLifetimeEnd(AI);
761 if (IFI.CG) CallerNode->addCalledFunction(EndCall, EndCGN);
762 }
763 }
764 }
765
Chris Lattnerbf229f42006-01-13 19:34:14 +0000766 // If the inlined code contained dynamic alloca instructions, wrap the inlined
767 // code with llvm.stacksave/llvm.stackrestore intrinsics.
768 if (InlinedFunctionInfo.ContainsDynamicAllocas) {
769 Module *M = Caller->getParent();
Chris Lattnerbf229f42006-01-13 19:34:14 +0000770 // Get the two intrinsics we care about.
Chris Lattner6128df52009-10-17 05:39:39 +0000771 Function *StackSave = Intrinsic::getDeclaration(M, Intrinsic::stacksave);
772 Function *StackRestore=Intrinsic::getDeclaration(M,Intrinsic::stackrestore);
Chris Lattnerd85340f2006-07-12 18:29:36 +0000773
774 // If we are preserving the callgraph, add edges to the stacksave/restore
775 // functions for the calls we insert.
Chris Lattner21ba23d2006-07-18 21:48:57 +0000776 CallGraphNode *StackSaveCGN = 0, *StackRestoreCGN = 0, *CallerNode = 0;
Chris Lattner60915142010-04-22 23:07:58 +0000777 if (CallGraph *CG = IFI.CG) {
Chris Lattner6128df52009-10-17 05:39:39 +0000778 StackSaveCGN = CG->getOrInsertFunction(StackSave);
779 StackRestoreCGN = CG->getOrInsertFunction(StackRestore);
Chris Lattnerd85340f2006-07-12 18:29:36 +0000780 CallerNode = (*CG)[Caller];
781 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000782
Chris Lattnerbf229f42006-01-13 19:34:14 +0000783 // Insert the llvm.stacksave.
Duncan Sandsa7212e52008-09-05 12:37:12 +0000784 CallInst *SavedPtr = CallInst::Create(StackSave, "savedstack",
Gabor Greif051a9502008-04-06 20:25:17 +0000785 FirstNewBlock->begin());
Chris Lattner60915142010-04-22 23:07:58 +0000786 if (IFI.CG) CallerNode->addCalledFunction(SavedPtr, StackSaveCGN);
Duncan Sandsa7212e52008-09-05 12:37:12 +0000787
Chris Lattnerbf229f42006-01-13 19:34:14 +0000788 // Insert a call to llvm.stackrestore before any return instructions in the
789 // inlined function.
Chris Lattnerd85340f2006-07-12 18:29:36 +0000790 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
Gabor Greif051a9502008-04-06 20:25:17 +0000791 CallInst *CI = CallInst::Create(StackRestore, SavedPtr, "", Returns[i]);
Chris Lattner60915142010-04-22 23:07:58 +0000792 if (IFI.CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
Chris Lattnerd85340f2006-07-12 18:29:36 +0000793 }
Chris Lattner468fb1d2006-01-14 20:07:50 +0000794
795 // Count the number of StackRestore calls we insert.
796 unsigned NumStackRestores = Returns.size();
Duncan Sandsa7212e52008-09-05 12:37:12 +0000797
Chris Lattnerbf229f42006-01-13 19:34:14 +0000798 // If we are inlining an invoke instruction, insert restores before each
799 // unwind. These unwinds will be rewritten into branches later.
800 if (InlinedFunctionInfo.ContainsUnwinds && isa<InvokeInst>(TheCall)) {
801 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
802 BB != E; ++BB)
Chris Lattner468fb1d2006-01-14 20:07:50 +0000803 if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
Chris Lattner6128df52009-10-17 05:39:39 +0000804 CallInst *CI = CallInst::Create(StackRestore, SavedPtr, "", UI);
Chris Lattner60915142010-04-22 23:07:58 +0000805 if (IFI.CG) CallerNode->addCalledFunction(CI, StackRestoreCGN);
Chris Lattner468fb1d2006-01-14 20:07:50 +0000806 ++NumStackRestores;
807 }
808 }
Chris Lattnerbf229f42006-01-13 19:34:14 +0000809 }
810
Duncan Sandsa7212e52008-09-05 12:37:12 +0000811 // If we are inlining tail call instruction through a call site that isn't
Chris Lattner1fdf4a82006-01-13 19:18:11 +0000812 // marked 'tail', we must remove the tail marker for any calls in the inlined
Duncan Sandsf0c33542007-12-19 21:13:37 +0000813 // code. Also, calls inlined through a 'nounwind' call site should be marked
814 // 'nounwind'.
815 if (InlinedFunctionInfo.ContainsCalls &&
816 (MustClearTailCallFlags || MarkNoUnwind)) {
Chris Lattner1b491412005-05-06 06:47:52 +0000817 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
818 BB != E; ++BB)
819 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Duncan Sandsf0c33542007-12-19 21:13:37 +0000820 if (CallInst *CI = dyn_cast<CallInst>(I)) {
821 if (MustClearTailCallFlags)
822 CI->setTailCall(false);
823 if (MarkNoUnwind)
824 CI->setDoesNotThrow();
825 }
Chris Lattner1b491412005-05-06 06:47:52 +0000826 }
827
Duncan Sandsf0c33542007-12-19 21:13:37 +0000828 // If we are inlining through a 'nounwind' call site then any inlined 'unwind'
829 // instructions are unreachable.
830 if (InlinedFunctionInfo.ContainsUnwinds && MarkNoUnwind)
831 for (Function::iterator BB = FirstNewBlock, E = Caller->end();
832 BB != E; ++BB) {
833 TerminatorInst *Term = BB->getTerminator();
834 if (isa<UnwindInst>(Term)) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000835 new UnreachableInst(Context, Term);
Duncan Sandsf0c33542007-12-19 21:13:37 +0000836 BB->getInstList().erase(Term);
837 }
838 }
839
Chris Lattner5e923de2004-02-04 02:51:48 +0000840 // If we are inlining for an invoke instruction, we must make sure to rewrite
841 // any inlined 'unwind' instructions into branches to the invoke exception
842 // destination, and call instructions into invoke instructions.
Chris Lattnercd4d3392006-01-13 19:05:59 +0000843 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
Chris Lattner81dfb382009-09-01 18:44:06 +0000844 HandleInlinedInvoke(II, FirstNewBlock, InlinedFunctionInfo);
Chris Lattner5e923de2004-02-04 02:51:48 +0000845
Chris Lattner44a68072004-02-04 04:17:06 +0000846 // If we cloned in _exactly one_ basic block, and if that block ends in a
847 // return instruction, we splice the body of the inlined callee directly into
848 // the calling basic block.
849 if (Returns.size() == 1 && std::distance(FirstNewBlock, Caller->end()) == 1) {
850 // Move all of the instructions right before the call.
851 OrigBB->getInstList().splice(TheCall, FirstNewBlock->getInstList(),
852 FirstNewBlock->begin(), FirstNewBlock->end());
853 // Remove the cloned basic block.
854 Caller->getBasicBlockList().pop_back();
Misha Brukmanfd939082005-04-21 23:48:37 +0000855
Chris Lattner44a68072004-02-04 04:17:06 +0000856 // If the call site was an invoke instruction, add a branch to the normal
857 // destination.
858 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall))
Gabor Greif051a9502008-04-06 20:25:17 +0000859 BranchInst::Create(II->getNormalDest(), TheCall);
Chris Lattner44a68072004-02-04 04:17:06 +0000860
861 // If the return instruction returned a value, replace uses of the call with
862 // uses of the returned value.
Devang Pateldc00d422008-03-04 21:15:15 +0000863 if (!TheCall->use_empty()) {
864 ReturnInst *R = Returns[0];
Eli Friedman5877ad72009-05-08 00:22:04 +0000865 if (TheCall == R->getReturnValue())
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000866 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Eli Friedman5877ad72009-05-08 00:22:04 +0000867 else
868 TheCall->replaceAllUsesWith(R->getReturnValue());
Devang Pateldc00d422008-03-04 21:15:15 +0000869 }
Chris Lattner44a68072004-02-04 04:17:06 +0000870 // Since we are now done with the Call/Invoke, we can delete it.
Dan Gohman1adec832008-06-21 22:08:46 +0000871 TheCall->eraseFromParent();
Chris Lattner44a68072004-02-04 04:17:06 +0000872
873 // Since we are now done with the return instruction, delete it also.
Dan Gohman1adec832008-06-21 22:08:46 +0000874 Returns[0]->eraseFromParent();
Chris Lattner44a68072004-02-04 04:17:06 +0000875
876 // We are now done with the inlining.
877 return true;
878 }
879
880 // Otherwise, we have the normal case, of more than one block to inline or
881 // multiple return sites.
882
Chris Lattner5e923de2004-02-04 02:51:48 +0000883 // We want to clone the entire callee function into the hole between the
884 // "starter" and "ender" blocks. How we accomplish this depends on whether
885 // this is an invoke instruction or a call instruction.
886 BasicBlock *AfterCallBB;
887 if (InvokeInst *II = dyn_cast<InvokeInst>(TheCall)) {
Misha Brukmanfd939082005-04-21 23:48:37 +0000888
Chris Lattner5e923de2004-02-04 02:51:48 +0000889 // Add an unconditional branch to make this look like the CallInst case...
Gabor Greif051a9502008-04-06 20:25:17 +0000890 BranchInst *NewBr = BranchInst::Create(II->getNormalDest(), TheCall);
Misha Brukmanfd939082005-04-21 23:48:37 +0000891
Chris Lattner5e923de2004-02-04 02:51:48 +0000892 // Split the basic block. This guarantees that no PHI nodes will have to be
893 // updated due to new incoming edges, and make the invoke case more
894 // symmetric to the call case.
895 AfterCallBB = OrigBB->splitBasicBlock(NewBr,
Chris Lattner284d1b82004-12-11 16:59:54 +0000896 CalledFunc->getName()+".exit");
Misha Brukmanfd939082005-04-21 23:48:37 +0000897
Chris Lattner5e923de2004-02-04 02:51:48 +0000898 } else { // It's a call
Chris Lattner44a68072004-02-04 04:17:06 +0000899 // If this is a call instruction, we need to split the basic block that
900 // the call lives in.
Chris Lattner5e923de2004-02-04 02:51:48 +0000901 //
902 AfterCallBB = OrigBB->splitBasicBlock(TheCall,
Chris Lattner284d1b82004-12-11 16:59:54 +0000903 CalledFunc->getName()+".exit");
Chris Lattner5e923de2004-02-04 02:51:48 +0000904 }
905
Chris Lattner44a68072004-02-04 04:17:06 +0000906 // Change the branch that used to go to AfterCallBB to branch to the first
907 // basic block of the inlined function.
908 //
909 TerminatorInst *Br = OrigBB->getTerminator();
Misha Brukmanfd939082005-04-21 23:48:37 +0000910 assert(Br && Br->getOpcode() == Instruction::Br &&
Chris Lattner44a68072004-02-04 04:17:06 +0000911 "splitBasicBlock broken!");
912 Br->setOperand(0, FirstNewBlock);
913
914
915 // Now that the function is correct, make it a little bit nicer. In
916 // particular, move the basic blocks inserted from the end of the function
917 // into the space made by splitting the source basic block.
Chris Lattner44a68072004-02-04 04:17:06 +0000918 Caller->getBasicBlockList().splice(AfterCallBB, Caller->getBasicBlockList(),
919 FirstNewBlock, Caller->end());
920
Chris Lattner5e923de2004-02-04 02:51:48 +0000921 // Handle all of the return instructions that we just cloned in, and eliminate
922 // any users of the original call/invoke instruction.
Devang Patelb8f198a2008-03-10 18:34:00 +0000923 const Type *RTy = CalledFunc->getReturnType();
Dan Gohman2c317502008-06-20 01:03:44 +0000924
Duncan Sands6fb881c2010-11-17 11:16:23 +0000925 PHINode *PHI = 0;
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000926 if (Returns.size() > 1) {
Chris Lattner5e923de2004-02-04 02:51:48 +0000927 // The PHI node should go at the front of the new basic block to merge all
928 // possible incoming values.
Chris Lattner5e923de2004-02-04 02:51:48 +0000929 if (!TheCall->use_empty()) {
Jay Foad3ecfc862011-03-30 11:28:46 +0000930 PHI = PHINode::Create(RTy, Returns.size(), TheCall->getName(),
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000931 AfterCallBB->begin());
932 // Anything that used the result of the function call should now use the
933 // PHI node as their operand.
Duncan Sandsa7212e52008-09-05 12:37:12 +0000934 TheCall->replaceAllUsesWith(PHI);
Chris Lattner5e923de2004-02-04 02:51:48 +0000935 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000936
Gabor Greifc478e522009-01-15 18:40:09 +0000937 // Loop over all of the return instructions adding entries to the PHI node
938 // as appropriate.
Dan Gohmanfc74abf2008-07-23 00:34:11 +0000939 if (PHI) {
940 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
941 ReturnInst *RI = Returns[i];
942 assert(RI->getReturnValue()->getType() == PHI->getType() &&
943 "Ret value not consistent in function!");
944 PHI->addIncoming(RI->getReturnValue(), RI->getParent());
Devang Patel12a466b2008-03-07 20:06:16 +0000945 }
946 }
947
Chris Lattnerc581acb2009-10-27 05:39:41 +0000948
Gabor Greifde62aea2009-01-16 23:08:50 +0000949 // Add a branch to the merge points and remove return instructions.
Chris Lattner5e923de2004-02-04 02:51:48 +0000950 for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
951 ReturnInst *RI = Returns[i];
Dale Johannesen0744f092009-03-04 02:09:48 +0000952 BranchInst::Create(AfterCallBB, RI);
Devang Patelb8f198a2008-03-10 18:34:00 +0000953 RI->eraseFromParent();
Chris Lattner5e923de2004-02-04 02:51:48 +0000954 }
Devang Patelb8f198a2008-03-10 18:34:00 +0000955 } else if (!Returns.empty()) {
956 // Otherwise, if there is exactly one return value, just replace anything
957 // using the return value of the call with the computed value.
Eli Friedman5877ad72009-05-08 00:22:04 +0000958 if (!TheCall->use_empty()) {
959 if (TheCall == Returns[0]->getReturnValue())
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000960 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Eli Friedman5877ad72009-05-08 00:22:04 +0000961 else
962 TheCall->replaceAllUsesWith(Returns[0]->getReturnValue());
963 }
Duncan Sandsa7212e52008-09-05 12:37:12 +0000964
Devang Patelb8f198a2008-03-10 18:34:00 +0000965 // Splice the code from the return block into the block that it will return
966 // to, which contains the code that was after the call.
967 BasicBlock *ReturnBB = Returns[0]->getParent();
968 AfterCallBB->getInstList().splice(AfterCallBB->begin(),
969 ReturnBB->getInstList());
Duncan Sandsa7212e52008-09-05 12:37:12 +0000970
Devang Patelb8f198a2008-03-10 18:34:00 +0000971 // Update PHI nodes that use the ReturnBB to use the AfterCallBB.
972 ReturnBB->replaceAllUsesWith(AfterCallBB);
Duncan Sandsa7212e52008-09-05 12:37:12 +0000973
Devang Patelb8f198a2008-03-10 18:34:00 +0000974 // Delete the return instruction now and empty ReturnBB now.
975 Returns[0]->eraseFromParent();
976 ReturnBB->eraseFromParent();
Chris Lattner3787e762004-10-17 23:21:07 +0000977 } else if (!TheCall->use_empty()) {
978 // No returns, but something is using the return value of the call. Just
979 // nuke the result.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000980 TheCall->replaceAllUsesWith(UndefValue::get(TheCall->getType()));
Chris Lattner5e923de2004-02-04 02:51:48 +0000981 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000982
Chris Lattner5e923de2004-02-04 02:51:48 +0000983 // Since we are now done with the Call/Invoke, we can delete it.
Chris Lattner3787e762004-10-17 23:21:07 +0000984 TheCall->eraseFromParent();
Chris Lattnerca398dc2003-05-29 15:11:31 +0000985
Chris Lattner7152c232003-08-24 04:06:56 +0000986 // We should always be able to fold the entry block of the function into the
987 // single predecessor of the block...
Chris Lattnercd01ae52004-04-16 05:17:59 +0000988 assert(cast<BranchInst>(Br)->isUnconditional() && "splitBasicBlock broken!");
Chris Lattner7152c232003-08-24 04:06:56 +0000989 BasicBlock *CalleeEntry = cast<BranchInst>(Br)->getSuccessor(0);
Chris Lattner44a68072004-02-04 04:17:06 +0000990
Chris Lattnercd01ae52004-04-16 05:17:59 +0000991 // Splice the code entry block into calling block, right before the
992 // unconditional branch.
993 OrigBB->getInstList().splice(Br, CalleeEntry->getInstList());
994 CalleeEntry->replaceAllUsesWith(OrigBB); // Update PHI nodes
995
996 // Remove the unconditional branch.
997 OrigBB->getInstList().erase(Br);
998
999 // Now we can remove the CalleeEntry block, which is now empty.
1000 Caller->getBasicBlockList().erase(CalleeEntry);
Duncan Sandsa7212e52008-09-05 12:37:12 +00001001
Duncan Sands6fb881c2010-11-17 11:16:23 +00001002 // If we inserted a phi node, check to see if it has a single value (e.g. all
1003 // the entries are the same or undef). If so, remove the PHI so it doesn't
1004 // block other optimizations.
1005 if (PHI)
1006 if (Value *V = SimplifyInstruction(PHI, IFI.TD)) {
1007 PHI->replaceAllUsesWith(V);
1008 PHI->eraseFromParent();
1009 }
1010
Chris Lattnerca398dc2003-05-29 15:11:31 +00001011 return true;
1012}