LLVM  mainline
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 #include "llvm/Transforms/Scalar.h"
00054 #include "llvm/ADT/STLExtras.h"
00055 #include "llvm/ADT/SmallPtrSet.h"
00056 #include "llvm/ADT/Statistic.h"
00057 #include "llvm/Analysis/CFG.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/DataLayout.h"
00067 #include "llvm/IR/DerivedTypes.h"
00068 #include "llvm/IR/DiagnosticInfo.h"
00069 #include "llvm/IR/Function.h"
00070 #include "llvm/IR/Instructions.h"
00071 #include "llvm/IR/IntrinsicInst.h"
00072 #include "llvm/IR/Module.h"
00073 #include "llvm/IR/ValueHandle.h"
00074 #include "llvm/Pass.h"
00075 #include "llvm/Support/Debug.h"
00076 #include "llvm/Support/raw_ostream.h"
00077 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00078 #include "llvm/Transforms/Utils/Local.h"
00079 using namespace llvm;
00080 
00081 #define DEBUG_TYPE "tailcallelim"
00082 
00083 STATISTIC(NumEliminated, "Number of tail calls removed");
00084 STATISTIC(NumRetDuped,   "Number of return duplicated");
00085 STATISTIC(NumAccumAdded, "Number of accumulators introduced");
00086 
00087 namespace {
00088   struct TailCallElim : public FunctionPass {
00089     const TargetTransformInfo *TTI;
00090 
00091     static char ID; // Pass identification, replacement for typeid
00092     TailCallElim() : FunctionPass(ID) {
00093       initializeTailCallElimPass(*PassRegistry::getPassRegistry());
00094     }
00095 
00096     void getAnalysisUsage(AnalysisUsage &AU) const override;
00097 
00098     bool runOnFunction(Function &F) override;
00099 
00100   private:
00101     bool runTRE(Function &F);
00102     bool markTails(Function &F, bool &AllCallsAreTailCalls);
00103 
00104     CallInst *FindTRECandidate(Instruction *I,
00105                                bool CannotTailCallElimCallsMarkedTail);
00106     bool EliminateRecursiveTailCall(CallInst *CI, ReturnInst *Ret,
00107                                     BasicBlock *&OldEntry,
00108                                     bool &TailCallsAreMarkedTail,
00109                                     SmallVectorImpl<PHINode *> &ArgumentPHIs,
00110                                     bool CannotTailCallElimCallsMarkedTail);
00111     bool FoldReturnAndProcessPred(BasicBlock *BB,
00112                                   ReturnInst *Ret, BasicBlock *&OldEntry,
00113                                   bool &TailCallsAreMarkedTail,
00114                                   SmallVectorImpl<PHINode *> &ArgumentPHIs,
00115                                   bool CannotTailCallElimCallsMarkedTail);
00116     bool ProcessReturningBlock(ReturnInst *RI, BasicBlock *&OldEntry,
00117                                bool &TailCallsAreMarkedTail,
00118                                SmallVectorImpl<PHINode *> &ArgumentPHIs,
00119                                bool CannotTailCallElimCallsMarkedTail);
00120     bool CanMoveAboveCall(Instruction *I, CallInst *CI);
00121     Value *CanTransformAccumulatorRecursion(Instruction *I, CallInst *CI);
00122   };
00123 }
00124 
00125 char TailCallElim::ID = 0;
00126 INITIALIZE_PASS_BEGIN(TailCallElim, "tailcallelim",
00127                       "Tail Call Elimination", false, false)
00128 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
00129 INITIALIZE_PASS_END(TailCallElim, "tailcallelim",
00130                     "Tail Call Elimination", false, false)
00131 
00132 // Public interface to the TailCallElimination pass
00133 FunctionPass *llvm::createTailCallEliminationPass() {
00134   return new TailCallElim();
00135 }
00136 
00137 void TailCallElim::getAnalysisUsage(AnalysisUsage &AU) const {
00138   AU.addRequired<TargetTransformInfoWrapperPass>();
00139 }
00140 
00141 /// \brief Scan the specified function for alloca instructions.
00142 /// If it contains any dynamic allocas, returns false.
00143 static bool CanTRE(Function &F) {
00144   // Because of PR962, we don't TRE dynamic allocas.
00145   for (auto &BB : F) {
00146     for (auto &I : BB) {
00147       if (AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
00148         if (!AI->isStaticAlloca())
00149           return false;
00150       }
00151     }
00152   }
00153 
00154   return true;
00155 }
00156 
00157 bool TailCallElim::runOnFunction(Function &F) {
00158   if (skipOptnoneFunction(F))
00159     return false;
00160 
00161   bool AllCallsAreTailCalls = false;
00162   bool Modified = markTails(F, AllCallsAreTailCalls);
00163   if (AllCallsAreTailCalls)
00164     Modified |= runTRE(F);
00165   return Modified;
00166 }
00167 
00168 namespace {
00169 struct AllocaDerivedValueTracker {
00170   // Start at a root value and walk its use-def chain to mark calls that use the
00171   // value or a derived value in AllocaUsers, and places where it may escape in
00172   // EscapePoints.
00173   void walk(Value *Root) {
00174     SmallVector<Use *, 32> Worklist;
00175     SmallPtrSet<Use *, 32> Visited;
00176 
00177     auto AddUsesToWorklist = [&](Value *V) {
00178       for (auto &U : V->uses()) {
00179         if (!Visited.insert(&U).second)
00180           continue;
00181         Worklist.push_back(&U);
00182       }
00183     };
00184 
00185     AddUsesToWorklist(Root);
00186 
00187     while (!Worklist.empty()) {
00188       Use *U = Worklist.pop_back_val();
00189       Instruction *I = cast<Instruction>(U->getUser());
00190 
00191       switch (I->getOpcode()) {
00192       case Instruction::Call:
00193       case Instruction::Invoke: {
00194         CallSite CS(I);
00195         bool IsNocapture = !CS.isCallee(U) &&
00196                            CS.doesNotCapture(CS.getArgumentNo(U));
00197         callUsesLocalStack(CS, IsNocapture);
00198         if (IsNocapture) {
00199           // If the alloca-derived argument is passed in as nocapture, then it
00200           // can't propagate to the call's return. That would be capturing.
00201           continue;
00202         }
00203         break;
00204       }
00205       case Instruction::Load: {
00206         // The result of a load is not alloca-derived (unless an alloca has
00207         // otherwise escaped, but this is a local analysis).
00208         continue;
00209       }
00210       case Instruction::Store: {
00211         if (U->getOperandNo() == 0)
00212           EscapePoints.insert(I);
00213         continue;  // Stores have no users to analyze.
00214       }
00215       case Instruction::BitCast:
00216       case Instruction::GetElementPtr:
00217       case Instruction::PHI:
00218       case Instruction::Select:
00219       case Instruction::AddrSpaceCast:
00220         break;
00221       default:
00222         EscapePoints.insert(I);
00223         break;
00224       }
00225 
00226       AddUsesToWorklist(I);
00227     }
00228   }
00229 
00230   void callUsesLocalStack(CallSite CS, bool IsNocapture) {
00231     // Add it to the list of alloca users.
00232     AllocaUsers.insert(CS.getInstruction());
00233 
00234     // If it's nocapture then it can't capture this alloca.
00235     if (IsNocapture)
00236       return;
00237 
00238     // If it can write to memory, it can leak the alloca value.
00239     if (!CS.onlyReadsMemory())
00240       EscapePoints.insert(CS.getInstruction());
00241   }
00242 
00243   SmallPtrSet<Instruction *, 32> AllocaUsers;
00244   SmallPtrSet<Instruction *, 32> EscapePoints;
00245 };
00246 }
00247 
00248 bool TailCallElim::markTails(Function &F, bool &AllCallsAreTailCalls) {
00249   if (F.callsFunctionThatReturnsTwice())
00250     return false;
00251   AllCallsAreTailCalls = true;
00252 
00253   // The local stack holds all alloca instructions and all byval arguments.
00254   AllocaDerivedValueTracker Tracker;
00255   for (Argument &Arg : F.args()) {
00256     if (Arg.hasByValAttr())
00257       Tracker.walk(&Arg);
00258   }
00259   for (auto &BB : F) {
00260     for (auto &I : BB)
00261       if (AllocaInst *AI = dyn_cast<AllocaInst>(&I))
00262         Tracker.walk(AI);
00263   }
00264 
00265   bool Modified = false;
00266 
00267   // Track whether a block is reachable after an alloca has escaped. Blocks that
00268   // contain the escaping instruction will be marked as being visited without an
00269   // escaped alloca, since that is how the block began.
00270   enum VisitType {
00271     UNVISITED,
00272     UNESCAPED,
00273     ESCAPED
00274   };
00275   DenseMap<BasicBlock *, VisitType> Visited;
00276 
00277   // We propagate the fact that an alloca has escaped from block to successor.
00278   // Visit the blocks that are propagating the escapedness first. To do this, we
00279   // maintain two worklists.
00280   SmallVector<BasicBlock *, 32> WorklistUnescaped, WorklistEscaped;
00281 
00282   // We may enter a block and visit it thinking that no alloca has escaped yet,
00283   // then see an escape point and go back around a loop edge and come back to
00284   // the same block twice. Because of this, we defer setting tail on calls when
00285   // we first encounter them in a block. Every entry in this list does not
00286   // statically use an alloca via use-def chain analysis, but may find an alloca
00287   // through other means if the block turns out to be reachable after an escape
00288   // point.
00289   SmallVector<CallInst *, 32> DeferredTails;
00290 
00291   BasicBlock *BB = &F.getEntryBlock();
00292   VisitType Escaped = UNESCAPED;
00293   do {
00294     for (auto &I : *BB) {
00295       if (Tracker.EscapePoints.count(&I))
00296         Escaped = ESCAPED;
00297 
00298       CallInst *CI = dyn_cast<CallInst>(&I);
00299       if (!CI || CI->isTailCall())
00300         continue;
00301 
00302       if (CI->doesNotAccessMemory()) {
00303         // A call to a readnone function whose arguments are all things computed
00304         // outside this function can be marked tail. Even if you stored the
00305         // alloca address into a global, a readnone function can't load the
00306         // global anyhow.
00307         //
00308         // Note that this runs whether we know an alloca has escaped or not. If
00309         // it has, then we can't trust Tracker.AllocaUsers to be accurate.
00310         bool SafeToTail = true;
00311         for (auto &Arg : CI->arg_operands()) {
00312           if (isa<Constant>(Arg.getUser()))
00313             continue;
00314           if (Argument *A = dyn_cast<Argument>(Arg.getUser()))
00315             if (!A->hasByValAttr())
00316               continue;
00317           SafeToTail = false;
00318           break;
00319         }
00320         if (SafeToTail) {
00321           emitOptimizationRemark(
00322               F.getContext(), "tailcallelim", F, CI->getDebugLoc(),
00323               "marked this readnone call a tail call candidate");
00324           CI->setTailCall();
00325           Modified = true;
00326           continue;
00327         }
00328       }
00329 
00330       if (Escaped == UNESCAPED && !Tracker.AllocaUsers.count(CI)) {
00331         DeferredTails.push_back(CI);
00332       } else {
00333         AllCallsAreTailCalls = false;
00334       }
00335     }
00336 
00337     for (auto *SuccBB : make_range(succ_begin(BB), succ_end(BB))) {
00338       auto &State = Visited[SuccBB];
00339       if (State < Escaped) {
00340         State = Escaped;
00341         if (State == ESCAPED)
00342           WorklistEscaped.push_back(SuccBB);
00343         else
00344           WorklistUnescaped.push_back(SuccBB);
00345       }
00346     }
00347 
00348     if (!WorklistEscaped.empty()) {
00349       BB = WorklistEscaped.pop_back_val();
00350       Escaped = ESCAPED;
00351     } else {
00352       BB = nullptr;
00353       while (!WorklistUnescaped.empty()) {
00354         auto *NextBB = WorklistUnescaped.pop_back_val();
00355         if (Visited[NextBB] == UNESCAPED) {
00356           BB = NextBB;
00357           Escaped = UNESCAPED;
00358           break;
00359         }
00360       }
00361     }
00362   } while (BB);
00363 
00364   for (CallInst *CI : DeferredTails) {
00365     if (Visited[CI->getParent()] != ESCAPED) {
00366       // If the escape point was part way through the block, calls after the
00367       // escape point wouldn't have been put into DeferredTails.
00368       emitOptimizationRemark(F.getContext(), "tailcallelim", F,
00369                              CI->getDebugLoc(),
00370                              "marked this call a tail call candidate");
00371       CI->setTailCall();
00372       Modified = true;
00373     } else {
00374       AllCallsAreTailCalls = false;
00375     }
00376   }
00377 
00378   return Modified;
00379 }
00380 
00381 bool TailCallElim::runTRE(Function &F) {
00382   // If this function is a varargs function, we won't be able to PHI the args
00383   // right, so don't even try to convert it...
00384   if (F.getFunctionType()->isVarArg()) return false;
00385 
00386   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
00387   BasicBlock *OldEntry = nullptr;
00388   bool TailCallsAreMarkedTail = false;
00389   SmallVector<PHINode*, 8> ArgumentPHIs;
00390   bool MadeChange = false;
00391 
00392   // If false, we cannot perform TRE on tail calls marked with the 'tail'
00393   // attribute, because doing so would cause the stack size to increase (real
00394   // TRE would deallocate variable sized allocas, TRE doesn't).
00395   bool CanTRETailMarkedCall = CanTRE(F);
00396 
00397   // Change any tail recursive calls to loops.
00398   //
00399   // FIXME: The code generator produces really bad code when an 'escaping
00400   // alloca' is changed from being a static alloca to being a dynamic alloca.
00401   // Until this is resolved, disable this transformation if that would ever
00402   // happen.  This bug is PR962.
00403   for (Function::iterator BBI = F.begin(), E = F.end(); BBI != E; /*in loop*/) {
00404     BasicBlock *BB = BBI++; // FoldReturnAndProcessPred may delete BB.
00405     if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB->getTerminator())) {
00406       bool Change = ProcessReturningBlock(Ret, OldEntry, TailCallsAreMarkedTail,
00407                                           ArgumentPHIs, !CanTRETailMarkedCall);
00408       if (!Change && BB->getFirstNonPHIOrDbg() == Ret)
00409         Change = FoldReturnAndProcessPred(BB, Ret, OldEntry,
00410                                           TailCallsAreMarkedTail, ArgumentPHIs,
00411                                           !CanTRETailMarkedCall);
00412       MadeChange |= Change;
00413     }
00414   }
00415 
00416   // If we eliminated any tail recursions, it's possible that we inserted some
00417   // silly PHI nodes which just merge an initial value (the incoming operand)
00418   // with themselves.  Check to see if we did and clean up our mess if so.  This
00419   // occurs when a function passes an argument straight through to its tail
00420   // call.
00421   for (unsigned i = 0, e = ArgumentPHIs.size(); i != e; ++i) {
00422     PHINode *PN = ArgumentPHIs[i];
00423 
00424     // If the PHI Node is a dynamic constant, replace it with the value it is.
00425     if (Value *PNV = SimplifyInstruction(PN, F.getParent()->getDataLayout())) {
00426       PN->replaceAllUsesWith(PNV);
00427       PN->eraseFromParent();
00428     }
00429   }
00430 
00431   return MadeChange;
00432 }
00433 
00434 
00435 /// Return true if it is safe to move the specified
00436 /// instruction from after the call to before the call, assuming that all
00437 /// instructions between the call and this instruction are movable.
00438 ///
00439 bool TailCallElim::CanMoveAboveCall(Instruction *I, CallInst *CI) {
00440   // FIXME: We can move load/store/call/free instructions above the call if the
00441   // call does not mod/ref the memory location being processed.
00442   if (I->mayHaveSideEffects())  // This also handles volatile loads.
00443     return false;
00444 
00445   if (LoadInst *L = dyn_cast<LoadInst>(I)) {
00446     // Loads may always be moved above calls without side effects.
00447     if (CI->mayHaveSideEffects()) {
00448       // Non-volatile loads may be moved above a call with side effects if it
00449       // does not write to memory and the load provably won't trap.
00450       // FIXME: Writes to memory only matter if they may alias the pointer
00451       // being loaded from.
00452       if (CI->mayWriteToMemory() ||
00453           !isSafeToLoadUnconditionally(L->getPointerOperand(), L,
00454                                        L->getAlignment()))
00455         return false;
00456     }
00457   }
00458 
00459   // Otherwise, if this is a side-effect free instruction, check to make sure
00460   // that it does not use the return value of the call.  If it doesn't use the
00461   // return value of the call, it must only use things that are defined before
00462   // the call, or movable instructions between the call and the instruction
00463   // itself.
00464   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
00465     if (I->getOperand(i) == CI)
00466       return false;
00467   return true;
00468 }
00469 
00470 /// Return true if the specified value is the same when the return would exit
00471 /// as it was when the initial iteration of the recursive function was executed.
00472 ///
00473 /// We currently handle static constants and arguments that are not modified as
00474 /// part of the recursion.
00475 static bool isDynamicConstant(Value *V, CallInst *CI, ReturnInst *RI) {
00476   if (isa<Constant>(V)) return true; // Static constants are always dyn consts
00477 
00478   // Check to see if this is an immutable argument, if so, the value
00479   // will be available to initialize the accumulator.
00480   if (Argument *Arg = dyn_cast<Argument>(V)) {
00481     // Figure out which argument number this is...
00482     unsigned ArgNo = 0;
00483     Function *F = CI->getParent()->getParent();
00484     for (Function::arg_iterator AI = F->arg_begin(); &*AI != Arg; ++AI)
00485       ++ArgNo;
00486 
00487     // If we are passing this argument into call as the corresponding
00488     // argument operand, then the argument is dynamically constant.
00489     // Otherwise, we cannot transform this function safely.
00490     if (CI->getArgOperand(ArgNo) == Arg)
00491       return true;
00492   }
00493 
00494   // Switch cases are always constant integers. If the value is being switched
00495   // on and the return is only reachable from one of its cases, it's
00496   // effectively constant.
00497   if (BasicBlock *UniquePred = RI->getParent()->getUniquePredecessor())
00498     if (SwitchInst *SI = dyn_cast<SwitchInst>(UniquePred->getTerminator()))
00499       if (SI->getCondition() == V)
00500         return SI->getDefaultDest() != RI->getParent();
00501 
00502   // Not a constant or immutable argument, we can't safely transform.
00503   return false;
00504 }
00505 
00506 /// Check to see if the function containing the specified tail call consistently
00507 /// returns the same runtime-constant value at all exit points except for
00508 /// IgnoreRI. If so, return the returned value.
00509 static Value *getCommonReturnValue(ReturnInst *IgnoreRI, CallInst *CI) {
00510   Function *F = CI->getParent()->getParent();
00511   Value *ReturnedValue = nullptr;
00512 
00513   for (Function::iterator BBI = F->begin(), E = F->end(); BBI != E; ++BBI) {
00514     ReturnInst *RI = dyn_cast<ReturnInst>(BBI->getTerminator());
00515     if (RI == nullptr || RI == IgnoreRI) continue;
00516 
00517     // We can only perform this transformation if the value returned is
00518     // evaluatable at the start of the initial invocation of the function,
00519     // instead of at the end of the evaluation.
00520     //
00521     Value *RetOp = RI->getOperand(0);
00522     if (!isDynamicConstant(RetOp, CI, RI))
00523       return nullptr;
00524 
00525     if (ReturnedValue && RetOp != ReturnedValue)
00526       return nullptr;     // Cannot transform if differing values are returned.
00527     ReturnedValue = RetOp;
00528   }
00529   return ReturnedValue;
00530 }
00531 
00532 /// If the specified instruction can be transformed using accumulator recursion
00533 /// elimination, return the constant which is the start of the accumulator
00534 /// value.  Otherwise return null.
00535 Value *TailCallElim::CanTransformAccumulatorRecursion(Instruction *I,
00536                                                       CallInst *CI) {
00537   if (!I->isAssociative() || !I->isCommutative()) return nullptr;
00538   assert(I->getNumOperands() == 2 &&
00539          "Associative/commutative operations should have 2 args!");
00540 
00541   // Exactly one operand should be the result of the call instruction.
00542   if ((I->getOperand(0) == CI && I->getOperand(1) == CI) ||
00543       (I->getOperand(0) != CI && I->getOperand(1) != CI))
00544     return nullptr;
00545 
00546   // The only user of this instruction we allow is a single return instruction.
00547   if (!I->hasOneUse() || !isa<ReturnInst>(I->user_back()))
00548     return nullptr;
00549 
00550   // Ok, now we have to check all of the other return instructions in this
00551   // function.  If they return non-constants or differing values, then we cannot
00552   // transform the function safely.
00553   return getCommonReturnValue(cast<ReturnInst>(I->user_back()), CI);
00554 }
00555 
00556 static Instruction *FirstNonDbg(BasicBlock::iterator I) {
00557   while (isa<DbgInfoIntrinsic>(I))
00558     ++I;
00559   return &*I;
00560 }
00561 
00562 CallInst*
00563 TailCallElim::FindTRECandidate(Instruction *TI,
00564                                bool CannotTailCallElimCallsMarkedTail) {
00565   BasicBlock *BB = TI->getParent();
00566   Function *F = BB->getParent();
00567 
00568   if (&BB->front() == TI) // Make sure there is something before the terminator.
00569     return nullptr;
00570 
00571   // Scan backwards from the return, checking to see if there is a tail call in
00572   // this block.  If so, set CI to it.
00573   CallInst *CI = nullptr;
00574   BasicBlock::iterator BBI = TI;
00575   while (true) {
00576     CI = dyn_cast<CallInst>(BBI);
00577     if (CI && CI->getCalledFunction() == F)
00578       break;
00579 
00580     if (BBI == BB->begin())
00581       return nullptr;          // Didn't find a potential tail call.
00582     --BBI;
00583   }
00584 
00585   // If this call is marked as a tail call, and if there are dynamic allocas in
00586   // the function, we cannot perform this optimization.
00587   if (CI->isTailCall() && CannotTailCallElimCallsMarkedTail)
00588     return nullptr;
00589 
00590   // As a special case, detect code like this:
00591   //   double fabs(double f) { return __builtin_fabs(f); } // a 'fabs' call
00592   // and disable this xform in this case, because the code generator will
00593   // lower the call to fabs into inline code.
00594   if (BB == &F->getEntryBlock() &&
00595       FirstNonDbg(BB->front()) == CI &&
00596       FirstNonDbg(std::next(BB->begin())) == TI &&
00597       CI->getCalledFunction() &&
00598       !TTI->isLoweredToCall(CI->getCalledFunction())) {
00599     // A single-block function with just a call and a return. Check that
00600     // the arguments match.
00601     CallSite::arg_iterator I = CallSite(CI).arg_begin(),
00602                            E = CallSite(CI).arg_end();
00603     Function::arg_iterator FI = F->arg_begin(),
00604                            FE = F->arg_end();
00605     for (; I != E && FI != FE; ++I, ++FI)
00606       if (*I != &*FI) break;
00607     if (I == E && FI == FE)
00608       return nullptr;
00609   }
00610 
00611   return CI;
00612 }
00613 
00614 bool TailCallElim::EliminateRecursiveTailCall(CallInst *CI, ReturnInst *Ret,
00615                                        BasicBlock *&OldEntry,
00616                                        bool &TailCallsAreMarkedTail,
00617                                        SmallVectorImpl<PHINode *> &ArgumentPHIs,
00618                                        bool CannotTailCallElimCallsMarkedTail) {
00619   // If we are introducing accumulator recursion to eliminate operations after
00620   // the call instruction that are both associative and commutative, the initial
00621   // value for the accumulator is placed in this variable.  If this value is set
00622   // then we actually perform accumulator recursion elimination instead of
00623   // simple tail recursion elimination.  If the operation is an LLVM instruction
00624   // (eg: "add") then it is recorded in AccumulatorRecursionInstr.  If not, then
00625   // we are handling the case when the return instruction returns a constant C
00626   // which is different to the constant returned by other return instructions
00627   // (which is recorded in AccumulatorRecursionEliminationInitVal).  This is a
00628   // special case of accumulator recursion, the operation being "return C".
00629   Value *AccumulatorRecursionEliminationInitVal = nullptr;
00630   Instruction *AccumulatorRecursionInstr = nullptr;
00631 
00632   // Ok, we found a potential tail call.  We can currently only transform the
00633   // tail call if all of the instructions between the call and the return are
00634   // movable to above the call itself, leaving the call next to the return.
00635   // Check that this is the case now.
00636   BasicBlock::iterator BBI = CI;
00637   for (++BBI; &*BBI != Ret; ++BBI) {
00638     if (CanMoveAboveCall(BBI, CI)) continue;
00639 
00640     // If we can't move the instruction above the call, it might be because it
00641     // is an associative and commutative operation that could be transformed
00642     // using accumulator recursion elimination.  Check to see if this is the
00643     // case, and if so, remember the initial accumulator value for later.
00644     if ((AccumulatorRecursionEliminationInitVal =
00645                            CanTransformAccumulatorRecursion(BBI, CI))) {
00646       // Yes, this is accumulator recursion.  Remember which instruction
00647       // accumulates.
00648       AccumulatorRecursionInstr = BBI;
00649     } else {
00650       return false;   // Otherwise, we cannot eliminate the tail recursion!
00651     }
00652   }
00653 
00654   // We can only transform call/return pairs that either ignore the return value
00655   // of the call and return void, ignore the value of the call and return a
00656   // constant, return the value returned by the tail call, or that are being
00657   // accumulator recursion variable eliminated.
00658   if (Ret->getNumOperands() == 1 && Ret->getReturnValue() != CI &&
00659       !isa<UndefValue>(Ret->getReturnValue()) &&
00660       AccumulatorRecursionEliminationInitVal == nullptr &&
00661       !getCommonReturnValue(nullptr, CI)) {
00662     // One case remains that we are able to handle: the current return
00663     // instruction returns a constant, and all other return instructions
00664     // return a different constant.
00665     if (!isDynamicConstant(Ret->getReturnValue(), CI, Ret))
00666       return false; // Current return instruction does not return a constant.
00667     // Check that all other return instructions return a common constant.  If
00668     // so, record it in AccumulatorRecursionEliminationInitVal.
00669     AccumulatorRecursionEliminationInitVal = getCommonReturnValue(Ret, CI);
00670     if (!AccumulatorRecursionEliminationInitVal)
00671       return false;
00672   }
00673 
00674   BasicBlock *BB = Ret->getParent();
00675   Function *F = BB->getParent();
00676 
00677   emitOptimizationRemark(F->getContext(), "tailcallelim", *F, CI->getDebugLoc(),
00678                          "transforming tail recursion to loop");
00679 
00680   // OK! We can transform this tail call.  If this is the first one found,
00681   // create the new entry block, allowing us to branch back to the old entry.
00682   if (!OldEntry) {
00683     OldEntry = &F->getEntryBlock();
00684     BasicBlock *NewEntry = BasicBlock::Create(F->getContext(), "", F, OldEntry);
00685     NewEntry->takeName(OldEntry);
00686     OldEntry->setName("tailrecurse");
00687     BranchInst::Create(OldEntry, NewEntry);
00688 
00689     // If this tail call is marked 'tail' and if there are any allocas in the
00690     // entry block, move them up to the new entry block.
00691     TailCallsAreMarkedTail = CI->isTailCall();
00692     if (TailCallsAreMarkedTail)
00693       // Move all fixed sized allocas from OldEntry to NewEntry.
00694       for (BasicBlock::iterator OEBI = OldEntry->begin(), E = OldEntry->end(),
00695              NEBI = NewEntry->begin(); OEBI != E; )
00696         if (AllocaInst *AI = dyn_cast<AllocaInst>(OEBI++))
00697           if (isa<ConstantInt>(AI->getArraySize()))
00698             AI->moveBefore(NEBI);
00699 
00700     // Now that we have created a new block, which jumps to the entry
00701     // block, insert a PHI node for each argument of the function.
00702     // For now, we initialize each PHI to only have the real arguments
00703     // which are passed in.
00704     Instruction *InsertPos = OldEntry->begin();
00705     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
00706          I != E; ++I) {
00707       PHINode *PN = PHINode::Create(I->getType(), 2,
00708                                     I->getName() + ".tr", InsertPos);
00709       I->replaceAllUsesWith(PN); // Everyone use the PHI node now!
00710       PN->addIncoming(I, NewEntry);
00711       ArgumentPHIs.push_back(PN);
00712     }
00713   }
00714 
00715   // If this function has self recursive calls in the tail position where some
00716   // are marked tail and some are not, only transform one flavor or another.  We
00717   // have to choose whether we move allocas in the entry block to the new entry
00718   // block or not, so we can't make a good choice for both.  NOTE: We could do
00719   // slightly better here in the case that the function has no entry block
00720   // allocas.
00721   if (TailCallsAreMarkedTail && !CI->isTailCall())
00722     return false;
00723 
00724   // Ok, now that we know we have a pseudo-entry block WITH all of the
00725   // required PHI nodes, add entries into the PHI node for the actual
00726   // parameters passed into the tail-recursive call.
00727   for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i)
00728     ArgumentPHIs[i]->addIncoming(CI->getArgOperand(i), BB);
00729 
00730   // If we are introducing an accumulator variable to eliminate the recursion,
00731   // do so now.  Note that we _know_ that no subsequent tail recursion
00732   // eliminations will happen on this function because of the way the
00733   // accumulator recursion predicate is set up.
00734   //
00735   if (AccumulatorRecursionEliminationInitVal) {
00736     Instruction *AccRecInstr = AccumulatorRecursionInstr;
00737     // Start by inserting a new PHI node for the accumulator.
00738     pred_iterator PB = pred_begin(OldEntry), PE = pred_end(OldEntry);
00739     PHINode *AccPN =
00740       PHINode::Create(AccumulatorRecursionEliminationInitVal->getType(),
00741                       std::distance(PB, PE) + 1,
00742                       "accumulator.tr", OldEntry->begin());
00743 
00744     // Loop over all of the predecessors of the tail recursion block.  For the
00745     // real entry into the function we seed the PHI with the initial value,
00746     // computed earlier.  For any other existing branches to this block (due to
00747     // other tail recursions eliminated) the accumulator is not modified.
00748     // Because we haven't added the branch in the current block to OldEntry yet,
00749     // it will not show up as a predecessor.
00750     for (pred_iterator PI = PB; PI != PE; ++PI) {
00751       BasicBlock *P = *PI;
00752       if (P == &F->getEntryBlock())
00753         AccPN->addIncoming(AccumulatorRecursionEliminationInitVal, P);
00754       else
00755         AccPN->addIncoming(AccPN, P);
00756     }
00757 
00758     if (AccRecInstr) {
00759       // Add an incoming argument for the current block, which is computed by
00760       // our associative and commutative accumulator instruction.
00761       AccPN->addIncoming(AccRecInstr, BB);
00762 
00763       // Next, rewrite the accumulator recursion instruction so that it does not
00764       // use the result of the call anymore, instead, use the PHI node we just
00765       // inserted.
00766       AccRecInstr->setOperand(AccRecInstr->getOperand(0) != CI, AccPN);
00767     } else {
00768       // Add an incoming argument for the current block, which is just the
00769       // constant returned by the current return instruction.
00770       AccPN->addIncoming(Ret->getReturnValue(), BB);
00771     }
00772 
00773     // Finally, rewrite any return instructions in the program to return the PHI
00774     // node instead of the "initval" that they do currently.  This loop will
00775     // actually rewrite the return value we are destroying, but that's ok.
00776     for (Function::iterator BBI = F->begin(), E = F->end(); BBI != E; ++BBI)
00777       if (ReturnInst *RI = dyn_cast<ReturnInst>(BBI->getTerminator()))
00778         RI->setOperand(0, AccPN);
00779     ++NumAccumAdded;
00780   }
00781 
00782   // Now that all of the PHI nodes are in place, remove the call and
00783   // ret instructions, replacing them with an unconditional branch.
00784   BranchInst *NewBI = BranchInst::Create(OldEntry, Ret);
00785   NewBI->setDebugLoc(CI->getDebugLoc());
00786 
00787   BB->getInstList().erase(Ret);  // Remove return.
00788   BB->getInstList().erase(CI);   // Remove call.
00789   ++NumEliminated;
00790   return true;
00791 }
00792 
00793 bool TailCallElim::FoldReturnAndProcessPred(BasicBlock *BB,
00794                                        ReturnInst *Ret, BasicBlock *&OldEntry,
00795                                        bool &TailCallsAreMarkedTail,
00796                                        SmallVectorImpl<PHINode *> &ArgumentPHIs,
00797                                        bool CannotTailCallElimCallsMarkedTail) {
00798   bool Change = false;
00799 
00800   // If the return block contains nothing but the return and PHI's,
00801   // there might be an opportunity to duplicate the return in its
00802   // predecessors and perform TRC there. Look for predecessors that end
00803   // in unconditional branch and recursive call(s).
00804   SmallVector<BranchInst*, 8> UncondBranchPreds;
00805   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
00806     BasicBlock *Pred = *PI;
00807     TerminatorInst *PTI = Pred->getTerminator();
00808     if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
00809       if (BI->isUnconditional())
00810         UncondBranchPreds.push_back(BI);
00811   }
00812 
00813   while (!UncondBranchPreds.empty()) {
00814     BranchInst *BI = UncondBranchPreds.pop_back_val();
00815     BasicBlock *Pred = BI->getParent();
00816     if (CallInst *CI = FindTRECandidate(BI, CannotTailCallElimCallsMarkedTail)){
00817       DEBUG(dbgs() << "FOLDING: " << *BB
00818             << "INTO UNCOND BRANCH PRED: " << *Pred);
00819       ReturnInst *RI = FoldReturnIntoUncondBranch(Ret, BB, Pred);
00820 
00821       // Cleanup: if all predecessors of BB have been eliminated by
00822       // FoldReturnIntoUncondBranch, delete it.  It is important to empty it,
00823       // because the ret instruction in there is still using a value which
00824       // EliminateRecursiveTailCall will attempt to remove.
00825       if (!BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
00826         BB->eraseFromParent();
00827 
00828       EliminateRecursiveTailCall(CI, RI, OldEntry, TailCallsAreMarkedTail,
00829                                  ArgumentPHIs,
00830                                  CannotTailCallElimCallsMarkedTail);
00831       ++NumRetDuped;
00832       Change = true;
00833     }
00834   }
00835 
00836   return Change;
00837 }
00838 
00839 bool
00840 TailCallElim::ProcessReturningBlock(ReturnInst *Ret, BasicBlock *&OldEntry,
00841                                     bool &TailCallsAreMarkedTail,
00842                                     SmallVectorImpl<PHINode *> &ArgumentPHIs,
00843                                     bool CannotTailCallElimCallsMarkedTail) {
00844   CallInst *CI = FindTRECandidate(Ret, CannotTailCallElimCallsMarkedTail);
00845   if (!CI)
00846     return false;
00847 
00848   return EliminateRecursiveTailCall(CI, Ret, OldEntry, TailCallsAreMarkedTail,
00849                                     ArgumentPHIs,
00850                                     CannotTailCallElimCallsMarkedTail);
00851 }