blob: 28c278f036274c90ee79324e80dc6458f795eb9d [file] [log] [blame]
Chris Lattner2240d2b2003-09-20 05:03:31 +00001//===- TailRecursionElimination.cpp - Eliminate Tail Calls ----------------===//
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 Lattner2240d2b2003-09-20 05:03:31 +00009//
Chris Lattner7152da32003-12-08 05:34:54 +000010// This file transforms calls of the current function (self recursion) followed
11// by a return instruction with a branch to the entry of the function, creating
12// a loop. This pass also implements the following extensions to the basic
13// algorithm:
Chris Lattner2240d2b2003-09-20 05:03:31 +000014//
Chris Lattner7152da32003-12-08 05:34:54 +000015// 1. Trivial instructions between the call and return do not prevent the
16// transformation from taking place, though currently the analysis cannot
17// support moving any really useful instructions (only dead ones).
Chris Lattner543d6222003-12-08 23:19:26 +000018// 2. This pass transforms functions that are prevented from being tail
Duncan Sands24080a92010-07-10 20:31:42 +000019// recursive by an associative and commutative expression to use an
20// accumulator variable, thus compiling the typical naive factorial or
21// 'fib' implementation into efficient code.
Chris Lattnerd64152a2003-12-14 23:57:39 +000022// 3. TRE is performed if the function returns void, if the return
23// returns the result returned by the call, or if the function returns a
24// run-time constant on all exits from the function. It is possible, though
25// unlikely, that the return returns something else (like constant 0), and
26// can still be TRE'd. It can be TRE'd if ALL OTHER return instructions in
27// the function return the exact same value.
Nick Lewycky0cade262009-11-07 07:10:01 +000028// 4. If it can prove that callees do not access their caller stack frame,
Chris Lattner7f78f212005-05-09 23:51:13 +000029// they are marked as eligible for tail call elimination (by the code
30// generator).
Chris Lattner2240d2b2003-09-20 05:03:31 +000031//
Chris Lattner7152da32003-12-08 05:34:54 +000032// There are several improvements that could be made:
33//
34// 1. If the function has any alloca instructions, these instructions will be
35// moved out of the entry block of the function, causing them to be
36// evaluated each time through the tail recursion. Safely keeping allocas
37// in the entry block requires analysis to proves that the tail-called
38// function does not read or write the stack object.
Chris Lattner7a2bdde2011-04-15 05:18:47 +000039// 2. Tail recursion is only performed if the call immediately precedes the
Chris Lattner7152da32003-12-08 05:34:54 +000040// return instruction. It's possible that there could be a jump between
41// the call and the return.
Chris Lattnerd64152a2003-12-14 23:57:39 +000042// 3. There can be intervening operations between the call and the return that
Chris Lattner7152da32003-12-08 05:34:54 +000043// prevent the TRE from occurring. For example, there could be GEP's and
44// stores to memory that will not be read or written by the call. This
45// requires some substantial analysis (such as with DSA) to prove safe to
46// move ahead of the call, but doing so could allow many more TREs to be
47// performed, for example in TreeAdd/TreeAlloc from the treeadd benchmark.
Chris Lattner7f78f212005-05-09 23:51:13 +000048// 4. The algorithm we use to detect if callees access their caller stack
49// frames is very primitive.
Chris Lattner2240d2b2003-09-20 05:03:31 +000050//
51//===----------------------------------------------------------------------===//
52
Chris Lattner0e5f4992006-12-19 21:40:18 +000053#define DEBUG_TYPE "tailcallelim"
Chris Lattner3fc6ef12003-09-20 05:14:13 +000054#include "llvm/Transforms/Scalar.h"
Evan Chengc3f507f2011-01-29 04:46:23 +000055#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner6a35b402009-06-19 04:22:16 +000056#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerce869ee2005-08-07 04:27:41 +000057#include "llvm/Constants.h"
Chris Lattner2240d2b2003-09-20 05:03:31 +000058#include "llvm/DerivedTypes.h"
59#include "llvm/Function.h"
60#include "llvm/Instructions.h"
Evan Chengc3f507f2011-01-29 04:46:23 +000061#include "llvm/IntrinsicInst.h"
Rafael Espindola0e00c6c2011-05-16 03:05:33 +000062#include "llvm/Module.h"
Chris Lattner2240d2b2003-09-20 05:03:31 +000063#include "llvm/Pass.h"
Nick Lewycky0cade262009-11-07 07:10:01 +000064#include "llvm/Analysis/CaptureTracking.h"
Dan Gohmanea25b482010-04-16 15:57:50 +000065#include "llvm/Analysis/InlineCost.h"
Duncan Sandscdbd9922010-11-16 17:41:24 +000066#include "llvm/Analysis/InstructionSimplify.h"
Dan Gohmandd9344f2010-05-28 16:19:17 +000067#include "llvm/Analysis/Loads.h"
Dan Gohmanea25b482010-04-16 15:57:50 +000068#include "llvm/Support/CallSite.h"
Chris Lattner543d6222003-12-08 23:19:26 +000069#include "llvm/Support/CFG.h"
Evan Chengc3f507f2011-01-29 04:46:23 +000070#include "llvm/Support/Debug.h"
Francois Pichet337c0812011-01-29 20:06:16 +000071#include "llvm/Support/raw_ostream.h"
Nick Lewycky18b1f4e2012-10-22 03:03:52 +000072#include "llvm/Support/ValueHandle.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000073#include "llvm/ADT/Statistic.h"
Evan Chengc3f507f2011-01-29 04:46:23 +000074#include "llvm/ADT/STLExtras.h"
Chris Lattnerf8485c62003-11-20 18:25:24 +000075using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000076
Chris Lattner0e5f4992006-12-19 21:40:18 +000077STATISTIC(NumEliminated, "Number of tail calls removed");
Evan Cheng60f5ad42011-01-29 04:53:35 +000078STATISTIC(NumRetDuped, "Number of return duplicated");
Chris Lattner0e5f4992006-12-19 21:40:18 +000079STATISTIC(NumAccumAdded, "Number of accumulators introduced");
Chris Lattner2240d2b2003-09-20 05:03:31 +000080
Chris Lattner0e5f4992006-12-19 21:40:18 +000081namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000082 struct TailCallElim : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +000083 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000084 TailCallElim() : FunctionPass(ID) {
85 initializeTailCallElimPass(*PassRegistry::getPassRegistry());
86 }
Devang Patel794fd752007-05-01 21:15:47 +000087
Chris Lattner2240d2b2003-09-20 05:03:31 +000088 virtual bool runOnFunction(Function &F);
Chris Lattner7152da32003-12-08 05:34:54 +000089
90 private:
Evan Chengc3f507f2011-01-29 04:46:23 +000091 CallInst *FindTRECandidate(Instruction *I,
92 bool CannotTailCallElimCallsMarkedTail);
93 bool EliminateRecursiveTailCall(CallInst *CI, ReturnInst *Ret,
94 BasicBlock *&OldEntry,
95 bool &TailCallsAreMarkedTail,
96 SmallVector<PHINode*, 8> &ArgumentPHIs,
97 bool CannotTailCallElimCallsMarkedTail);
98 bool FoldReturnAndProcessPred(BasicBlock *BB,
99 ReturnInst *Ret, BasicBlock *&OldEntry,
100 bool &TailCallsAreMarkedTail,
101 SmallVector<PHINode*, 8> &ArgumentPHIs,
102 bool CannotTailCallElimCallsMarkedTail);
Chris Lattner7152da32003-12-08 05:34:54 +0000103 bool ProcessReturningBlock(ReturnInst *RI, BasicBlock *&OldEntry,
Chris Lattnerce869ee2005-08-07 04:27:41 +0000104 bool &TailCallsAreMarkedTail,
Nick Lewycky0cade262009-11-07 07:10:01 +0000105 SmallVector<PHINode*, 8> &ArgumentPHIs,
Chris Lattnerce869ee2005-08-07 04:27:41 +0000106 bool CannotTailCallElimCallsMarkedTail);
Chris Lattner7152da32003-12-08 05:34:54 +0000107 bool CanMoveAboveCall(Instruction *I, CallInst *CI);
Chris Lattner543d6222003-12-08 23:19:26 +0000108 Value *CanTransformAccumulatorRecursion(Instruction *I, CallInst *CI);
Chris Lattner2240d2b2003-09-20 05:03:31 +0000109 };
Chris Lattner2240d2b2003-09-20 05:03:31 +0000110}
111
Dan Gohman844731a2008-05-13 00:00:25 +0000112char TailCallElim::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +0000113INITIALIZE_PASS(TailCallElim, "tailcallelim",
Owen Andersonce665bd2010-10-07 22:25:06 +0000114 "Tail Call Elimination", false, false)
Dan Gohman844731a2008-05-13 00:00:25 +0000115
Brian Gaeked0fde302003-11-11 22:41:34 +0000116// Public interface to the TailCallElimination pass
Chris Lattnerf8485c62003-11-20 18:25:24 +0000117FunctionPass *llvm::createTailCallEliminationPass() {
118 return new TailCallElim();
119}
Chris Lattner3fc6ef12003-09-20 05:14:13 +0000120
Nick Lewycky18b1f4e2012-10-22 03:03:52 +0000121/// CanTRE - Scan the specified basic block for alloca instructions.
122/// If it contains any that are variable-sized or not in the entry block,
123/// returns false.
124static bool CanTRE(AllocaInst *AI) {
125 // Because of PR962, we don't TRE allocas outside the entry block.
126
127 // If this alloca is in the body of the function, or if it is a variable
128 // sized allocation, we cannot tail call eliminate calls marked 'tail'
129 // with this mechanism.
130 BasicBlock *BB = AI->getParent();
131 return BB == &BB->getParent()->getEntryBlock() &&
132 isa<ConstantInt>(AI->getArraySize());
Nick Lewyckycb194382009-11-07 07:42:38 +0000133}
134
Nick Lewycky18b1f4e2012-10-22 03:03:52 +0000135struct AllocaCaptureTracker : public CaptureTracker {
136 AllocaCaptureTracker() : Captured(false) {}
Chris Lattnerce869ee2005-08-07 04:27:41 +0000137
Nick Lewycky18b1f4e2012-10-22 03:03:52 +0000138 void tooManyUses() { Captured = true; }
139
140 bool shouldExplore(Use *U) {
141 Value *V = U->getUser();
142 if (isa<CallInst>(V) || isa<InvokeInst>(V))
143 UsesAlloca.push_back(V);
144
145 return true;
146 }
147
148 bool captured(Use *U) {
149 if (isa<ReturnInst>(U->getUser()))
150 return false;
151
152 Captured = true;
153 return true;
154 }
155
156 SmallVector<WeakVH, 64> UsesAlloca;
157
158 bool Captured;
159};
Chris Lattner7f78f212005-05-09 23:51:13 +0000160
Chris Lattner2240d2b2003-09-20 05:03:31 +0000161bool TailCallElim::runOnFunction(Function &F) {
162 // If this function is a varargs function, we won't be able to PHI the args
163 // right, so don't even try to convert it...
164 if (F.getFunctionType()->isVarArg()) return false;
165
166 BasicBlock *OldEntry = 0;
Chris Lattnerce869ee2005-08-07 04:27:41 +0000167 bool TailCallsAreMarkedTail = false;
Nick Lewycky0cade262009-11-07 07:10:01 +0000168 SmallVector<PHINode*, 8> ArgumentPHIs;
Chris Lattner2240d2b2003-09-20 05:03:31 +0000169 bool MadeChange = false;
Chris Lattner7f78f212005-05-09 23:51:13 +0000170 bool FunctionContainsEscapingAllocas = false;
171
Nick Lewycky18b1f4e2012-10-22 03:03:52 +0000172 // CanTRETailMarkedCall - If false, we cannot perform TRE on tail calls
Chris Lattnerce869ee2005-08-07 04:27:41 +0000173 // marked with the 'tail' attribute, because doing so would cause the stack
Nick Lewycky18b1f4e2012-10-22 03:03:52 +0000174 // size to increase (real TRE would deallocate variable sized allocas, TRE
Chris Lattnerce869ee2005-08-07 04:27:41 +0000175 // doesn't).
Nick Lewycky18b1f4e2012-10-22 03:03:52 +0000176 bool CanTRETailMarkedCall = true;
Chris Lattnerce869ee2005-08-07 04:27:41 +0000177
Nick Lewycky18b1f4e2012-10-22 03:03:52 +0000178 // Find calls that can be marked tail.
179 AllocaCaptureTracker ACT;
180 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB) {
181 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
182 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
183 CanTRETailMarkedCall &= CanTRE(AI);
184 PointerMayBeCaptured(AI, &ACT);
185 if (ACT.Captured)
186 return false;
187 }
188 }
Chris Lattner7f78f212005-05-09 23:51:13 +0000189 }
Nadav Rotema94d6e82012-07-24 10:51:42 +0000190
Nick Lewycky18b1f4e2012-10-22 03:03:52 +0000191 // Second pass, change any tail recursive calls to loops.
Evan Chengc3f507f2011-01-29 04:46:23 +0000192 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
193 if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB->getTerminator())) {
194 bool Change = ProcessReturningBlock(Ret, OldEntry, TailCallsAreMarkedTail,
Nick Lewycky18b1f4e2012-10-22 03:03:52 +0000195 ArgumentPHIs, !CanTRETailMarkedCall);
Evan Chengc3f507f2011-01-29 04:46:23 +0000196 if (!Change && BB->getFirstNonPHIOrDbg() == Ret)
197 Change = FoldReturnAndProcessPred(BB, Ret, OldEntry,
198 TailCallsAreMarkedTail, ArgumentPHIs,
Nick Lewycky18b1f4e2012-10-22 03:03:52 +0000199 !CanTRETailMarkedCall);
Evan Chengc3f507f2011-01-29 04:46:23 +0000200 MadeChange |= Change;
201 }
202 }
Chris Lattnerce869ee2005-08-07 04:27:41 +0000203
Chris Lattnercf2f8922003-12-08 23:37:35 +0000204 // If we eliminated any tail recursions, it's possible that we inserted some
205 // silly PHI nodes which just merge an initial value (the incoming operand)
206 // with themselves. Check to see if we did and clean up our mess if so. This
207 // occurs when a function passes an argument straight through to its tail
208 // call.
209 if (!ArgumentPHIs.empty()) {
Chris Lattnercf2f8922003-12-08 23:37:35 +0000210 for (unsigned i = 0, e = ArgumentPHIs.size(); i != e; ++i) {
211 PHINode *PN = ArgumentPHIs[i];
Chris Lattnercf2f8922003-12-08 23:37:35 +0000212
213 // If the PHI Node is a dynamic constant, replace it with the value it is.
Duncan Sandscdbd9922010-11-16 17:41:24 +0000214 if (Value *PNV = SimplifyInstruction(PN)) {
Chris Lattnerce869ee2005-08-07 04:27:41 +0000215 PN->replaceAllUsesWith(PNV);
216 PN->eraseFromParent();
Chris Lattnercf2f8922003-12-08 23:37:35 +0000217 }
218 }
219 }
220
Nick Lewycky18b1f4e2012-10-22 03:03:52 +0000221 // Finally, if this function contains no non-escaping allocas and doesn't
222 // call setjmp, mark all calls in the function as eligible for tail calls
223 // (there is no stack memory for them to access).
224 std::sort(ACT.UsesAlloca.begin(), ACT.UsesAlloca.end());
225
Bill Wendling3c5e6092011-10-17 18:43:40 +0000226 if (!FunctionContainsEscapingAllocas && !F.callsFunctionThatReturnsTwice())
Chris Lattner7f78f212005-05-09 23:51:13 +0000227 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
228 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Nick Lewycky18b1f4e2012-10-22 03:03:52 +0000229 if (CallInst *CI = dyn_cast<CallInst>(I))
230 if (!std::binary_search(ACT.UsesAlloca.begin(), ACT.UsesAlloca.end(),
231 CI)) {
232 CI->setTailCall();
233 MadeChange = true;
234 }
Chris Lattner7f78f212005-05-09 23:51:13 +0000235
Chris Lattner2240d2b2003-09-20 05:03:31 +0000236 return MadeChange;
237}
Chris Lattner7152da32003-12-08 05:34:54 +0000238
Chris Lattner543d6222003-12-08 23:19:26 +0000239/// CanMoveAboveCall - Return true if it is safe to move the specified
240/// instruction from after the call to before the call, assuming that all
241/// instructions between the call and this instruction are movable.
242///
Chris Lattner7152da32003-12-08 05:34:54 +0000243bool TailCallElim::CanMoveAboveCall(Instruction *I, CallInst *CI) {
244 // FIXME: We can move load/store/call/free instructions above the call if the
245 // call does not mod/ref the memory location being processed.
Chris Lattner6a35b402009-06-19 04:22:16 +0000246 if (I->mayHaveSideEffects()) // This also handles volatile loads.
Chris Lattner7152da32003-12-08 05:34:54 +0000247 return false;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000248
Nick Lewycky0cade262009-11-07 07:10:01 +0000249 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
Chris Lattner6a35b402009-06-19 04:22:16 +0000250 // Loads may always be moved above calls without side effects.
251 if (CI->mayHaveSideEffects()) {
252 // Non-volatile loads may be moved above a call with side effects if it
253 // does not write to memory and the load provably won't trap.
254 // FIXME: Writes to memory only matter if they may alias the pointer
255 // being loaded from.
256 if (CI->mayWriteToMemory() ||
Bob Wilson49db68f2010-01-30 04:42:39 +0000257 !isSafeToLoadUnconditionally(L->getPointerOperand(), L,
258 L->getAlignment()))
Chris Lattner6a35b402009-06-19 04:22:16 +0000259 return false;
260 }
261 }
Chris Lattner7152da32003-12-08 05:34:54 +0000262
263 // Otherwise, if this is a side-effect free instruction, check to make sure
264 // that it does not use the return value of the call. If it doesn't use the
265 // return value of the call, it must only use things that are defined before
266 // the call, or movable instructions between the call and the instruction
267 // itself.
268 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
269 if (I->getOperand(i) == CI)
270 return false;
271 return true;
272}
273
Chris Lattnerd64152a2003-12-14 23:57:39 +0000274// isDynamicConstant - Return true if the specified value is the same when the
275// return would exit as it was when the initial iteration of the recursive
276// function was executed.
277//
278// We currently handle static constants and arguments that are not modified as
279// part of the recursion.
280//
Nick Lewyckyf80fcd02009-11-07 21:10:15 +0000281static bool isDynamicConstant(Value *V, CallInst *CI, ReturnInst *RI) {
Chris Lattnerd64152a2003-12-14 23:57:39 +0000282 if (isa<Constant>(V)) return true; // Static constants are always dyn consts
283
284 // Check to see if this is an immutable argument, if so, the value
285 // will be available to initialize the accumulator.
286 if (Argument *Arg = dyn_cast<Argument>(V)) {
287 // Figure out which argument number this is...
288 unsigned ArgNo = 0;
289 Function *F = CI->getParent()->getParent();
Chris Lattnere4d5c442005-03-15 04:54:21 +0000290 for (Function::arg_iterator AI = F->arg_begin(); &*AI != Arg; ++AI)
Chris Lattnerd64152a2003-12-14 23:57:39 +0000291 ++ArgNo;
Misha Brukmanfd939082005-04-21 23:48:37 +0000292
Chris Lattnerd64152a2003-12-14 23:57:39 +0000293 // If we are passing this argument into call as the corresponding
294 // argument operand, then the argument is dynamically constant.
295 // Otherwise, we cannot transform this function safely.
Gabor Greifde9f5452010-06-24 00:44:01 +0000296 if (CI->getArgOperand(ArgNo) == Arg)
Chris Lattnerd64152a2003-12-14 23:57:39 +0000297 return true;
298 }
Nick Lewyckyf80fcd02009-11-07 21:10:15 +0000299
300 // Switch cases are always constant integers. If the value is being switched
301 // on and the return is only reachable from one of its cases, it's
302 // effectively constant.
303 if (BasicBlock *UniquePred = RI->getParent()->getUniquePredecessor())
304 if (SwitchInst *SI = dyn_cast<SwitchInst>(UniquePred->getTerminator()))
305 if (SI->getCondition() == V)
306 return SI->getDefaultDest() != RI->getParent();
307
Chris Lattnerd64152a2003-12-14 23:57:39 +0000308 // Not a constant or immutable argument, we can't safely transform.
309 return false;
310}
311
312// getCommonReturnValue - Check to see if the function containing the specified
Duncan Sandsd50e9e22010-06-26 12:53:31 +0000313// tail call consistently returns the same runtime-constant value at all exit
314// points except for IgnoreRI. If so, return the returned value.
Chris Lattnerd64152a2003-12-14 23:57:39 +0000315//
Duncan Sandsd50e9e22010-06-26 12:53:31 +0000316static Value *getCommonReturnValue(ReturnInst *IgnoreRI, CallInst *CI) {
317 Function *F = CI->getParent()->getParent();
Chris Lattnerd64152a2003-12-14 23:57:39 +0000318 Value *ReturnedValue = 0;
319
Chris Lattnerb5d84d12010-08-31 21:21:25 +0000320 for (Function::iterator BBI = F->begin(), E = F->end(); BBI != E; ++BBI) {
321 ReturnInst *RI = dyn_cast<ReturnInst>(BBI->getTerminator());
322 if (RI == 0 || RI == IgnoreRI) continue;
Chris Lattnerd64152a2003-12-14 23:57:39 +0000323
Chris Lattnerb5d84d12010-08-31 21:21:25 +0000324 // We can only perform this transformation if the value returned is
325 // evaluatable at the start of the initial invocation of the function,
326 // instead of at the end of the evaluation.
327 //
328 Value *RetOp = RI->getOperand(0);
329 if (!isDynamicConstant(RetOp, CI, RI))
330 return 0;
Chris Lattnerd64152a2003-12-14 23:57:39 +0000331
Chris Lattnerb5d84d12010-08-31 21:21:25 +0000332 if (ReturnedValue && RetOp != ReturnedValue)
333 return 0; // Cannot transform if differing values are returned.
334 ReturnedValue = RetOp;
335 }
Chris Lattnerd64152a2003-12-14 23:57:39 +0000336 return ReturnedValue;
337}
Chris Lattner7152da32003-12-08 05:34:54 +0000338
Chris Lattner543d6222003-12-08 23:19:26 +0000339/// CanTransformAccumulatorRecursion - If the specified instruction can be
340/// transformed using accumulator recursion elimination, return the constant
341/// which is the start of the accumulator value. Otherwise return null.
342///
343Value *TailCallElim::CanTransformAccumulatorRecursion(Instruction *I,
344 CallInst *CI) {
Duncan Sands24080a92010-07-10 20:31:42 +0000345 if (!I->isAssociative() || !I->isCommutative()) return 0;
Chris Lattner543d6222003-12-08 23:19:26 +0000346 assert(I->getNumOperands() == 2 &&
Duncan Sands24080a92010-07-10 20:31:42 +0000347 "Associative/commutative operations should have 2 args!");
Chris Lattner543d6222003-12-08 23:19:26 +0000348
Chris Lattnerb5d84d12010-08-31 21:21:25 +0000349 // Exactly one operand should be the result of the call instruction.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +0000350 if ((I->getOperand(0) == CI && I->getOperand(1) == CI) ||
351 (I->getOperand(0) != CI && I->getOperand(1) != CI))
Chris Lattner543d6222003-12-08 23:19:26 +0000352 return 0;
353
354 // The only user of this instruction we allow is a single return instruction.
355 if (!I->hasOneUse() || !isa<ReturnInst>(I->use_back()))
356 return 0;
357
358 // Ok, now we have to check all of the other return instructions in this
359 // function. If they return non-constants or differing values, then we cannot
360 // transform the function safely.
Chris Lattnerd64152a2003-12-14 23:57:39 +0000361 return getCommonReturnValue(cast<ReturnInst>(I->use_back()), CI);
Chris Lattner543d6222003-12-08 23:19:26 +0000362}
363
Evan Chengc3f507f2011-01-29 04:46:23 +0000364static Instruction *FirstNonDbg(BasicBlock::iterator I) {
365 while (isa<DbgInfoIntrinsic>(I))
366 ++I;
367 return &*I;
368}
369
370CallInst*
371TailCallElim::FindTRECandidate(Instruction *TI,
372 bool CannotTailCallElimCallsMarkedTail) {
373 BasicBlock *BB = TI->getParent();
Chris Lattner7152da32003-12-08 05:34:54 +0000374 Function *F = BB->getParent();
375
Evan Chengc3f507f2011-01-29 04:46:23 +0000376 if (&BB->front() == TI) // Make sure there is something before the terminator.
377 return 0;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000378
Chris Lattner7152da32003-12-08 05:34:54 +0000379 // Scan backwards from the return, checking to see if there is a tail call in
380 // this block. If so, set CI to it.
Evan Chengc3f507f2011-01-29 04:46:23 +0000381 CallInst *CI = 0;
382 BasicBlock::iterator BBI = TI;
383 while (true) {
Chris Lattner7152da32003-12-08 05:34:54 +0000384 CI = dyn_cast<CallInst>(BBI);
385 if (CI && CI->getCalledFunction() == F)
386 break;
387
388 if (BBI == BB->begin())
Evan Chengc3f507f2011-01-29 04:46:23 +0000389 return 0; // Didn't find a potential tail call.
Chris Lattner7152da32003-12-08 05:34:54 +0000390 --BBI;
391 }
392
Chris Lattnerce869ee2005-08-07 04:27:41 +0000393 // If this call is marked as a tail call, and if there are dynamic allocas in
394 // the function, we cannot perform this optimization.
395 if (CI->isTailCall() && CannotTailCallElimCallsMarkedTail)
Evan Chengc3f507f2011-01-29 04:46:23 +0000396 return 0;
Chris Lattnerce869ee2005-08-07 04:27:41 +0000397
Dan Gohmanea25b482010-04-16 15:57:50 +0000398 // As a special case, detect code like this:
399 // double fabs(double f) { return __builtin_fabs(f); } // a 'fabs' call
400 // and disable this xform in this case, because the code generator will
401 // lower the call to fabs into inline code.
Nadav Rotema94d6e82012-07-24 10:51:42 +0000402 if (BB == &F->getEntryBlock() &&
Evan Chengc3f507f2011-01-29 04:46:23 +0000403 FirstNonDbg(BB->front()) == CI &&
404 FirstNonDbg(llvm::next(BB->begin())) == TI &&
Chandler Carruthd5003ca2012-05-04 00:58:03 +0000405 callIsSmall(CI)) {
Dan Gohmanea25b482010-04-16 15:57:50 +0000406 // A single-block function with just a call and a return. Check that
407 // the arguments match.
408 CallSite::arg_iterator I = CallSite(CI).arg_begin(),
409 E = CallSite(CI).arg_end();
410 Function::arg_iterator FI = F->arg_begin(),
411 FE = F->arg_end();
412 for (; I != E && FI != FE; ++I, ++FI)
413 if (*I != &*FI) break;
414 if (I == E && FI == FE)
Evan Chengc3f507f2011-01-29 04:46:23 +0000415 return 0;
Dan Gohmanea25b482010-04-16 15:57:50 +0000416 }
417
Evan Chengc3f507f2011-01-29 04:46:23 +0000418 return CI;
419}
420
421bool TailCallElim::EliminateRecursiveTailCall(CallInst *CI, ReturnInst *Ret,
422 BasicBlock *&OldEntry,
423 bool &TailCallsAreMarkedTail,
424 SmallVector<PHINode*, 8> &ArgumentPHIs,
425 bool CannotTailCallElimCallsMarkedTail) {
Duncan Sands24080a92010-07-10 20:31:42 +0000426 // If we are introducing accumulator recursion to eliminate operations after
427 // the call instruction that are both associative and commutative, the initial
428 // value for the accumulator is placed in this variable. If this value is set
429 // then we actually perform accumulator recursion elimination instead of
Duncan Sandsd0d3ccc2010-07-13 15:41:41 +0000430 // simple tail recursion elimination. If the operation is an LLVM instruction
431 // (eg: "add") then it is recorded in AccumulatorRecursionInstr. If not, then
432 // we are handling the case when the return instruction returns a constant C
433 // which is different to the constant returned by other return instructions
434 // (which is recorded in AccumulatorRecursionEliminationInitVal). This is a
435 // special case of accumulator recursion, the operation being "return C".
Chris Lattner543d6222003-12-08 23:19:26 +0000436 Value *AccumulatorRecursionEliminationInitVal = 0;
437 Instruction *AccumulatorRecursionInstr = 0;
438
Chris Lattner7152da32003-12-08 05:34:54 +0000439 // Ok, we found a potential tail call. We can currently only transform the
440 // tail call if all of the instructions between the call and the return are
441 // movable to above the call itself, leaving the call next to the return.
442 // Check that this is the case now.
Evan Chengc3f507f2011-01-29 04:46:23 +0000443 BasicBlock::iterator BBI = CI;
444 for (++BBI; &*BBI != Ret; ++BBI) {
Chris Lattnerb5d84d12010-08-31 21:21:25 +0000445 if (CanMoveAboveCall(BBI, CI)) continue;
Nadav Rotema94d6e82012-07-24 10:51:42 +0000446
Chris Lattnerb5d84d12010-08-31 21:21:25 +0000447 // If we can't move the instruction above the call, it might be because it
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000448 // is an associative and commutative operation that could be transformed
Chris Lattnerb5d84d12010-08-31 21:21:25 +0000449 // using accumulator recursion elimination. Check to see if this is the
450 // case, and if so, remember the initial accumulator value for later.
451 if ((AccumulatorRecursionEliminationInitVal =
452 CanTransformAccumulatorRecursion(BBI, CI))) {
453 // Yes, this is accumulator recursion. Remember which instruction
454 // accumulates.
455 AccumulatorRecursionInstr = BBI;
456 } else {
457 return false; // Otherwise, we cannot eliminate the tail recursion!
Chris Lattner543d6222003-12-08 23:19:26 +0000458 }
Chris Lattnerb5d84d12010-08-31 21:21:25 +0000459 }
Chris Lattner7152da32003-12-08 05:34:54 +0000460
461 // We can only transform call/return pairs that either ignore the return value
Chris Lattnerd64152a2003-12-14 23:57:39 +0000462 // of the call and return void, ignore the value of the call and return a
463 // constant, return the value returned by the tail call, or that are being
464 // accumulator recursion variable eliminated.
Devang Patel826c4912008-03-11 17:33:32 +0000465 if (Ret->getNumOperands() == 1 && Ret->getReturnValue() != CI &&
Chris Lattner3b5f4502005-11-05 08:21:11 +0000466 !isa<UndefValue>(Ret->getReturnValue()) &&
Chris Lattnerd64152a2003-12-14 23:57:39 +0000467 AccumulatorRecursionEliminationInitVal == 0 &&
Duncan Sandsd0d3ccc2010-07-13 15:41:41 +0000468 !getCommonReturnValue(0, CI)) {
469 // One case remains that we are able to handle: the current return
470 // instruction returns a constant, and all other return instructions
471 // return a different constant.
472 if (!isDynamicConstant(Ret->getReturnValue(), CI, Ret))
473 return false; // Current return instruction does not return a constant.
474 // Check that all other return instructions return a common constant. If
475 // so, record it in AccumulatorRecursionEliminationInitVal.
476 AccumulatorRecursionEliminationInitVal = getCommonReturnValue(Ret, CI);
477 if (!AccumulatorRecursionEliminationInitVal)
478 return false;
479 }
Chris Lattner7152da32003-12-08 05:34:54 +0000480
Evan Chengc3f507f2011-01-29 04:46:23 +0000481 BasicBlock *BB = Ret->getParent();
482 Function *F = BB->getParent();
483
Chris Lattner7152da32003-12-08 05:34:54 +0000484 // OK! We can transform this tail call. If this is the first one found,
485 // create the new entry block, allowing us to branch back to the old entry.
486 if (OldEntry == 0) {
487 OldEntry = &F->getEntryBlock();
Owen Anderson1d0be152009-08-13 21:58:54 +0000488 BasicBlock *NewEntry = BasicBlock::Create(F->getContext(), "", F, OldEntry);
Chris Lattner6934a042007-02-11 01:23:03 +0000489 NewEntry->takeName(OldEntry);
490 OldEntry->setName("tailrecurse");
Gabor Greif051a9502008-04-06 20:25:17 +0000491 BranchInst::Create(OldEntry, NewEntry);
Misha Brukmanfd939082005-04-21 23:48:37 +0000492
Chris Lattnerce869ee2005-08-07 04:27:41 +0000493 // If this tail call is marked 'tail' and if there are any allocas in the
494 // entry block, move them up to the new entry block.
495 TailCallsAreMarkedTail = CI->isTailCall();
496 if (TailCallsAreMarkedTail)
497 // Move all fixed sized allocas from OldEntry to NewEntry.
498 for (BasicBlock::iterator OEBI = OldEntry->begin(), E = OldEntry->end(),
499 NEBI = NewEntry->begin(); OEBI != E; )
500 if (AllocaInst *AI = dyn_cast<AllocaInst>(OEBI++))
501 if (isa<ConstantInt>(AI->getArraySize()))
Chris Lattner4bc5f802005-08-08 19:11:57 +0000502 AI->moveBefore(NEBI);
Chris Lattnerce869ee2005-08-07 04:27:41 +0000503
Chris Lattner7152da32003-12-08 05:34:54 +0000504 // Now that we have created a new block, which jumps to the entry
505 // block, insert a PHI node for each argument of the function.
506 // For now, we initialize each PHI to only have the real arguments
507 // which are passed in.
508 Instruction *InsertPos = OldEntry->begin();
Chris Lattner7f78f212005-05-09 23:51:13 +0000509 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
510 I != E; ++I) {
Jay Foad3ecfc862011-03-30 11:28:46 +0000511 PHINode *PN = PHINode::Create(I->getType(), 2,
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000512 I->getName() + ".tr", InsertPos);
Chris Lattner7152da32003-12-08 05:34:54 +0000513 I->replaceAllUsesWith(PN); // Everyone use the PHI node now!
514 PN->addIncoming(I, NewEntry);
515 ArgumentPHIs.push_back(PN);
516 }
517 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000518
Chris Lattnerce869ee2005-08-07 04:27:41 +0000519 // If this function has self recursive calls in the tail position where some
520 // are marked tail and some are not, only transform one flavor or another. We
521 // have to choose whether we move allocas in the entry block to the new entry
522 // block or not, so we can't make a good choice for both. NOTE: We could do
523 // slightly better here in the case that the function has no entry block
524 // allocas.
525 if (TailCallsAreMarkedTail && !CI->isTailCall())
526 return false;
527
Chris Lattner7152da32003-12-08 05:34:54 +0000528 // Ok, now that we know we have a pseudo-entry block WITH all of the
529 // required PHI nodes, add entries into the PHI node for the actual
530 // parameters passed into the tail-recursive call.
Gabor Greif407014f2010-06-24 00:48:48 +0000531 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i)
Gabor Greifde9f5452010-06-24 00:44:01 +0000532 ArgumentPHIs[i]->addIncoming(CI->getArgOperand(i), BB);
Misha Brukmanfd939082005-04-21 23:48:37 +0000533
Chris Lattner543d6222003-12-08 23:19:26 +0000534 // If we are introducing an accumulator variable to eliminate the recursion,
535 // do so now. Note that we _know_ that no subsequent tail recursion
536 // eliminations will happen on this function because of the way the
537 // accumulator recursion predicate is set up.
538 //
539 if (AccumulatorRecursionEliminationInitVal) {
540 Instruction *AccRecInstr = AccumulatorRecursionInstr;
541 // Start by inserting a new PHI node for the accumulator.
Jay Foadd8b4fb42011-03-30 11:19:20 +0000542 pred_iterator PB = pred_begin(OldEntry), PE = pred_end(OldEntry);
Duncan Sandsd0d3ccc2010-07-13 15:41:41 +0000543 PHINode *AccPN =
544 PHINode::Create(AccumulatorRecursionEliminationInitVal->getType(),
Jay Foad3ecfc862011-03-30 11:28:46 +0000545 std::distance(PB, PE) + 1,
Duncan Sandsd0d3ccc2010-07-13 15:41:41 +0000546 "accumulator.tr", OldEntry->begin());
Chris Lattner543d6222003-12-08 23:19:26 +0000547
548 // Loop over all of the predecessors of the tail recursion block. For the
549 // real entry into the function we seed the PHI with the initial value,
550 // computed earlier. For any other existing branches to this block (due to
551 // other tail recursions eliminated) the accumulator is not modified.
552 // Because we haven't added the branch in the current block to OldEntry yet,
553 // it will not show up as a predecessor.
Jay Foadd8b4fb42011-03-30 11:19:20 +0000554 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greifa8b9df72010-07-12 10:36:48 +0000555 BasicBlock *P = *PI;
556 if (P == &F->getEntryBlock())
557 AccPN->addIncoming(AccumulatorRecursionEliminationInitVal, P);
Chris Lattner543d6222003-12-08 23:19:26 +0000558 else
Gabor Greifa8b9df72010-07-12 10:36:48 +0000559 AccPN->addIncoming(AccPN, P);
Chris Lattner543d6222003-12-08 23:19:26 +0000560 }
561
Duncan Sandsd0d3ccc2010-07-13 15:41:41 +0000562 if (AccRecInstr) {
563 // Add an incoming argument for the current block, which is computed by
564 // our associative and commutative accumulator instruction.
565 AccPN->addIncoming(AccRecInstr, BB);
Chris Lattner543d6222003-12-08 23:19:26 +0000566
Duncan Sandsd0d3ccc2010-07-13 15:41:41 +0000567 // Next, rewrite the accumulator recursion instruction so that it does not
568 // use the result of the call anymore, instead, use the PHI node we just
569 // inserted.
570 AccRecInstr->setOperand(AccRecInstr->getOperand(0) != CI, AccPN);
571 } else {
572 // Add an incoming argument for the current block, which is just the
573 // constant returned by the current return instruction.
574 AccPN->addIncoming(Ret->getReturnValue(), BB);
575 }
Chris Lattner543d6222003-12-08 23:19:26 +0000576
577 // Finally, rewrite any return instructions in the program to return the PHI
578 // node instead of the "initval" that they do currently. This loop will
579 // actually rewrite the return value we are destroying, but that's ok.
580 for (Function::iterator BBI = F->begin(), E = F->end(); BBI != E; ++BBI)
581 if (ReturnInst *RI = dyn_cast<ReturnInst>(BBI->getTerminator()))
582 RI->setOperand(0, AccPN);
583 ++NumAccumAdded;
584 }
585
Chris Lattner7152da32003-12-08 05:34:54 +0000586 // Now that all of the PHI nodes are in place, remove the call and
587 // ret instructions, replacing them with an unconditional branch.
Devang Patel81199d22011-04-28 18:43:39 +0000588 BranchInst *NewBI = BranchInst::Create(OldEntry, Ret);
589 NewBI->setDebugLoc(CI->getDebugLoc());
590
Chris Lattner7152da32003-12-08 05:34:54 +0000591 BB->getInstList().erase(Ret); // Remove return.
592 BB->getInstList().erase(CI); // Remove call.
Chris Lattner543d6222003-12-08 23:19:26 +0000593 ++NumEliminated;
Chris Lattner7152da32003-12-08 05:34:54 +0000594 return true;
595}
Evan Chengc3f507f2011-01-29 04:46:23 +0000596
597bool TailCallElim::FoldReturnAndProcessPred(BasicBlock *BB,
598 ReturnInst *Ret, BasicBlock *&OldEntry,
599 bool &TailCallsAreMarkedTail,
600 SmallVector<PHINode*, 8> &ArgumentPHIs,
601 bool CannotTailCallElimCallsMarkedTail) {
602 bool Change = false;
603
604 // If the return block contains nothing but the return and PHI's,
605 // there might be an opportunity to duplicate the return in its
606 // predecessors and perform TRC there. Look for predecessors that end
607 // in unconditional branch and recursive call(s).
608 SmallVector<BranchInst*, 8> UncondBranchPreds;
609 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
610 BasicBlock *Pred = *PI;
611 TerminatorInst *PTI = Pred->getTerminator();
612 if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
613 if (BI->isUnconditional())
614 UncondBranchPreds.push_back(BI);
615 }
616
617 while (!UncondBranchPreds.empty()) {
618 BranchInst *BI = UncondBranchPreds.pop_back_val();
619 BasicBlock *Pred = BI->getParent();
620 if (CallInst *CI = FindTRECandidate(BI, CannotTailCallElimCallsMarkedTail)){
621 DEBUG(dbgs() << "FOLDING: " << *BB
622 << "INTO UNCOND BRANCH PRED: " << *Pred);
623 EliminateRecursiveTailCall(CI, FoldReturnIntoUncondBranch(Ret, BB, Pred),
624 OldEntry, TailCallsAreMarkedTail, ArgumentPHIs,
625 CannotTailCallElimCallsMarkedTail);
Evan Cheng60f5ad42011-01-29 04:53:35 +0000626 ++NumRetDuped;
Evan Chengc3f507f2011-01-29 04:46:23 +0000627 Change = true;
628 }
629 }
630
631 return Change;
632}
633
634bool TailCallElim::ProcessReturningBlock(ReturnInst *Ret, BasicBlock *&OldEntry,
635 bool &TailCallsAreMarkedTail,
636 SmallVector<PHINode*, 8> &ArgumentPHIs,
637 bool CannotTailCallElimCallsMarkedTail) {
638 CallInst *CI = FindTRECandidate(Ret, CannotTailCallElimCallsMarkedTail);
639 if (!CI)
640 return false;
641
642 return EliminateRecursiveTailCall(CI, Ret, OldEntry, TailCallsAreMarkedTail,
643 ArgumentPHIs,
644 CannotTailCallElimCallsMarkedTail);
645}