blob: 8b2fb1b3f9b5b8abe8b71150361ffe2947c536ea [file] [log] [blame]
Chris Lattner2e9014c2003-09-20 05:03:31 +00001//===- TailRecursionElimination.cpp - Eliminate Tail Calls ----------------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-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 Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner2e9014c2003-09-20 05:03:31 +00009//
Chris Lattnera7b6f3a2003-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 Lattner2e9014c2003-09-20 05:03:31 +000014//
Chris Lattnera7b6f3a2003-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 Lattner198e6202003-12-08 23:19:26 +000018// 2. This pass transforms functions that are prevented from being tail
Duncan Sands82b21c02010-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 Lattner884e8242003-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 Lewycky50912722009-11-07 07:10:01 +000028// 4. If it can prove that callees do not access their caller stack frame,
Chris Lattnerbfc796f2005-05-09 23:51:13 +000029// they are marked as eligible for tail call elimination (by the code
30// generator).
Chris Lattner2e9014c2003-09-20 05:03:31 +000031//
Chris Lattnera7b6f3a2003-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 Lattner0ab5e2c2011-04-15 05:18:47 +000039// 2. Tail recursion is only performed if the call immediately precedes the
Chris Lattnera7b6f3a2003-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 Lattner884e8242003-12-14 23:57:39 +000042// 3. There can be intervening operations between the call and the return that
Chris Lattnera7b6f3a2003-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 Lattnerbfc796f2005-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 Lattner2e9014c2003-09-20 05:03:31 +000050//
51//===----------------------------------------------------------------------===//
52
Chris Lattner00160852003-09-20 05:14:13 +000053#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000054#include "llvm/ADT/STLExtras.h"
Michael Gottesmanb40db262013-07-11 04:40:01 +000055#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000056#include "llvm/ADT/Statistic.h"
57#include "llvm/Analysis/CaptureTracking.h"
58#include "llvm/Analysis/InlineCost.h"
59#include "llvm/Analysis/InstructionSimplify.h"
60#include "llvm/Analysis/Loads.h"
Chandler Carruth0ba8db42013-01-22 11:26:02 +000061#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruth1305dc32014-03-04 11:45:46 +000062#include "llvm/IR/CFG.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000063#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000064#include "llvm/IR/Constants.h"
65#include "llvm/IR/DerivedTypes.h"
66#include "llvm/IR/Function.h"
67#include "llvm/IR/Instructions.h"
68#include "llvm/IR/IntrinsicInst.h"
69#include "llvm/IR/Module.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000070#include "llvm/IR/ValueHandle.h"
Chris Lattner2e9014c2003-09-20 05:03:31 +000071#include "llvm/Pass.h"
Evan Chengd983eba2011-01-29 04:46:23 +000072#include "llvm/Support/Debug.h"
Francois Pichet326e4a22011-01-29 20:06:16 +000073#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000074#include "llvm/Transforms/Utils/BasicBlockUtils.h"
75#include "llvm/Transforms/Utils/Local.h"
Chris Lattner2af51722003-11-20 18:25:24 +000076using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000077
Chandler Carruth964daaa2014-04-22 02:55:47 +000078#define DEBUG_TYPE "tailcallelim"
79
Chris Lattner79a42ac2006-12-19 21:40:18 +000080STATISTIC(NumEliminated, "Number of tail calls removed");
Evan Cheng73c291782011-01-29 04:53:35 +000081STATISTIC(NumRetDuped, "Number of return duplicated");
Chris Lattner79a42ac2006-12-19 21:40:18 +000082STATISTIC(NumAccumAdded, "Number of accumulators introduced");
Chris Lattner2e9014c2003-09-20 05:03:31 +000083
Chris Lattner79a42ac2006-12-19 21:40:18 +000084namespace {
Chris Lattner2dd09db2009-09-02 06:11:42 +000085 struct TailCallElim : public FunctionPass {
Chandler Carruth0ba8db42013-01-22 11:26:02 +000086 const TargetTransformInfo *TTI;
87
Nick Lewyckye7da2d62007-05-06 13:37:16 +000088 static char ID; // Pass identification, replacement for typeid
Owen Anderson6c18d1a2010-10-19 17:21:58 +000089 TailCallElim() : FunctionPass(ID) {
90 initializeTailCallElimPass(*PassRegistry::getPassRegistry());
91 }
Devang Patel09f162c2007-05-01 21:15:47 +000092
Craig Topper3e4c6972014-03-05 09:10:37 +000093 void getAnalysisUsage(AnalysisUsage &AU) const override;
Chandler Carruth0ba8db42013-01-22 11:26:02 +000094
Craig Topper3e4c6972014-03-05 09:10:37 +000095 bool runOnFunction(Function &F) override;
Chris Lattnera7b6f3a2003-12-08 05:34:54 +000096
97 private:
Evan Chengd983eba2011-01-29 04:46:23 +000098 CallInst *FindTRECandidate(Instruction *I,
99 bool CannotTailCallElimCallsMarkedTail);
100 bool EliminateRecursiveTailCall(CallInst *CI, ReturnInst *Ret,
101 BasicBlock *&OldEntry,
102 bool &TailCallsAreMarkedTail,
Craig Topperb94011f2013-07-14 04:42:23 +0000103 SmallVectorImpl<PHINode *> &ArgumentPHIs,
Evan Chengd983eba2011-01-29 04:46:23 +0000104 bool CannotTailCallElimCallsMarkedTail);
105 bool FoldReturnAndProcessPred(BasicBlock *BB,
106 ReturnInst *Ret, BasicBlock *&OldEntry,
107 bool &TailCallsAreMarkedTail,
Craig Topperb94011f2013-07-14 04:42:23 +0000108 SmallVectorImpl<PHINode *> &ArgumentPHIs,
Evan Chengd983eba2011-01-29 04:46:23 +0000109 bool CannotTailCallElimCallsMarkedTail);
Chris Lattnera7b6f3a2003-12-08 05:34:54 +0000110 bool ProcessReturningBlock(ReturnInst *RI, BasicBlock *&OldEntry,
Chris Lattnerf4dd8c42005-08-07 04:27:41 +0000111 bool &TailCallsAreMarkedTail,
Craig Topperb94011f2013-07-14 04:42:23 +0000112 SmallVectorImpl<PHINode *> &ArgumentPHIs,
Chris Lattnerf4dd8c42005-08-07 04:27:41 +0000113 bool CannotTailCallElimCallsMarkedTail);
Chris Lattnera7b6f3a2003-12-08 05:34:54 +0000114 bool CanMoveAboveCall(Instruction *I, CallInst *CI);
Chris Lattner198e6202003-12-08 23:19:26 +0000115 Value *CanTransformAccumulatorRecursion(Instruction *I, CallInst *CI);
Chris Lattner2e9014c2003-09-20 05:03:31 +0000116 };
Chris Lattner2e9014c2003-09-20 05:03:31 +0000117}
118
Dan Gohmand78c4002008-05-13 00:00:25 +0000119char TailCallElim::ID = 0;
Chandler Carruth0ba8db42013-01-22 11:26:02 +0000120INITIALIZE_PASS_BEGIN(TailCallElim, "tailcallelim",
121 "Tail Call Elimination", false, false)
122INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
123INITIALIZE_PASS_END(TailCallElim, "tailcallelim",
124 "Tail Call Elimination", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000125
Brian Gaeke960707c2003-11-11 22:41:34 +0000126// Public interface to the TailCallElimination pass
Chris Lattner2af51722003-11-20 18:25:24 +0000127FunctionPass *llvm::createTailCallEliminationPass() {
128 return new TailCallElim();
129}
Chris Lattner00160852003-09-20 05:14:13 +0000130
Chandler Carruth0ba8db42013-01-22 11:26:02 +0000131void TailCallElim::getAnalysisUsage(AnalysisUsage &AU) const {
132 AU.addRequired<TargetTransformInfo>();
133}
134
Michael Gottesmanb40db262013-07-11 04:40:01 +0000135/// CanTRE - Scan the specified basic block for alloca instructions.
136/// If it contains any that are variable-sized or not in the entry block,
137/// returns false.
138static bool CanTRE(AllocaInst *AI) {
139 // Because of PR962, we don't TRE allocas outside the entry block.
140
141 // If this alloca is in the body of the function, or if it is a variable
142 // sized allocation, we cannot tail call eliminate calls marked 'tail'
143 // with this mechanism.
144 BasicBlock *BB = AI->getParent();
145 return BB == &BB->getParent()->getEntryBlock() &&
146 isa<ConstantInt>(AI->getArraySize());
Nick Lewycky9b669b32009-11-07 07:42:38 +0000147}
148
Benjamin Kramer328da332013-07-24 16:12:08 +0000149namespace {
Michael Gottesmanb40db262013-07-11 04:40:01 +0000150struct AllocaCaptureTracker : public CaptureTracker {
151 AllocaCaptureTracker() : Captured(false) {}
Chris Lattnerf4dd8c42005-08-07 04:27:41 +0000152
Craig Topper73156022014-03-02 09:09:27 +0000153 void tooManyUses() override { Captured = true; }
Michael Gottesmanb40db262013-07-11 04:40:01 +0000154
Chandler Carruth64e9aa52014-03-05 10:21:48 +0000155 bool shouldExplore(const Use *U) override {
Michael Gottesmanb40db262013-07-11 04:40:01 +0000156 Value *V = U->getUser();
157 if (isa<CallInst>(V) || isa<InvokeInst>(V))
158 UsesAlloca.insert(V);
159 return true;
160 }
161
Chandler Carruth64e9aa52014-03-05 10:21:48 +0000162 bool captured(const Use *U) override {
Michael Gottesmanb40db262013-07-11 04:40:01 +0000163 if (isa<ReturnInst>(U->getUser()))
164 return false;
165 Captured = true;
166 return true;
167 }
168
169 bool Captured;
Benjamin Kramer328da332013-07-24 16:12:08 +0000170 SmallPtrSet<const Value *, 16> UsesAlloca;
Michael Gottesmanb40db262013-07-11 04:40:01 +0000171};
Benjamin Kramer328da332013-07-24 16:12:08 +0000172} // end anonymous namespace
Chris Lattnerbfc796f2005-05-09 23:51:13 +0000173
Chris Lattner2e9014c2003-09-20 05:03:31 +0000174bool TailCallElim::runOnFunction(Function &F) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +0000175 if (skipOptnoneFunction(F))
176 return false;
177
Chris Lattner2e9014c2003-09-20 05:03:31 +0000178 // If this function is a varargs function, we won't be able to PHI the args
179 // right, so don't even try to convert it...
180 if (F.getFunctionType()->isVarArg()) return false;
181
Chandler Carruth0ba8db42013-01-22 11:26:02 +0000182 TTI = &getAnalysis<TargetTransformInfo>();
Craig Topperf40110f2014-04-25 05:29:35 +0000183 BasicBlock *OldEntry = nullptr;
Chris Lattnerf4dd8c42005-08-07 04:27:41 +0000184 bool TailCallsAreMarkedTail = false;
Nick Lewycky50912722009-11-07 07:10:01 +0000185 SmallVector<PHINode*, 8> ArgumentPHIs;
Chris Lattner2e9014c2003-09-20 05:03:31 +0000186 bool MadeChange = false;
Chris Lattnerbfc796f2005-05-09 23:51:13 +0000187
Michael Gottesmanb40db262013-07-11 04:40:01 +0000188 // CanTRETailMarkedCall - If false, we cannot perform TRE on tail calls
Chris Lattnerf4dd8c42005-08-07 04:27:41 +0000189 // marked with the 'tail' attribute, because doing so would cause the stack
Michael Gottesmanb40db262013-07-11 04:40:01 +0000190 // size to increase (real TRE would deallocate variable sized allocas, TRE
Chris Lattnerf4dd8c42005-08-07 04:27:41 +0000191 // doesn't).
Michael Gottesmanb40db262013-07-11 04:40:01 +0000192 bool CanTRETailMarkedCall = true;
Chris Lattnerf4dd8c42005-08-07 04:27:41 +0000193
Michael Gottesmanb40db262013-07-11 04:40:01 +0000194 // Find calls that can be marked tail.
195 AllocaCaptureTracker ACT;
196 for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB) {
197 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
198 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
199 CanTRETailMarkedCall &= CanTRE(AI);
200 PointerMayBeCaptured(AI, &ACT);
201 // If any allocas are captured, exit.
202 if (ACT.Captured)
203 return false;
204 }
205 }
Chris Lattnerbfc796f2005-05-09 23:51:13 +0000206 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000207
Reid Kleckner9b2cc642014-04-21 20:48:47 +0000208 // If any byval or inalloca args are captured, exit. They are also allocated
209 // in our stack frame.
210 for (Argument &Arg : F.args()) {
211 if (Arg.hasByValOrInAllocaAttr())
212 PointerMayBeCaptured(&Arg, &ACT);
213 if (ACT.Captured)
214 return false;
215 }
216
Michael Gottesmanb40db262013-07-11 04:40:01 +0000217 // Second pass, change any tail recursive calls to loops.
218 //
219 // FIXME: The code generator produces really bad code when an 'escaping
220 // alloca' is changed from being a static alloca to being a dynamic alloca.
221 // Until this is resolved, disable this transformation if that would ever
222 // happen. This bug is PR962.
223 if (ACT.UsesAlloca.empty()) {
224 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
225 if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB->getTerminator())) {
226 bool Change = ProcessReturningBlock(Ret, OldEntry, TailCallsAreMarkedTail,
227 ArgumentPHIs, !CanTRETailMarkedCall);
228 if (!Change && BB->getFirstNonPHIOrDbg() == Ret)
229 Change = FoldReturnAndProcessPred(BB, Ret, OldEntry,
230 TailCallsAreMarkedTail, ArgumentPHIs,
231 !CanTRETailMarkedCall);
232 MadeChange |= Change;
233 }
Evan Chengd983eba2011-01-29 04:46:23 +0000234 }
235 }
Chris Lattnerf4dd8c42005-08-07 04:27:41 +0000236
Chris Lattner50663a12003-12-08 23:37:35 +0000237 // If we eliminated any tail recursions, it's possible that we inserted some
238 // silly PHI nodes which just merge an initial value (the incoming operand)
239 // with themselves. Check to see if we did and clean up our mess if so. This
240 // occurs when a function passes an argument straight through to its tail
241 // call.
242 if (!ArgumentPHIs.empty()) {
Chris Lattner50663a12003-12-08 23:37:35 +0000243 for (unsigned i = 0, e = ArgumentPHIs.size(); i != e; ++i) {
244 PHINode *PN = ArgumentPHIs[i];
Chris Lattner50663a12003-12-08 23:37:35 +0000245
246 // If the PHI Node is a dynamic constant, replace it with the value it is.
Duncan Sands63704952010-11-16 17:41:24 +0000247 if (Value *PNV = SimplifyInstruction(PN)) {
Chris Lattnerf4dd8c42005-08-07 04:27:41 +0000248 PN->replaceAllUsesWith(PNV);
249 PN->eraseFromParent();
Chris Lattner50663a12003-12-08 23:37:35 +0000250 }
251 }
252 }
253
Michael Gottesmanb40db262013-07-11 04:40:01 +0000254 // At this point, we know that the function does not have any captured
255 // allocas. If additionally the function does not call setjmp, mark all calls
256 // in the function that do not access stack memory with the tail keyword. This
257 // implies ensuring that there does not exist any path from a call that takes
258 // in an alloca but does not capture it and the call which we wish to mark
259 // with "tail".
260 if (!F.callsFunctionThatReturnsTwice()) {
261 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
262 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
Argyrios Kyrtzidis54ff5e82012-10-22 18:16:14 +0000263 if (CallInst *CI = dyn_cast<CallInst>(I)) {
Michael Gottesmanb40db262013-07-11 04:40:01 +0000264 if (!ACT.UsesAlloca.count(CI)) {
265 CI->setTailCall();
266 MadeChange = true;
267 }
Argyrios Kyrtzidis54ff5e82012-10-22 18:16:14 +0000268 }
Michael Gottesmanb40db262013-07-11 04:40:01 +0000269 }
270 }
271 }
Chris Lattnerbfc796f2005-05-09 23:51:13 +0000272
Chris Lattner2e9014c2003-09-20 05:03:31 +0000273 return MadeChange;
274}
Chris Lattnera7b6f3a2003-12-08 05:34:54 +0000275
Argyrios Kyrtzidis54ff5e82012-10-22 18:16:14 +0000276
Chris Lattner198e6202003-12-08 23:19:26 +0000277/// CanMoveAboveCall - Return true if it is safe to move the specified
278/// instruction from after the call to before the call, assuming that all
279/// instructions between the call and this instruction are movable.
280///
Chris Lattnera7b6f3a2003-12-08 05:34:54 +0000281bool TailCallElim::CanMoveAboveCall(Instruction *I, CallInst *CI) {
282 // FIXME: We can move load/store/call/free instructions above the call if the
283 // call does not mod/ref the memory location being processed.
Chris Lattner5ca41972009-06-19 04:22:16 +0000284 if (I->mayHaveSideEffects()) // This also handles volatile loads.
Chris Lattnera7b6f3a2003-12-08 05:34:54 +0000285 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000286
Nick Lewycky50912722009-11-07 07:10:01 +0000287 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
Chris Lattner5ca41972009-06-19 04:22:16 +0000288 // Loads may always be moved above calls without side effects.
289 if (CI->mayHaveSideEffects()) {
290 // Non-volatile loads may be moved above a call with side effects if it
291 // does not write to memory and the load provably won't trap.
292 // FIXME: Writes to memory only matter if they may alias the pointer
293 // being loaded from.
294 if (CI->mayWriteToMemory() ||
Bob Wilson56600a12010-01-30 04:42:39 +0000295 !isSafeToLoadUnconditionally(L->getPointerOperand(), L,
296 L->getAlignment()))
Chris Lattner5ca41972009-06-19 04:22:16 +0000297 return false;
298 }
299 }
Chris Lattnera7b6f3a2003-12-08 05:34:54 +0000300
301 // Otherwise, if this is a side-effect free instruction, check to make sure
302 // that it does not use the return value of the call. If it doesn't use the
303 // return value of the call, it must only use things that are defined before
304 // the call, or movable instructions between the call and the instruction
305 // itself.
306 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
307 if (I->getOperand(i) == CI)
308 return false;
309 return true;
310}
311
Chris Lattner884e8242003-12-14 23:57:39 +0000312// isDynamicConstant - Return true if the specified value is the same when the
313// return would exit as it was when the initial iteration of the recursive
314// function was executed.
315//
316// We currently handle static constants and arguments that are not modified as
317// part of the recursion.
318//
Nick Lewyckyb9397262009-11-07 21:10:15 +0000319static bool isDynamicConstant(Value *V, CallInst *CI, ReturnInst *RI) {
Chris Lattner884e8242003-12-14 23:57:39 +0000320 if (isa<Constant>(V)) return true; // Static constants are always dyn consts
321
322 // Check to see if this is an immutable argument, if so, the value
323 // will be available to initialize the accumulator.
324 if (Argument *Arg = dyn_cast<Argument>(V)) {
325 // Figure out which argument number this is...
326 unsigned ArgNo = 0;
327 Function *F = CI->getParent()->getParent();
Chris Lattner531f9e92005-03-15 04:54:21 +0000328 for (Function::arg_iterator AI = F->arg_begin(); &*AI != Arg; ++AI)
Chris Lattner884e8242003-12-14 23:57:39 +0000329 ++ArgNo;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000330
Chris Lattner884e8242003-12-14 23:57:39 +0000331 // If we are passing this argument into call as the corresponding
332 // argument operand, then the argument is dynamically constant.
333 // Otherwise, we cannot transform this function safely.
Gabor Greif4a39b842010-06-24 00:44:01 +0000334 if (CI->getArgOperand(ArgNo) == Arg)
Chris Lattner884e8242003-12-14 23:57:39 +0000335 return true;
336 }
Nick Lewyckyb9397262009-11-07 21:10:15 +0000337
338 // Switch cases are always constant integers. If the value is being switched
339 // on and the return is only reachable from one of its cases, it's
340 // effectively constant.
341 if (BasicBlock *UniquePred = RI->getParent()->getUniquePredecessor())
342 if (SwitchInst *SI = dyn_cast<SwitchInst>(UniquePred->getTerminator()))
343 if (SI->getCondition() == V)
344 return SI->getDefaultDest() != RI->getParent();
345
Chris Lattner884e8242003-12-14 23:57:39 +0000346 // Not a constant or immutable argument, we can't safely transform.
347 return false;
348}
349
350// getCommonReturnValue - Check to see if the function containing the specified
Duncan Sands3a5cb692010-06-26 12:53:31 +0000351// tail call consistently returns the same runtime-constant value at all exit
352// points except for IgnoreRI. If so, return the returned value.
Chris Lattner884e8242003-12-14 23:57:39 +0000353//
Duncan Sands3a5cb692010-06-26 12:53:31 +0000354static Value *getCommonReturnValue(ReturnInst *IgnoreRI, CallInst *CI) {
355 Function *F = CI->getParent()->getParent();
Craig Topperf40110f2014-04-25 05:29:35 +0000356 Value *ReturnedValue = nullptr;
Chris Lattner884e8242003-12-14 23:57:39 +0000357
Chris Lattnerdaca6f32010-08-31 21:21:25 +0000358 for (Function::iterator BBI = F->begin(), E = F->end(); BBI != E; ++BBI) {
359 ReturnInst *RI = dyn_cast<ReturnInst>(BBI->getTerminator());
Craig Topperf40110f2014-04-25 05:29:35 +0000360 if (RI == nullptr || RI == IgnoreRI) continue;
Chris Lattner884e8242003-12-14 23:57:39 +0000361
Chris Lattnerdaca6f32010-08-31 21:21:25 +0000362 // We can only perform this transformation if the value returned is
363 // evaluatable at the start of the initial invocation of the function,
364 // instead of at the end of the evaluation.
365 //
366 Value *RetOp = RI->getOperand(0);
367 if (!isDynamicConstant(RetOp, CI, RI))
Craig Topperf40110f2014-04-25 05:29:35 +0000368 return nullptr;
Chris Lattner884e8242003-12-14 23:57:39 +0000369
Chris Lattnerdaca6f32010-08-31 21:21:25 +0000370 if (ReturnedValue && RetOp != ReturnedValue)
Craig Topperf40110f2014-04-25 05:29:35 +0000371 return nullptr; // Cannot transform if differing values are returned.
Chris Lattnerdaca6f32010-08-31 21:21:25 +0000372 ReturnedValue = RetOp;
373 }
Chris Lattner884e8242003-12-14 23:57:39 +0000374 return ReturnedValue;
375}
Chris Lattnera7b6f3a2003-12-08 05:34:54 +0000376
Chris Lattner198e6202003-12-08 23:19:26 +0000377/// CanTransformAccumulatorRecursion - If the specified instruction can be
378/// transformed using accumulator recursion elimination, return the constant
379/// which is the start of the accumulator value. Otherwise return null.
380///
381Value *TailCallElim::CanTransformAccumulatorRecursion(Instruction *I,
382 CallInst *CI) {
Craig Topperf40110f2014-04-25 05:29:35 +0000383 if (!I->isAssociative() || !I->isCommutative()) return nullptr;
Chris Lattner198e6202003-12-08 23:19:26 +0000384 assert(I->getNumOperands() == 2 &&
Duncan Sands82b21c02010-07-10 20:31:42 +0000385 "Associative/commutative operations should have 2 args!");
Chris Lattner198e6202003-12-08 23:19:26 +0000386
Chris Lattnerdaca6f32010-08-31 21:21:25 +0000387 // Exactly one operand should be the result of the call instruction.
Anton Korobeynikov1bfd1212008-02-20 11:26:25 +0000388 if ((I->getOperand(0) == CI && I->getOperand(1) == CI) ||
389 (I->getOperand(0) != CI && I->getOperand(1) != CI))
Craig Topperf40110f2014-04-25 05:29:35 +0000390 return nullptr;
Chris Lattner198e6202003-12-08 23:19:26 +0000391
392 // The only user of this instruction we allow is a single return instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000393 if (!I->hasOneUse() || !isa<ReturnInst>(I->user_back()))
Craig Topperf40110f2014-04-25 05:29:35 +0000394 return nullptr;
Chris Lattner198e6202003-12-08 23:19:26 +0000395
396 // Ok, now we have to check all of the other return instructions in this
397 // function. If they return non-constants or differing values, then we cannot
398 // transform the function safely.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000399 return getCommonReturnValue(cast<ReturnInst>(I->user_back()), CI);
Chris Lattner198e6202003-12-08 23:19:26 +0000400}
401
Evan Chengd983eba2011-01-29 04:46:23 +0000402static Instruction *FirstNonDbg(BasicBlock::iterator I) {
403 while (isa<DbgInfoIntrinsic>(I))
404 ++I;
405 return &*I;
406}
407
408CallInst*
409TailCallElim::FindTRECandidate(Instruction *TI,
410 bool CannotTailCallElimCallsMarkedTail) {
411 BasicBlock *BB = TI->getParent();
Chris Lattnera7b6f3a2003-12-08 05:34:54 +0000412 Function *F = BB->getParent();
413
Evan Chengd983eba2011-01-29 04:46:23 +0000414 if (&BB->front() == TI) // Make sure there is something before the terminator.
Craig Topperf40110f2014-04-25 05:29:35 +0000415 return nullptr;
Nadav Rotem465834c2012-07-24 10:51:42 +0000416
Chris Lattnera7b6f3a2003-12-08 05:34:54 +0000417 // Scan backwards from the return, checking to see if there is a tail call in
418 // this block. If so, set CI to it.
Craig Topperf40110f2014-04-25 05:29:35 +0000419 CallInst *CI = nullptr;
Evan Chengd983eba2011-01-29 04:46:23 +0000420 BasicBlock::iterator BBI = TI;
421 while (true) {
Chris Lattnera7b6f3a2003-12-08 05:34:54 +0000422 CI = dyn_cast<CallInst>(BBI);
423 if (CI && CI->getCalledFunction() == F)
424 break;
425
426 if (BBI == BB->begin())
Craig Topperf40110f2014-04-25 05:29:35 +0000427 return nullptr; // Didn't find a potential tail call.
Chris Lattnera7b6f3a2003-12-08 05:34:54 +0000428 --BBI;
429 }
430
Chris Lattnerf4dd8c42005-08-07 04:27:41 +0000431 // If this call is marked as a tail call, and if there are dynamic allocas in
432 // the function, we cannot perform this optimization.
433 if (CI->isTailCall() && CannotTailCallElimCallsMarkedTail)
Craig Topperf40110f2014-04-25 05:29:35 +0000434 return nullptr;
Chris Lattnerf4dd8c42005-08-07 04:27:41 +0000435
Dan Gohman99e53272010-04-16 15:57:50 +0000436 // As a special case, detect code like this:
437 // double fabs(double f) { return __builtin_fabs(f); } // a 'fabs' call
438 // and disable this xform in this case, because the code generator will
439 // lower the call to fabs into inline code.
Nadav Rotem465834c2012-07-24 10:51:42 +0000440 if (BB == &F->getEntryBlock() &&
Evan Chengd983eba2011-01-29 04:46:23 +0000441 FirstNonDbg(BB->front()) == CI &&
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000442 FirstNonDbg(std::next(BB->begin())) == TI &&
Chandler Carruth0ba8db42013-01-22 11:26:02 +0000443 CI->getCalledFunction() &&
444 !TTI->isLoweredToCall(CI->getCalledFunction())) {
Dan Gohman99e53272010-04-16 15:57:50 +0000445 // A single-block function with just a call and a return. Check that
446 // the arguments match.
447 CallSite::arg_iterator I = CallSite(CI).arg_begin(),
448 E = CallSite(CI).arg_end();
449 Function::arg_iterator FI = F->arg_begin(),
450 FE = F->arg_end();
451 for (; I != E && FI != FE; ++I, ++FI)
452 if (*I != &*FI) break;
453 if (I == E && FI == FE)
Craig Topperf40110f2014-04-25 05:29:35 +0000454 return nullptr;
Dan Gohman99e53272010-04-16 15:57:50 +0000455 }
456
Evan Chengd983eba2011-01-29 04:46:23 +0000457 return CI;
458}
459
460bool TailCallElim::EliminateRecursiveTailCall(CallInst *CI, ReturnInst *Ret,
461 BasicBlock *&OldEntry,
462 bool &TailCallsAreMarkedTail,
Craig Topperb94011f2013-07-14 04:42:23 +0000463 SmallVectorImpl<PHINode *> &ArgumentPHIs,
Evan Chengd983eba2011-01-29 04:46:23 +0000464 bool CannotTailCallElimCallsMarkedTail) {
Duncan Sands82b21c02010-07-10 20:31:42 +0000465 // If we are introducing accumulator recursion to eliminate operations after
466 // the call instruction that are both associative and commutative, the initial
467 // value for the accumulator is placed in this variable. If this value is set
468 // then we actually perform accumulator recursion elimination instead of
Duncan Sandsf88a2842010-07-13 15:41:41 +0000469 // simple tail recursion elimination. If the operation is an LLVM instruction
470 // (eg: "add") then it is recorded in AccumulatorRecursionInstr. If not, then
471 // we are handling the case when the return instruction returns a constant C
472 // which is different to the constant returned by other return instructions
473 // (which is recorded in AccumulatorRecursionEliminationInitVal). This is a
474 // special case of accumulator recursion, the operation being "return C".
Craig Topperf40110f2014-04-25 05:29:35 +0000475 Value *AccumulatorRecursionEliminationInitVal = nullptr;
476 Instruction *AccumulatorRecursionInstr = nullptr;
Chris Lattner198e6202003-12-08 23:19:26 +0000477
Chris Lattnera7b6f3a2003-12-08 05:34:54 +0000478 // Ok, we found a potential tail call. We can currently only transform the
479 // tail call if all of the instructions between the call and the return are
480 // movable to above the call itself, leaving the call next to the return.
481 // Check that this is the case now.
Evan Chengd983eba2011-01-29 04:46:23 +0000482 BasicBlock::iterator BBI = CI;
483 for (++BBI; &*BBI != Ret; ++BBI) {
Chris Lattnerdaca6f32010-08-31 21:21:25 +0000484 if (CanMoveAboveCall(BBI, CI)) continue;
Nadav Rotem465834c2012-07-24 10:51:42 +0000485
Chris Lattnerdaca6f32010-08-31 21:21:25 +0000486 // If we can't move the instruction above the call, it might be because it
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000487 // is an associative and commutative operation that could be transformed
Chris Lattnerdaca6f32010-08-31 21:21:25 +0000488 // using accumulator recursion elimination. Check to see if this is the
489 // case, and if so, remember the initial accumulator value for later.
490 if ((AccumulatorRecursionEliminationInitVal =
491 CanTransformAccumulatorRecursion(BBI, CI))) {
492 // Yes, this is accumulator recursion. Remember which instruction
493 // accumulates.
494 AccumulatorRecursionInstr = BBI;
495 } else {
496 return false; // Otherwise, we cannot eliminate the tail recursion!
Chris Lattner198e6202003-12-08 23:19:26 +0000497 }
Chris Lattnerdaca6f32010-08-31 21:21:25 +0000498 }
Chris Lattnera7b6f3a2003-12-08 05:34:54 +0000499
500 // We can only transform call/return pairs that either ignore the return value
Chris Lattner884e8242003-12-14 23:57:39 +0000501 // of the call and return void, ignore the value of the call and return a
502 // constant, return the value returned by the tail call, or that are being
503 // accumulator recursion variable eliminated.
Devang Patel5663fe62008-03-11 17:33:32 +0000504 if (Ret->getNumOperands() == 1 && Ret->getReturnValue() != CI &&
Chris Lattner16b29e92005-11-05 08:21:11 +0000505 !isa<UndefValue>(Ret->getReturnValue()) &&
Craig Topperf40110f2014-04-25 05:29:35 +0000506 AccumulatorRecursionEliminationInitVal == nullptr &&
507 !getCommonReturnValue(nullptr, CI)) {
Duncan Sandsf88a2842010-07-13 15:41:41 +0000508 // One case remains that we are able to handle: the current return
509 // instruction returns a constant, and all other return instructions
510 // return a different constant.
511 if (!isDynamicConstant(Ret->getReturnValue(), CI, Ret))
512 return false; // Current return instruction does not return a constant.
513 // Check that all other return instructions return a common constant. If
514 // so, record it in AccumulatorRecursionEliminationInitVal.
515 AccumulatorRecursionEliminationInitVal = getCommonReturnValue(Ret, CI);
516 if (!AccumulatorRecursionEliminationInitVal)
517 return false;
518 }
Chris Lattnera7b6f3a2003-12-08 05:34:54 +0000519
Evan Chengd983eba2011-01-29 04:46:23 +0000520 BasicBlock *BB = Ret->getParent();
521 Function *F = BB->getParent();
522
Chris Lattnera7b6f3a2003-12-08 05:34:54 +0000523 // OK! We can transform this tail call. If this is the first one found,
524 // create the new entry block, allowing us to branch back to the old entry.
Craig Topperf40110f2014-04-25 05:29:35 +0000525 if (!OldEntry) {
Chris Lattnera7b6f3a2003-12-08 05:34:54 +0000526 OldEntry = &F->getEntryBlock();
Owen Anderson55f1c092009-08-13 21:58:54 +0000527 BasicBlock *NewEntry = BasicBlock::Create(F->getContext(), "", F, OldEntry);
Chris Lattner6e0123b2007-02-11 01:23:03 +0000528 NewEntry->takeName(OldEntry);
529 OldEntry->setName("tailrecurse");
Gabor Greife9ecc682008-04-06 20:25:17 +0000530 BranchInst::Create(OldEntry, NewEntry);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000531
Chris Lattnerf4dd8c42005-08-07 04:27:41 +0000532 // If this tail call is marked 'tail' and if there are any allocas in the
533 // entry block, move them up to the new entry block.
534 TailCallsAreMarkedTail = CI->isTailCall();
535 if (TailCallsAreMarkedTail)
536 // Move all fixed sized allocas from OldEntry to NewEntry.
537 for (BasicBlock::iterator OEBI = OldEntry->begin(), E = OldEntry->end(),
538 NEBI = NewEntry->begin(); OEBI != E; )
539 if (AllocaInst *AI = dyn_cast<AllocaInst>(OEBI++))
540 if (isa<ConstantInt>(AI->getArraySize()))
Chris Lattner9f269e42005-08-08 19:11:57 +0000541 AI->moveBefore(NEBI);
Chris Lattnerf4dd8c42005-08-07 04:27:41 +0000542
Chris Lattnera7b6f3a2003-12-08 05:34:54 +0000543 // Now that we have created a new block, which jumps to the entry
544 // block, insert a PHI node for each argument of the function.
545 // For now, we initialize each PHI to only have the real arguments
546 // which are passed in.
547 Instruction *InsertPos = OldEntry->begin();
Chris Lattnerbfc796f2005-05-09 23:51:13 +0000548 for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
549 I != E; ++I) {
Jay Foad52131342011-03-30 11:28:46 +0000550 PHINode *PN = PHINode::Create(I->getType(), 2,
Gabor Greif697e94c2008-05-15 10:04:30 +0000551 I->getName() + ".tr", InsertPos);
Chris Lattnera7b6f3a2003-12-08 05:34:54 +0000552 I->replaceAllUsesWith(PN); // Everyone use the PHI node now!
553 PN->addIncoming(I, NewEntry);
554 ArgumentPHIs.push_back(PN);
555 }
556 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000557
Chris Lattnerf4dd8c42005-08-07 04:27:41 +0000558 // If this function has self recursive calls in the tail position where some
559 // are marked tail and some are not, only transform one flavor or another. We
560 // have to choose whether we move allocas in the entry block to the new entry
561 // block or not, so we can't make a good choice for both. NOTE: We could do
562 // slightly better here in the case that the function has no entry block
563 // allocas.
564 if (TailCallsAreMarkedTail && !CI->isTailCall())
565 return false;
566
Chris Lattnera7b6f3a2003-12-08 05:34:54 +0000567 // Ok, now that we know we have a pseudo-entry block WITH all of the
568 // required PHI nodes, add entries into the PHI node for the actual
569 // parameters passed into the tail-recursive call.
Gabor Greif0f607092010-06-24 00:48:48 +0000570 for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i)
Gabor Greif4a39b842010-06-24 00:44:01 +0000571 ArgumentPHIs[i]->addIncoming(CI->getArgOperand(i), BB);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000572
Chris Lattner198e6202003-12-08 23:19:26 +0000573 // If we are introducing an accumulator variable to eliminate the recursion,
574 // do so now. Note that we _know_ that no subsequent tail recursion
575 // eliminations will happen on this function because of the way the
576 // accumulator recursion predicate is set up.
577 //
578 if (AccumulatorRecursionEliminationInitVal) {
579 Instruction *AccRecInstr = AccumulatorRecursionInstr;
580 // Start by inserting a new PHI node for the accumulator.
Jay Foade0938d82011-03-30 11:19:20 +0000581 pred_iterator PB = pred_begin(OldEntry), PE = pred_end(OldEntry);
Duncan Sandsf88a2842010-07-13 15:41:41 +0000582 PHINode *AccPN =
583 PHINode::Create(AccumulatorRecursionEliminationInitVal->getType(),
Jay Foad52131342011-03-30 11:28:46 +0000584 std::distance(PB, PE) + 1,
Duncan Sandsf88a2842010-07-13 15:41:41 +0000585 "accumulator.tr", OldEntry->begin());
Chris Lattner198e6202003-12-08 23:19:26 +0000586
587 // Loop over all of the predecessors of the tail recursion block. For the
588 // real entry into the function we seed the PHI with the initial value,
589 // computed earlier. For any other existing branches to this block (due to
590 // other tail recursions eliminated) the accumulator is not modified.
591 // Because we haven't added the branch in the current block to OldEntry yet,
592 // it will not show up as a predecessor.
Jay Foade0938d82011-03-30 11:19:20 +0000593 for (pred_iterator PI = PB; PI != PE; ++PI) {
Gabor Greif2a464d72010-07-12 10:36:48 +0000594 BasicBlock *P = *PI;
595 if (P == &F->getEntryBlock())
596 AccPN->addIncoming(AccumulatorRecursionEliminationInitVal, P);
Chris Lattner198e6202003-12-08 23:19:26 +0000597 else
Gabor Greif2a464d72010-07-12 10:36:48 +0000598 AccPN->addIncoming(AccPN, P);
Chris Lattner198e6202003-12-08 23:19:26 +0000599 }
600
Duncan Sandsf88a2842010-07-13 15:41:41 +0000601 if (AccRecInstr) {
602 // Add an incoming argument for the current block, which is computed by
603 // our associative and commutative accumulator instruction.
604 AccPN->addIncoming(AccRecInstr, BB);
Chris Lattner198e6202003-12-08 23:19:26 +0000605
Duncan Sandsf88a2842010-07-13 15:41:41 +0000606 // Next, rewrite the accumulator recursion instruction so that it does not
607 // use the result of the call anymore, instead, use the PHI node we just
608 // inserted.
609 AccRecInstr->setOperand(AccRecInstr->getOperand(0) != CI, AccPN);
610 } else {
611 // Add an incoming argument for the current block, which is just the
612 // constant returned by the current return instruction.
613 AccPN->addIncoming(Ret->getReturnValue(), BB);
614 }
Chris Lattner198e6202003-12-08 23:19:26 +0000615
616 // Finally, rewrite any return instructions in the program to return the PHI
617 // node instead of the "initval" that they do currently. This loop will
618 // actually rewrite the return value we are destroying, but that's ok.
619 for (Function::iterator BBI = F->begin(), E = F->end(); BBI != E; ++BBI)
620 if (ReturnInst *RI = dyn_cast<ReturnInst>(BBI->getTerminator()))
621 RI->setOperand(0, AccPN);
622 ++NumAccumAdded;
623 }
624
Chris Lattnera7b6f3a2003-12-08 05:34:54 +0000625 // Now that all of the PHI nodes are in place, remove the call and
626 // ret instructions, replacing them with an unconditional branch.
Devang Patel33d87d92011-04-28 18:43:39 +0000627 BranchInst *NewBI = BranchInst::Create(OldEntry, Ret);
628 NewBI->setDebugLoc(CI->getDebugLoc());
629
Chris Lattnera7b6f3a2003-12-08 05:34:54 +0000630 BB->getInstList().erase(Ret); // Remove return.
631 BB->getInstList().erase(CI); // Remove call.
Chris Lattner198e6202003-12-08 23:19:26 +0000632 ++NumEliminated;
Chris Lattnera7b6f3a2003-12-08 05:34:54 +0000633 return true;
634}
Evan Chengd983eba2011-01-29 04:46:23 +0000635
636bool TailCallElim::FoldReturnAndProcessPred(BasicBlock *BB,
637 ReturnInst *Ret, BasicBlock *&OldEntry,
638 bool &TailCallsAreMarkedTail,
Craig Topperb94011f2013-07-14 04:42:23 +0000639 SmallVectorImpl<PHINode *> &ArgumentPHIs,
Evan Chengd983eba2011-01-29 04:46:23 +0000640 bool CannotTailCallElimCallsMarkedTail) {
641 bool Change = false;
642
643 // If the return block contains nothing but the return and PHI's,
644 // there might be an opportunity to duplicate the return in its
645 // predecessors and perform TRC there. Look for predecessors that end
646 // in unconditional branch and recursive call(s).
647 SmallVector<BranchInst*, 8> UncondBranchPreds;
648 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
649 BasicBlock *Pred = *PI;
650 TerminatorInst *PTI = Pred->getTerminator();
651 if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
652 if (BI->isUnconditional())
653 UncondBranchPreds.push_back(BI);
654 }
655
656 while (!UncondBranchPreds.empty()) {
657 BranchInst *BI = UncondBranchPreds.pop_back_val();
658 BasicBlock *Pred = BI->getParent();
659 if (CallInst *CI = FindTRECandidate(BI, CannotTailCallElimCallsMarkedTail)){
660 DEBUG(dbgs() << "FOLDING: " << *BB
661 << "INTO UNCOND BRANCH PRED: " << *Pred);
662 EliminateRecursiveTailCall(CI, FoldReturnIntoUncondBranch(Ret, BB, Pred),
663 OldEntry, TailCallsAreMarkedTail, ArgumentPHIs,
664 CannotTailCallElimCallsMarkedTail);
Evan Cheng73c291782011-01-29 04:53:35 +0000665 ++NumRetDuped;
Evan Chengd983eba2011-01-29 04:46:23 +0000666 Change = true;
667 }
668 }
669
670 return Change;
671}
672
Craig Topperb94011f2013-07-14 04:42:23 +0000673bool
674TailCallElim::ProcessReturningBlock(ReturnInst *Ret, BasicBlock *&OldEntry,
675 bool &TailCallsAreMarkedTail,
676 SmallVectorImpl<PHINode *> &ArgumentPHIs,
677 bool CannotTailCallElimCallsMarkedTail) {
Evan Chengd983eba2011-01-29 04:46:23 +0000678 CallInst *CI = FindTRECandidate(Ret, CannotTailCallElimCallsMarkedTail);
679 if (!CI)
680 return false;
681
682 return EliminateRecursiveTailCall(CI, Ret, OldEntry, TailCallsAreMarkedTail,
683 ArgumentPHIs,
684 CannotTailCallElimCallsMarkedTail);
685}