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