Teach TailRecursionElimination to consider 'nocapture' when deciding whether
[oota-llvm.git] / lib / Transforms / Scalar / TailRecursionElimination.cpp
1 //===- TailRecursionElimination.cpp - Eliminate Tail Calls ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // 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:
14 //
15 //  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).
18 //  2. This pass transforms functions that are prevented from being tail
19 //     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.
22 //  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.
28 //  4. If it can prove that callees do not access their caller stack frame,
29 //     they are marked as eligible for tail call elimination (by the code
30 //     generator).
31 //
32 // 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.
39 //  2. Tail recursion is only performed if the call immediately precedes the
40 //     return instruction.  It's possible that there could be a jump between
41 //     the call and the return.
42 //  3. There can be intervening operations between the call and the return that
43 //     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.
48 //  4. The algorithm we use to detect if callees access their caller stack
49 //     frames is very primitive.
50 //
51 //===----------------------------------------------------------------------===//
52
53 #define DEBUG_TYPE "tailcallelim"
54 #include "llvm/Transforms/Scalar.h"
55 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
56 #include "llvm/Transforms/Utils/Local.h"
57 #include "llvm/Constants.h"
58 #include "llvm/DerivedTypes.h"
59 #include "llvm/Function.h"
60 #include "llvm/Instructions.h"
61 #include "llvm/IntrinsicInst.h"
62 #include "llvm/Module.h"
63 #include "llvm/Pass.h"
64 #include "llvm/Analysis/CaptureTracking.h"
65 #include "llvm/Analysis/InlineCost.h"
66 #include "llvm/Analysis/InstructionSimplify.h"
67 #include "llvm/Analysis/Loads.h"
68 #include "llvm/Support/CallSite.h"
69 #include "llvm/Support/CFG.h"
70 #include "llvm/Support/Debug.h"
71 #include "llvm/Support/raw_ostream.h"
72 #include "llvm/Support/ValueHandle.h"
73 #include "llvm/ADT/Statistic.h"
74 #include "llvm/ADT/STLExtras.h"
75 using namespace llvm;
76
77 STATISTIC(NumEliminated, "Number of tail calls removed");
78 STATISTIC(NumRetDuped,   "Number of return duplicated");
79 STATISTIC(NumAccumAdded, "Number of accumulators introduced");
80
81 namespace {
82   struct TailCallElim : public FunctionPass {
83     static char ID; // Pass identification, replacement for typeid
84     TailCallElim() : FunctionPass(ID) {
85       initializeTailCallElimPass(*PassRegistry::getPassRegistry());
86     }
87
88     virtual bool runOnFunction(Function &F);
89
90   private:
91     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);
103     bool ProcessReturningBlock(ReturnInst *RI, BasicBlock *&OldEntry,
104                                bool &TailCallsAreMarkedTail,
105                                SmallVector<PHINode*, 8> &ArgumentPHIs,
106                                bool CannotTailCallElimCallsMarkedTail);
107     bool CanMoveAboveCall(Instruction *I, CallInst *CI);
108     Value *CanTransformAccumulatorRecursion(Instruction *I, CallInst *CI);
109   };
110 }
111
112 char TailCallElim::ID = 0;
113 INITIALIZE_PASS(TailCallElim, "tailcallelim",
114                 "Tail Call Elimination", false, false)
115
116 // Public interface to the TailCallElimination pass
117 FunctionPass *llvm::createTailCallEliminationPass() {
118   return new TailCallElim();
119 }
120
121 /// 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.
124 static 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());
133 }
134
135 struct AllocaCaptureTracker : public CaptureTracker {
136   AllocaCaptureTracker() : Captured(false) {}
137
138   void tooManyUses() { Captured = true; }
139
140   bool shouldExplore(Use *U) {
141     Value *V = U->get();
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 };
160
161 bool 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;
167   bool TailCallsAreMarkedTail = false;
168   SmallVector<PHINode*, 8> ArgumentPHIs;
169   bool MadeChange = false;
170   bool FunctionContainsEscapingAllocas = false;
171
172   // CanTRETailMarkedCall - If false, we cannot perform TRE on tail calls
173   // marked with the 'tail' attribute, because doing so would cause the stack
174   // size to increase (real TRE would deallocate variable sized allocas, TRE
175   // doesn't).
176   bool CanTRETailMarkedCall = true;
177
178   // 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(I, &ACT);
185         if (ACT.Captured)
186           return false;
187       }
188     }
189   }
190
191   // Second pass, change any tail recursive calls to loops.
192   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,
195                                           ArgumentPHIs, !CanTRETailMarkedCall);
196       if (!Change && BB->getFirstNonPHIOrDbg() == Ret)
197         Change = FoldReturnAndProcessPred(BB, Ret, OldEntry,
198                                           TailCallsAreMarkedTail, ArgumentPHIs,
199                                           !CanTRETailMarkedCall);
200       MadeChange |= Change;
201     }
202   }
203
204   // 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()) {
210     for (unsigned i = 0, e = ArgumentPHIs.size(); i != e; ++i) {
211       PHINode *PN = ArgumentPHIs[i];
212
213       // If the PHI Node is a dynamic constant, replace it with the value it is.
214       if (Value *PNV = SimplifyInstruction(PN)) {
215         PN->replaceAllUsesWith(PNV);
216         PN->eraseFromParent();
217       }
218     }
219   }
220
221   // 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
226   if (!FunctionContainsEscapingAllocas && !F.callsFunctionThatReturnsTwice())
227     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)
229         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           }
235
236   return MadeChange;
237 }
238
239 /// 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 ///
243 bool 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.
246   if (I->mayHaveSideEffects())  // This also handles volatile loads.
247     return false;
248
249   if (LoadInst *L = dyn_cast<LoadInst>(I)) {
250     // 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() ||
257           !isSafeToLoadUnconditionally(L->getPointerOperand(), L,
258                                        L->getAlignment()))
259         return false;
260     }
261   }
262
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
274 // 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 //
281 static bool isDynamicConstant(Value *V, CallInst *CI, ReturnInst *RI) {
282   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();
290     for (Function::arg_iterator AI = F->arg_begin(); &*AI != Arg; ++AI)
291       ++ArgNo;
292
293     // 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.
296     if (CI->getArgOperand(ArgNo) == Arg)
297       return true;
298   }
299
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
308   // 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
313 // tail call consistently returns the same runtime-constant value at all exit
314 // points except for IgnoreRI.  If so, return the returned value.
315 //
316 static Value *getCommonReturnValue(ReturnInst *IgnoreRI, CallInst *CI) {
317   Function *F = CI->getParent()->getParent();
318   Value *ReturnedValue = 0;
319
320   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;
323
324     // 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;
331
332     if (ReturnedValue && RetOp != ReturnedValue)
333       return 0;     // Cannot transform if differing values are returned.
334     ReturnedValue = RetOp;
335   }
336   return ReturnedValue;
337 }
338
339 /// 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 ///
343 Value *TailCallElim::CanTransformAccumulatorRecursion(Instruction *I,
344                                                       CallInst *CI) {
345   if (!I->isAssociative() || !I->isCommutative()) return 0;
346   assert(I->getNumOperands() == 2 &&
347          "Associative/commutative operations should have 2 args!");
348
349   // Exactly one operand should be the result of the call instruction.
350   if ((I->getOperand(0) == CI && I->getOperand(1) == CI) ||
351       (I->getOperand(0) != CI && I->getOperand(1) != CI))
352     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.
361   return getCommonReturnValue(cast<ReturnInst>(I->use_back()), CI);
362 }
363
364 static Instruction *FirstNonDbg(BasicBlock::iterator I) {
365   while (isa<DbgInfoIntrinsic>(I))
366     ++I;
367   return &*I;
368 }
369
370 CallInst*
371 TailCallElim::FindTRECandidate(Instruction *TI,
372                                bool CannotTailCallElimCallsMarkedTail) {
373   BasicBlock *BB = TI->getParent();
374   Function *F = BB->getParent();
375
376   if (&BB->front() == TI) // Make sure there is something before the terminator.
377     return 0;
378
379   // Scan backwards from the return, checking to see if there is a tail call in
380   // this block.  If so, set CI to it.
381   CallInst *CI = 0;
382   BasicBlock::iterator BBI = TI;
383   while (true) {
384     CI = dyn_cast<CallInst>(BBI);
385     if (CI && CI->getCalledFunction() == F)
386       break;
387
388     if (BBI == BB->begin())
389       return 0;          // Didn't find a potential tail call.
390     --BBI;
391   }
392
393   // 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)
396     return 0;
397
398   // 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.
402   if (BB == &F->getEntryBlock() &&
403       FirstNonDbg(BB->front()) == CI &&
404       FirstNonDbg(llvm::next(BB->begin())) == TI &&
405       callIsSmall(CI)) {
406     // 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)
415       return 0;
416   }
417
418   return CI;
419 }
420
421 bool TailCallElim::EliminateRecursiveTailCall(CallInst *CI, ReturnInst *Ret,
422                                        BasicBlock *&OldEntry,
423                                        bool &TailCallsAreMarkedTail,
424                                        SmallVector<PHINode*, 8> &ArgumentPHIs,
425                                        bool CannotTailCallElimCallsMarkedTail) {
426   // 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
430   // 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".
436   Value *AccumulatorRecursionEliminationInitVal = 0;
437   Instruction *AccumulatorRecursionInstr = 0;
438
439   // 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.
443   BasicBlock::iterator BBI = CI;
444   for (++BBI; &*BBI != Ret; ++BBI) {
445     if (CanMoveAboveCall(BBI, CI)) continue;
446
447     // If we can't move the instruction above the call, it might be because it
448     // is an associative and commutative operation that could be transformed
449     // 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!
458     }
459   }
460
461   // We can only transform call/return pairs that either ignore the return value
462   // 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.
465   if (Ret->getNumOperands() == 1 && Ret->getReturnValue() != CI &&
466       !isa<UndefValue>(Ret->getReturnValue()) &&
467       AccumulatorRecursionEliminationInitVal == 0 &&
468       !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   }
480
481   BasicBlock *BB = Ret->getParent();
482   Function *F = BB->getParent();
483
484   // 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();
488     BasicBlock *NewEntry = BasicBlock::Create(F->getContext(), "", F, OldEntry);
489     NewEntry->takeName(OldEntry);
490     OldEntry->setName("tailrecurse");
491     BranchInst::Create(OldEntry, NewEntry);
492
493     // 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()))
502             AI->moveBefore(NEBI);
503
504     // 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();
509     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
510          I != E; ++I) {
511       PHINode *PN = PHINode::Create(I->getType(), 2,
512                                     I->getName() + ".tr", InsertPos);
513       I->replaceAllUsesWith(PN); // Everyone use the PHI node now!
514       PN->addIncoming(I, NewEntry);
515       ArgumentPHIs.push_back(PN);
516     }
517   }
518
519   // 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
528   // 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.
531   for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i)
532     ArgumentPHIs[i]->addIncoming(CI->getArgOperand(i), BB);
533
534   // 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.
542     pred_iterator PB = pred_begin(OldEntry), PE = pred_end(OldEntry);
543     PHINode *AccPN =
544       PHINode::Create(AccumulatorRecursionEliminationInitVal->getType(),
545                       std::distance(PB, PE) + 1,
546                       "accumulator.tr", OldEntry->begin());
547
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.
554     for (pred_iterator PI = PB; PI != PE; ++PI) {
555       BasicBlock *P = *PI;
556       if (P == &F->getEntryBlock())
557         AccPN->addIncoming(AccumulatorRecursionEliminationInitVal, P);
558       else
559         AccPN->addIncoming(AccPN, P);
560     }
561
562     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);
566
567       // 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     }
576
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
586   // Now that all of the PHI nodes are in place, remove the call and
587   // ret instructions, replacing them with an unconditional branch.
588   BranchInst *NewBI = BranchInst::Create(OldEntry, Ret);
589   NewBI->setDebugLoc(CI->getDebugLoc());
590
591   BB->getInstList().erase(Ret);  // Remove return.
592   BB->getInstList().erase(CI);   // Remove call.
593   ++NumEliminated;
594   return true;
595 }
596
597 bool 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);
626       ++NumRetDuped;
627       Change = true;
628     }
629   }
630
631   return Change;
632 }
633
634 bool 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 }