LLVM API Documentation

TailRecursionElimination.cpp
Go to the documentation of this file.
00001 //===- TailRecursionElimination.cpp - Eliminate Tail Calls ----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file transforms calls of the current function (self recursion) followed
00011 // by a return instruction with a branch to the entry of the function, creating
00012 // a loop.  This pass also implements the following extensions to the basic
00013 // algorithm:
00014 //
00015 //  1. Trivial instructions between the call and return do not prevent the
00016 //     transformation from taking place, though currently the analysis cannot
00017 //     support moving any really useful instructions (only dead ones).
00018 //  2. This pass transforms functions that are prevented from being tail
00019 //     recursive by an associative and commutative expression to use an
00020 //     accumulator variable, thus compiling the typical naive factorial or
00021 //     'fib' implementation into efficient code.
00022 //  3. TRE is performed if the function returns void, if the return
00023 //     returns the result returned by the call, or if the function returns a
00024 //     run-time constant on all exits from the function.  It is possible, though
00025 //     unlikely, that the return returns something else (like constant 0), and
00026 //     can still be TRE'd.  It can be TRE'd if ALL OTHER return instructions in
00027 //     the function return the exact same value.
00028 //  4. If it can prove that callees do not access their caller stack frame,
00029 //     they are marked as eligible for tail call elimination (by the code
00030 //     generator).
00031 //
00032 // There are several improvements that could be made:
00033 //
00034 //  1. If the function has any alloca instructions, these instructions will be
00035 //     moved out of the entry block of the function, causing them to be
00036 //     evaluated each time through the tail recursion.  Safely keeping allocas
00037 //     in the entry block requires analysis to proves that the tail-called
00038 //     function does not read or write the stack object.
00039 //  2. Tail recursion is only performed if the call immediately precedes the
00040 //     return instruction.  It's possible that there could be a jump between
00041 //     the call and the return.
00042 //  3. There can be intervening operations between the call and the return that
00043 //     prevent the TRE from occurring.  For example, there could be GEP's and
00044 //     stores to memory that will not be read or written by the call.  This
00045 //     requires some substantial analysis (such as with DSA) to prove safe to
00046 //     move ahead of the call, but doing so could allow many more TREs to be
00047 //     performed, for example in TreeAdd/TreeAlloc from the treeadd benchmark.
00048 //  4. The algorithm we use to detect if callees access their caller stack
00049 //     frames is very primitive.
00050 //
00051 //===----------------------------------------------------------------------===//
00052 
00053 #define DEBUG_TYPE "tailcallelim"
00054 #include "llvm/Transforms/Scalar.h"
00055 #include "llvm/ADT/STLExtras.h"
00056 #include "llvm/ADT/SmallPtrSet.h"
00057 #include "llvm/ADT/Statistic.h"
00058 #include "llvm/Analysis/CaptureTracking.h"
00059 #include "llvm/Analysis/InlineCost.h"
00060 #include "llvm/Analysis/InstructionSimplify.h"
00061 #include "llvm/Analysis/Loads.h"
00062 #include "llvm/Analysis/TargetTransformInfo.h"
00063 #include "llvm/IR/CFG.h"
00064 #include "llvm/IR/CallSite.h"
00065 #include "llvm/IR/Constants.h"
00066 #include "llvm/IR/DerivedTypes.h"
00067 #include "llvm/IR/Function.h"
00068 #include "llvm/IR/Instructions.h"
00069 #include "llvm/IR/IntrinsicInst.h"
00070 #include "llvm/IR/Module.h"
00071 #include "llvm/IR/ValueHandle.h"
00072 #include "llvm/Pass.h"
00073 #include "llvm/Support/Debug.h"
00074 #include "llvm/Support/raw_ostream.h"
00075 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00076 #include "llvm/Transforms/Utils/Local.h"
00077 using namespace llvm;
00078 
00079 STATISTIC(NumEliminated, "Number of tail calls removed");
00080 STATISTIC(NumRetDuped,   "Number of return duplicated");
00081 STATISTIC(NumAccumAdded, "Number of accumulators introduced");
00082 
00083 namespace {
00084   struct TailCallElim : public FunctionPass {
00085     const TargetTransformInfo *TTI;
00086 
00087     static char ID; // Pass identification, replacement for typeid
00088     TailCallElim() : FunctionPass(ID) {
00089       initializeTailCallElimPass(*PassRegistry::getPassRegistry());
00090     }
00091 
00092     void getAnalysisUsage(AnalysisUsage &AU) const override;
00093 
00094     bool runOnFunction(Function &F) override;
00095 
00096   private:
00097     CallInst *FindTRECandidate(Instruction *I,
00098                                bool CannotTailCallElimCallsMarkedTail);
00099     bool EliminateRecursiveTailCall(CallInst *CI, ReturnInst *Ret,
00100                                     BasicBlock *&OldEntry,
00101                                     bool &TailCallsAreMarkedTail,
00102                                     SmallVectorImpl<PHINode *> &ArgumentPHIs,
00103                                     bool CannotTailCallElimCallsMarkedTail);
00104     bool FoldReturnAndProcessPred(BasicBlock *BB,
00105                                   ReturnInst *Ret, BasicBlock *&OldEntry,
00106                                   bool &TailCallsAreMarkedTail,
00107                                   SmallVectorImpl<PHINode *> &ArgumentPHIs,
00108                                   bool CannotTailCallElimCallsMarkedTail);
00109     bool ProcessReturningBlock(ReturnInst *RI, BasicBlock *&OldEntry,
00110                                bool &TailCallsAreMarkedTail,
00111                                SmallVectorImpl<PHINode *> &ArgumentPHIs,
00112                                bool CannotTailCallElimCallsMarkedTail);
00113     bool CanMoveAboveCall(Instruction *I, CallInst *CI);
00114     Value *CanTransformAccumulatorRecursion(Instruction *I, CallInst *CI);
00115   };
00116 }
00117 
00118 char TailCallElim::ID = 0;
00119 INITIALIZE_PASS_BEGIN(TailCallElim, "tailcallelim",
00120                       "Tail Call Elimination", false, false)
00121 INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
00122 INITIALIZE_PASS_END(TailCallElim, "tailcallelim",
00123                     "Tail Call Elimination", false, false)
00124 
00125 // Public interface to the TailCallElimination pass
00126 FunctionPass *llvm::createTailCallEliminationPass() {
00127   return new TailCallElim();
00128 }
00129 
00130 void TailCallElim::getAnalysisUsage(AnalysisUsage &AU) const {
00131   AU.addRequired<TargetTransformInfo>();
00132 }
00133 
00134 /// CanTRE - Scan the specified basic block for alloca instructions.
00135 /// If it contains any that are variable-sized or not in the entry block,
00136 /// returns false.
00137 static bool CanTRE(AllocaInst *AI) {
00138   // Because of PR962, we don't TRE allocas outside the entry block.
00139 
00140   // If this alloca is in the body of the function, or if it is a variable
00141   // sized allocation, we cannot tail call eliminate calls marked 'tail'
00142   // with this mechanism.
00143   BasicBlock *BB = AI->getParent();
00144   return BB == &BB->getParent()->getEntryBlock() &&
00145          isa<ConstantInt>(AI->getArraySize());
00146 }
00147 
00148 namespace {
00149 struct AllocaCaptureTracker : public CaptureTracker {
00150   AllocaCaptureTracker() : Captured(false) {}
00151 
00152   void tooManyUses() override { Captured = true; }
00153 
00154   bool shouldExplore(const Use *U) override {
00155     Value *V = U->getUser();
00156     if (isa<CallInst>(V) || isa<InvokeInst>(V))
00157       UsesAlloca.insert(V);
00158     return true;
00159   }
00160 
00161   bool captured(const Use *U) override {
00162     if (isa<ReturnInst>(U->getUser()))
00163       return false;
00164     Captured = true;
00165     return true;
00166   }
00167 
00168   bool Captured;
00169   SmallPtrSet<const Value *, 16> UsesAlloca;
00170 };
00171 } // end anonymous namespace
00172 
00173 bool TailCallElim::runOnFunction(Function &F) {
00174   if (skipOptnoneFunction(F))
00175     return false;
00176 
00177   // If this function is a varargs function, we won't be able to PHI the args
00178   // right, so don't even try to convert it...
00179   if (F.getFunctionType()->isVarArg()) return false;
00180 
00181   TTI = &getAnalysis<TargetTransformInfo>();
00182   BasicBlock *OldEntry = 0;
00183   bool TailCallsAreMarkedTail = false;
00184   SmallVector<PHINode*, 8> ArgumentPHIs;
00185   bool MadeChange = false;
00186 
00187   // CanTRETailMarkedCall - If false, we cannot perform TRE on tail calls
00188   // marked with the 'tail' attribute, because doing so would cause the stack
00189   // size to increase (real TRE would deallocate variable sized allocas, TRE
00190   // doesn't).
00191   bool CanTRETailMarkedCall = true;
00192 
00193   // Find calls that can be marked tail.
00194   AllocaCaptureTracker ACT;
00195   for (Function::iterator BB = F.begin(), EE = F.end(); BB != EE; ++BB) {
00196     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
00197       if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
00198         CanTRETailMarkedCall &= CanTRE(AI);
00199         PointerMayBeCaptured(AI, &ACT);
00200         // If any allocas are captured, exit.
00201         if (ACT.Captured)
00202           return false;
00203       }
00204     }
00205   }
00206 
00207   // Second pass, change any tail recursive calls to loops.
00208   //
00209   // FIXME: The code generator produces really bad code when an 'escaping
00210   // alloca' is changed from being a static alloca to being a dynamic alloca.
00211   // Until this is resolved, disable this transformation if that would ever
00212   // happen.  This bug is PR962.
00213   if (ACT.UsesAlloca.empty()) {
00214     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
00215       if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB->getTerminator())) {
00216         bool Change = ProcessReturningBlock(Ret, OldEntry, TailCallsAreMarkedTail,
00217                                             ArgumentPHIs, !CanTRETailMarkedCall);
00218         if (!Change && BB->getFirstNonPHIOrDbg() == Ret)
00219           Change = FoldReturnAndProcessPred(BB, Ret, OldEntry,
00220                                             TailCallsAreMarkedTail, ArgumentPHIs,
00221                                             !CanTRETailMarkedCall);
00222         MadeChange |= Change;
00223       }
00224     }
00225   }
00226 
00227   // If we eliminated any tail recursions, it's possible that we inserted some
00228   // silly PHI nodes which just merge an initial value (the incoming operand)
00229   // with themselves.  Check to see if we did and clean up our mess if so.  This
00230   // occurs when a function passes an argument straight through to its tail
00231   // call.
00232   if (!ArgumentPHIs.empty()) {
00233     for (unsigned i = 0, e = ArgumentPHIs.size(); i != e; ++i) {
00234       PHINode *PN = ArgumentPHIs[i];
00235 
00236       // If the PHI Node is a dynamic constant, replace it with the value it is.
00237       if (Value *PNV = SimplifyInstruction(PN)) {
00238         PN->replaceAllUsesWith(PNV);
00239         PN->eraseFromParent();
00240       }
00241     }
00242   }
00243 
00244   // At this point, we know that the function does not have any captured
00245   // allocas. If additionally the function does not call setjmp, mark all calls
00246   // in the function that do not access stack memory with the tail keyword. This
00247   // implies ensuring that there does not exist any path from a call that takes
00248   // in an alloca but does not capture it and the call which we wish to mark
00249   // with "tail".
00250   if (!F.callsFunctionThatReturnsTwice()) {
00251     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
00252       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
00253         if (CallInst *CI = dyn_cast<CallInst>(I)) {
00254           if (!ACT.UsesAlloca.count(CI)) {
00255             CI->setTailCall();
00256             MadeChange = true;
00257           }
00258         }
00259       }
00260     }
00261   }
00262 
00263   return MadeChange;
00264 }
00265 
00266 
00267 /// CanMoveAboveCall - Return true if it is safe to move the specified
00268 /// instruction from after the call to before the call, assuming that all
00269 /// instructions between the call and this instruction are movable.
00270 ///
00271 bool TailCallElim::CanMoveAboveCall(Instruction *I, CallInst *CI) {
00272   // FIXME: We can move load/store/call/free instructions above the call if the
00273   // call does not mod/ref the memory location being processed.
00274   if (I->mayHaveSideEffects())  // This also handles volatile loads.
00275     return false;
00276 
00277   if (LoadInst *L = dyn_cast<LoadInst>(I)) {
00278     // Loads may always be moved above calls without side effects.
00279     if (CI->mayHaveSideEffects()) {
00280       // Non-volatile loads may be moved above a call with side effects if it
00281       // does not write to memory and the load provably won't trap.
00282       // FIXME: Writes to memory only matter if they may alias the pointer
00283       // being loaded from.
00284       if (CI->mayWriteToMemory() ||
00285           !isSafeToLoadUnconditionally(L->getPointerOperand(), L,
00286                                        L->getAlignment()))
00287         return false;
00288     }
00289   }
00290 
00291   // Otherwise, if this is a side-effect free instruction, check to make sure
00292   // that it does not use the return value of the call.  If it doesn't use the
00293   // return value of the call, it must only use things that are defined before
00294   // the call, or movable instructions between the call and the instruction
00295   // itself.
00296   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
00297     if (I->getOperand(i) == CI)
00298       return false;
00299   return true;
00300 }
00301 
00302 // isDynamicConstant - Return true if the specified value is the same when the
00303 // return would exit as it was when the initial iteration of the recursive
00304 // function was executed.
00305 //
00306 // We currently handle static constants and arguments that are not modified as
00307 // part of the recursion.
00308 //
00309 static bool isDynamicConstant(Value *V, CallInst *CI, ReturnInst *RI) {
00310   if (isa<Constant>(V)) return true; // Static constants are always dyn consts
00311 
00312   // Check to see if this is an immutable argument, if so, the value
00313   // will be available to initialize the accumulator.
00314   if (Argument *Arg = dyn_cast<Argument>(V)) {
00315     // Figure out which argument number this is...
00316     unsigned ArgNo = 0;
00317     Function *F = CI->getParent()->getParent();
00318     for (Function::arg_iterator AI = F->arg_begin(); &*AI != Arg; ++AI)
00319       ++ArgNo;
00320 
00321     // If we are passing this argument into call as the corresponding
00322     // argument operand, then the argument is dynamically constant.
00323     // Otherwise, we cannot transform this function safely.
00324     if (CI->getArgOperand(ArgNo) == Arg)
00325       return true;
00326   }
00327 
00328   // Switch cases are always constant integers. If the value is being switched
00329   // on and the return is only reachable from one of its cases, it's
00330   // effectively constant.
00331   if (BasicBlock *UniquePred = RI->getParent()->getUniquePredecessor())
00332     if (SwitchInst *SI = dyn_cast<SwitchInst>(UniquePred->getTerminator()))
00333       if (SI->getCondition() == V)
00334         return SI->getDefaultDest() != RI->getParent();
00335 
00336   // Not a constant or immutable argument, we can't safely transform.
00337   return false;
00338 }
00339 
00340 // getCommonReturnValue - Check to see if the function containing the specified
00341 // tail call consistently returns the same runtime-constant value at all exit
00342 // points except for IgnoreRI.  If so, return the returned value.
00343 //
00344 static Value *getCommonReturnValue(ReturnInst *IgnoreRI, CallInst *CI) {
00345   Function *F = CI->getParent()->getParent();
00346   Value *ReturnedValue = 0;
00347 
00348   for (Function::iterator BBI = F->begin(), E = F->end(); BBI != E; ++BBI) {
00349     ReturnInst *RI = dyn_cast<ReturnInst>(BBI->getTerminator());
00350     if (RI == 0 || RI == IgnoreRI) continue;
00351 
00352     // We can only perform this transformation if the value returned is
00353     // evaluatable at the start of the initial invocation of the function,
00354     // instead of at the end of the evaluation.
00355     //
00356     Value *RetOp = RI->getOperand(0);
00357     if (!isDynamicConstant(RetOp, CI, RI))
00358       return 0;
00359 
00360     if (ReturnedValue && RetOp != ReturnedValue)
00361       return 0;     // Cannot transform if differing values are returned.
00362     ReturnedValue = RetOp;
00363   }
00364   return ReturnedValue;
00365 }
00366 
00367 /// CanTransformAccumulatorRecursion - If the specified instruction can be
00368 /// transformed using accumulator recursion elimination, return the constant
00369 /// which is the start of the accumulator value.  Otherwise return null.
00370 ///
00371 Value *TailCallElim::CanTransformAccumulatorRecursion(Instruction *I,
00372                                                       CallInst *CI) {
00373   if (!I->isAssociative() || !I->isCommutative()) return 0;
00374   assert(I->getNumOperands() == 2 &&
00375          "Associative/commutative operations should have 2 args!");
00376 
00377   // Exactly one operand should be the result of the call instruction.
00378   if ((I->getOperand(0) == CI && I->getOperand(1) == CI) ||
00379       (I->getOperand(0) != CI && I->getOperand(1) != CI))
00380     return 0;
00381 
00382   // The only user of this instruction we allow is a single return instruction.
00383   if (!I->hasOneUse() || !isa<ReturnInst>(I->user_back()))
00384     return 0;
00385 
00386   // Ok, now we have to check all of the other return instructions in this
00387   // function.  If they return non-constants or differing values, then we cannot
00388   // transform the function safely.
00389   return getCommonReturnValue(cast<ReturnInst>(I->user_back()), CI);
00390 }
00391 
00392 static Instruction *FirstNonDbg(BasicBlock::iterator I) {
00393   while (isa<DbgInfoIntrinsic>(I))
00394     ++I;
00395   return &*I;
00396 }
00397 
00398 CallInst*
00399 TailCallElim::FindTRECandidate(Instruction *TI,
00400                                bool CannotTailCallElimCallsMarkedTail) {
00401   BasicBlock *BB = TI->getParent();
00402   Function *F = BB->getParent();
00403 
00404   if (&BB->front() == TI) // Make sure there is something before the terminator.
00405     return 0;
00406 
00407   // Scan backwards from the return, checking to see if there is a tail call in
00408   // this block.  If so, set CI to it.
00409   CallInst *CI = 0;
00410   BasicBlock::iterator BBI = TI;
00411   while (true) {
00412     CI = dyn_cast<CallInst>(BBI);
00413     if (CI && CI->getCalledFunction() == F)
00414       break;
00415 
00416     if (BBI == BB->begin())
00417       return 0;          // Didn't find a potential tail call.
00418     --BBI;
00419   }
00420 
00421   // If this call is marked as a tail call, and if there are dynamic allocas in
00422   // the function, we cannot perform this optimization.
00423   if (CI->isTailCall() && CannotTailCallElimCallsMarkedTail)
00424     return 0;
00425 
00426   // As a special case, detect code like this:
00427   //   double fabs(double f) { return __builtin_fabs(f); } // a 'fabs' call
00428   // and disable this xform in this case, because the code generator will
00429   // lower the call to fabs into inline code.
00430   if (BB == &F->getEntryBlock() &&
00431       FirstNonDbg(BB->front()) == CI &&
00432       FirstNonDbg(std::next(BB->begin())) == TI &&
00433       CI->getCalledFunction() &&
00434       !TTI->isLoweredToCall(CI->getCalledFunction())) {
00435     // A single-block function with just a call and a return. Check that
00436     // the arguments match.
00437     CallSite::arg_iterator I = CallSite(CI).arg_begin(),
00438                            E = CallSite(CI).arg_end();
00439     Function::arg_iterator FI = F->arg_begin(),
00440                            FE = F->arg_end();
00441     for (; I != E && FI != FE; ++I, ++FI)
00442       if (*I != &*FI) break;
00443     if (I == E && FI == FE)
00444       return 0;
00445   }
00446 
00447   return CI;
00448 }
00449 
00450 bool TailCallElim::EliminateRecursiveTailCall(CallInst *CI, ReturnInst *Ret,
00451                                        BasicBlock *&OldEntry,
00452                                        bool &TailCallsAreMarkedTail,
00453                                        SmallVectorImpl<PHINode *> &ArgumentPHIs,
00454                                        bool CannotTailCallElimCallsMarkedTail) {
00455   // If we are introducing accumulator recursion to eliminate operations after
00456   // the call instruction that are both associative and commutative, the initial
00457   // value for the accumulator is placed in this variable.  If this value is set
00458   // then we actually perform accumulator recursion elimination instead of
00459   // simple tail recursion elimination.  If the operation is an LLVM instruction
00460   // (eg: "add") then it is recorded in AccumulatorRecursionInstr.  If not, then
00461   // we are handling the case when the return instruction returns a constant C
00462   // which is different to the constant returned by other return instructions
00463   // (which is recorded in AccumulatorRecursionEliminationInitVal).  This is a
00464   // special case of accumulator recursion, the operation being "return C".
00465   Value *AccumulatorRecursionEliminationInitVal = 0;
00466   Instruction *AccumulatorRecursionInstr = 0;
00467 
00468   // Ok, we found a potential tail call.  We can currently only transform the
00469   // tail call if all of the instructions between the call and the return are
00470   // movable to above the call itself, leaving the call next to the return.
00471   // Check that this is the case now.
00472   BasicBlock::iterator BBI = CI;
00473   for (++BBI; &*BBI != Ret; ++BBI) {
00474     if (CanMoveAboveCall(BBI, CI)) continue;
00475 
00476     // If we can't move the instruction above the call, it might be because it
00477     // is an associative and commutative operation that could be transformed
00478     // using accumulator recursion elimination.  Check to see if this is the
00479     // case, and if so, remember the initial accumulator value for later.
00480     if ((AccumulatorRecursionEliminationInitVal =
00481                            CanTransformAccumulatorRecursion(BBI, CI))) {
00482       // Yes, this is accumulator recursion.  Remember which instruction
00483       // accumulates.
00484       AccumulatorRecursionInstr = BBI;
00485     } else {
00486       return false;   // Otherwise, we cannot eliminate the tail recursion!
00487     }
00488   }
00489 
00490   // We can only transform call/return pairs that either ignore the return value
00491   // of the call and return void, ignore the value of the call and return a
00492   // constant, return the value returned by the tail call, or that are being
00493   // accumulator recursion variable eliminated.
00494   if (Ret->getNumOperands() == 1 && Ret->getReturnValue() != CI &&
00495       !isa<UndefValue>(Ret->getReturnValue()) &&
00496       AccumulatorRecursionEliminationInitVal == 0 &&
00497       !getCommonReturnValue(0, CI)) {
00498     // One case remains that we are able to handle: the current return
00499     // instruction returns a constant, and all other return instructions
00500     // return a different constant.
00501     if (!isDynamicConstant(Ret->getReturnValue(), CI, Ret))
00502       return false; // Current return instruction does not return a constant.
00503     // Check that all other return instructions return a common constant.  If
00504     // so, record it in AccumulatorRecursionEliminationInitVal.
00505     AccumulatorRecursionEliminationInitVal = getCommonReturnValue(Ret, CI);
00506     if (!AccumulatorRecursionEliminationInitVal)
00507       return false;
00508   }
00509 
00510   BasicBlock *BB = Ret->getParent();
00511   Function *F = BB->getParent();
00512 
00513   // OK! We can transform this tail call.  If this is the first one found,
00514   // create the new entry block, allowing us to branch back to the old entry.
00515   if (OldEntry == 0) {
00516     OldEntry = &F->getEntryBlock();
00517     BasicBlock *NewEntry = BasicBlock::Create(F->getContext(), "", F, OldEntry);
00518     NewEntry->takeName(OldEntry);
00519     OldEntry->setName("tailrecurse");
00520     BranchInst::Create(OldEntry, NewEntry);
00521 
00522     // If this tail call is marked 'tail' and if there are any allocas in the
00523     // entry block, move them up to the new entry block.
00524     TailCallsAreMarkedTail = CI->isTailCall();
00525     if (TailCallsAreMarkedTail)
00526       // Move all fixed sized allocas from OldEntry to NewEntry.
00527       for (BasicBlock::iterator OEBI = OldEntry->begin(), E = OldEntry->end(),
00528              NEBI = NewEntry->begin(); OEBI != E; )
00529         if (AllocaInst *AI = dyn_cast<AllocaInst>(OEBI++))
00530           if (isa<ConstantInt>(AI->getArraySize()))
00531             AI->moveBefore(NEBI);
00532 
00533     // Now that we have created a new block, which jumps to the entry
00534     // block, insert a PHI node for each argument of the function.
00535     // For now, we initialize each PHI to only have the real arguments
00536     // which are passed in.
00537     Instruction *InsertPos = OldEntry->begin();
00538     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
00539          I != E; ++I) {
00540       PHINode *PN = PHINode::Create(I->getType(), 2,
00541                                     I->getName() + ".tr", InsertPos);
00542       I->replaceAllUsesWith(PN); // Everyone use the PHI node now!
00543       PN->addIncoming(I, NewEntry);
00544       ArgumentPHIs.push_back(PN);
00545     }
00546   }
00547 
00548   // If this function has self recursive calls in the tail position where some
00549   // are marked tail and some are not, only transform one flavor or another.  We
00550   // have to choose whether we move allocas in the entry block to the new entry
00551   // block or not, so we can't make a good choice for both.  NOTE: We could do
00552   // slightly better here in the case that the function has no entry block
00553   // allocas.
00554   if (TailCallsAreMarkedTail && !CI->isTailCall())
00555     return false;
00556 
00557   // Ok, now that we know we have a pseudo-entry block WITH all of the
00558   // required PHI nodes, add entries into the PHI node for the actual
00559   // parameters passed into the tail-recursive call.
00560   for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i)
00561     ArgumentPHIs[i]->addIncoming(CI->getArgOperand(i), BB);
00562 
00563   // If we are introducing an accumulator variable to eliminate the recursion,
00564   // do so now.  Note that we _know_ that no subsequent tail recursion
00565   // eliminations will happen on this function because of the way the
00566   // accumulator recursion predicate is set up.
00567   //
00568   if (AccumulatorRecursionEliminationInitVal) {
00569     Instruction *AccRecInstr = AccumulatorRecursionInstr;
00570     // Start by inserting a new PHI node for the accumulator.
00571     pred_iterator PB = pred_begin(OldEntry), PE = pred_end(OldEntry);
00572     PHINode *AccPN =
00573       PHINode::Create(AccumulatorRecursionEliminationInitVal->getType(),
00574                       std::distance(PB, PE) + 1,
00575                       "accumulator.tr", OldEntry->begin());
00576 
00577     // Loop over all of the predecessors of the tail recursion block.  For the
00578     // real entry into the function we seed the PHI with the initial value,
00579     // computed earlier.  For any other existing branches to this block (due to
00580     // other tail recursions eliminated) the accumulator is not modified.
00581     // Because we haven't added the branch in the current block to OldEntry yet,
00582     // it will not show up as a predecessor.
00583     for (pred_iterator PI = PB; PI != PE; ++PI) {
00584       BasicBlock *P = *PI;
00585       if (P == &F->getEntryBlock())
00586         AccPN->addIncoming(AccumulatorRecursionEliminationInitVal, P);
00587       else
00588         AccPN->addIncoming(AccPN, P);
00589     }
00590 
00591     if (AccRecInstr) {
00592       // Add an incoming argument for the current block, which is computed by
00593       // our associative and commutative accumulator instruction.
00594       AccPN->addIncoming(AccRecInstr, BB);
00595 
00596       // Next, rewrite the accumulator recursion instruction so that it does not
00597       // use the result of the call anymore, instead, use the PHI node we just
00598       // inserted.
00599       AccRecInstr->setOperand(AccRecInstr->getOperand(0) != CI, AccPN);
00600     } else {
00601       // Add an incoming argument for the current block, which is just the
00602       // constant returned by the current return instruction.
00603       AccPN->addIncoming(Ret->getReturnValue(), BB);
00604     }
00605 
00606     // Finally, rewrite any return instructions in the program to return the PHI
00607     // node instead of the "initval" that they do currently.  This loop will
00608     // actually rewrite the return value we are destroying, but that's ok.
00609     for (Function::iterator BBI = F->begin(), E = F->end(); BBI != E; ++BBI)
00610       if (ReturnInst *RI = dyn_cast<ReturnInst>(BBI->getTerminator()))
00611         RI->setOperand(0, AccPN);
00612     ++NumAccumAdded;
00613   }
00614 
00615   // Now that all of the PHI nodes are in place, remove the call and
00616   // ret instructions, replacing them with an unconditional branch.
00617   BranchInst *NewBI = BranchInst::Create(OldEntry, Ret);
00618   NewBI->setDebugLoc(CI->getDebugLoc());
00619 
00620   BB->getInstList().erase(Ret);  // Remove return.
00621   BB->getInstList().erase(CI);   // Remove call.
00622   ++NumEliminated;
00623   return true;
00624 }
00625 
00626 bool TailCallElim::FoldReturnAndProcessPred(BasicBlock *BB,
00627                                        ReturnInst *Ret, BasicBlock *&OldEntry,
00628                                        bool &TailCallsAreMarkedTail,
00629                                        SmallVectorImpl<PHINode *> &ArgumentPHIs,
00630                                        bool CannotTailCallElimCallsMarkedTail) {
00631   bool Change = false;
00632 
00633   // If the return block contains nothing but the return and PHI's,
00634   // there might be an opportunity to duplicate the return in its
00635   // predecessors and perform TRC there. Look for predecessors that end
00636   // in unconditional branch and recursive call(s).
00637   SmallVector<BranchInst*, 8> UncondBranchPreds;
00638   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
00639     BasicBlock *Pred = *PI;
00640     TerminatorInst *PTI = Pred->getTerminator();
00641     if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
00642       if (BI->isUnconditional())
00643         UncondBranchPreds.push_back(BI);
00644   }
00645 
00646   while (!UncondBranchPreds.empty()) {
00647     BranchInst *BI = UncondBranchPreds.pop_back_val();
00648     BasicBlock *Pred = BI->getParent();
00649     if (CallInst *CI = FindTRECandidate(BI, CannotTailCallElimCallsMarkedTail)){
00650       DEBUG(dbgs() << "FOLDING: " << *BB
00651             << "INTO UNCOND BRANCH PRED: " << *Pred);
00652       EliminateRecursiveTailCall(CI, FoldReturnIntoUncondBranch(Ret, BB, Pred),
00653                                  OldEntry, TailCallsAreMarkedTail, ArgumentPHIs,
00654                                  CannotTailCallElimCallsMarkedTail);
00655       ++NumRetDuped;
00656       Change = true;
00657     }
00658   }
00659 
00660   return Change;
00661 }
00662 
00663 bool
00664 TailCallElim::ProcessReturningBlock(ReturnInst *Ret, BasicBlock *&OldEntry,
00665                                     bool &TailCallsAreMarkedTail,
00666                                     SmallVectorImpl<PHINode *> &ArgumentPHIs,
00667                                     bool CannotTailCallElimCallsMarkedTail) {
00668   CallInst *CI = FindTRECandidate(Ret, CannotTailCallElimCallsMarkedTail);
00669   if (!CI)
00670     return false;
00671 
00672   return EliminateRecursiveTailCall(CI, Ret, OldEntry, TailCallsAreMarkedTail,
00673                                     ArgumentPHIs,
00674                                     CannotTailCallElimCallsMarkedTail);
00675 }