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).second)
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   SmallVector<BasicBlock*, 8> BBToErase;
00408   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
00409     if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB->getTerminator())) {
00410       bool Change = ProcessReturningBlock(Ret, OldEntry, TailCallsAreMarkedTail,
00411                                           ArgumentPHIs, !CanTRETailMarkedCall);
00412       if (!Change && BB->getFirstNonPHIOrDbg() == Ret) {
00413         Change = FoldReturnAndProcessPred(BB, Ret, OldEntry,
00414                                           TailCallsAreMarkedTail, ArgumentPHIs,
00415                                           !CanTRETailMarkedCall);
00416         // FoldReturnAndProcessPred may have emptied some BB. Remember to
00417         // erase them.
00418         if (Change && BB->empty())
00419           BBToErase.push_back(BB);
00420 
00421       }
00422       MadeChange |= Change;
00423     }
00424   }
00425 
00426   for (auto BB: BBToErase)
00427     BB->eraseFromParent();
00428 
00429   // If we eliminated any tail recursions, it's possible that we inserted some
00430   // silly PHI nodes which just merge an initial value (the incoming operand)
00431   // with themselves.  Check to see if we did and clean up our mess if so.  This
00432   // occurs when a function passes an argument straight through to its tail
00433   // call.
00434   for (unsigned i = 0, e = ArgumentPHIs.size(); i != e; ++i) {
00435     PHINode *PN = ArgumentPHIs[i];
00436 
00437     // If the PHI Node is a dynamic constant, replace it with the value it is.
00438     if (Value *PNV = SimplifyInstruction(PN)) {
00439       PN->replaceAllUsesWith(PNV);
00440       PN->eraseFromParent();
00441     }
00442   }
00443 
00444   return MadeChange;
00445 }
00446 
00447 
00448 /// CanMoveAboveCall - Return true if it is safe to move the specified
00449 /// instruction from after the call to before the call, assuming that all
00450 /// instructions between the call and this instruction are movable.
00451 ///
00452 bool TailCallElim::CanMoveAboveCall(Instruction *I, CallInst *CI) {
00453   // FIXME: We can move load/store/call/free instructions above the call if the
00454   // call does not mod/ref the memory location being processed.
00455   if (I->mayHaveSideEffects())  // This also handles volatile loads.
00456     return false;
00457 
00458   if (LoadInst *L = dyn_cast<LoadInst>(I)) {
00459     // Loads may always be moved above calls without side effects.
00460     if (CI->mayHaveSideEffects()) {
00461       // Non-volatile loads may be moved above a call with side effects if it
00462       // does not write to memory and the load provably won't trap.
00463       // FIXME: Writes to memory only matter if they may alias the pointer
00464       // being loaded from.
00465       if (CI->mayWriteToMemory() ||
00466           !isSafeToLoadUnconditionally(L->getPointerOperand(), L,
00467                                        L->getAlignment(), DL))
00468         return false;
00469     }
00470   }
00471 
00472   // Otherwise, if this is a side-effect free instruction, check to make sure
00473   // that it does not use the return value of the call.  If it doesn't use the
00474   // return value of the call, it must only use things that are defined before
00475   // the call, or movable instructions between the call and the instruction
00476   // itself.
00477   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
00478     if (I->getOperand(i) == CI)
00479       return false;
00480   return true;
00481 }
00482 
00483 // isDynamicConstant - Return true if the specified value is the same when the
00484 // return would exit as it was when the initial iteration of the recursive
00485 // function was executed.
00486 //
00487 // We currently handle static constants and arguments that are not modified as
00488 // part of the recursion.
00489 //
00490 static bool isDynamicConstant(Value *V, CallInst *CI, ReturnInst *RI) {
00491   if (isa<Constant>(V)) return true; // Static constants are always dyn consts
00492 
00493   // Check to see if this is an immutable argument, if so, the value
00494   // will be available to initialize the accumulator.
00495   if (Argument *Arg = dyn_cast<Argument>(V)) {
00496     // Figure out which argument number this is...
00497     unsigned ArgNo = 0;
00498     Function *F = CI->getParent()->getParent();
00499     for (Function::arg_iterator AI = F->arg_begin(); &*AI != Arg; ++AI)
00500       ++ArgNo;
00501 
00502     // If we are passing this argument into call as the corresponding
00503     // argument operand, then the argument is dynamically constant.
00504     // Otherwise, we cannot transform this function safely.
00505     if (CI->getArgOperand(ArgNo) == Arg)
00506       return true;
00507   }
00508 
00509   // Switch cases are always constant integers. If the value is being switched
00510   // on and the return is only reachable from one of its cases, it's
00511   // effectively constant.
00512   if (BasicBlock *UniquePred = RI->getParent()->getUniquePredecessor())
00513     if (SwitchInst *SI = dyn_cast<SwitchInst>(UniquePred->getTerminator()))
00514       if (SI->getCondition() == V)
00515         return SI->getDefaultDest() != RI->getParent();
00516 
00517   // Not a constant or immutable argument, we can't safely transform.
00518   return false;
00519 }
00520 
00521 // getCommonReturnValue - Check to see if the function containing the specified
00522 // tail call consistently returns the same runtime-constant value at all exit
00523 // points except for IgnoreRI.  If so, return the returned value.
00524 //
00525 static Value *getCommonReturnValue(ReturnInst *IgnoreRI, CallInst *CI) {
00526   Function *F = CI->getParent()->getParent();
00527   Value *ReturnedValue = nullptr;
00528 
00529   for (Function::iterator BBI = F->begin(), E = F->end(); BBI != E; ++BBI) {
00530     ReturnInst *RI = dyn_cast<ReturnInst>(BBI->getTerminator());
00531     if (RI == nullptr || RI == IgnoreRI) continue;
00532 
00533     // We can only perform this transformation if the value returned is
00534     // evaluatable at the start of the initial invocation of the function,
00535     // instead of at the end of the evaluation.
00536     //
00537     Value *RetOp = RI->getOperand(0);
00538     if (!isDynamicConstant(RetOp, CI, RI))
00539       return nullptr;
00540 
00541     if (ReturnedValue && RetOp != ReturnedValue)
00542       return nullptr;     // Cannot transform if differing values are returned.
00543     ReturnedValue = RetOp;
00544   }
00545   return ReturnedValue;
00546 }
00547 
00548 /// CanTransformAccumulatorRecursion - If the specified instruction can be
00549 /// transformed using accumulator recursion elimination, return the constant
00550 /// which is the start of the accumulator value.  Otherwise return null.
00551 ///
00552 Value *TailCallElim::CanTransformAccumulatorRecursion(Instruction *I,
00553                                                       CallInst *CI) {
00554   if (!I->isAssociative() || !I->isCommutative()) return nullptr;
00555   assert(I->getNumOperands() == 2 &&
00556          "Associative/commutative operations should have 2 args!");
00557 
00558   // Exactly one operand should be the result of the call instruction.
00559   if ((I->getOperand(0) == CI && I->getOperand(1) == CI) ||
00560       (I->getOperand(0) != CI && I->getOperand(1) != CI))
00561     return nullptr;
00562 
00563   // The only user of this instruction we allow is a single return instruction.
00564   if (!I->hasOneUse() || !isa<ReturnInst>(I->user_back()))
00565     return nullptr;
00566 
00567   // Ok, now we have to check all of the other return instructions in this
00568   // function.  If they return non-constants or differing values, then we cannot
00569   // transform the function safely.
00570   return getCommonReturnValue(cast<ReturnInst>(I->user_back()), CI);
00571 }
00572 
00573 static Instruction *FirstNonDbg(BasicBlock::iterator I) {
00574   while (isa<DbgInfoIntrinsic>(I))
00575     ++I;
00576   return &*I;
00577 }
00578 
00579 CallInst*
00580 TailCallElim::FindTRECandidate(Instruction *TI,
00581                                bool CannotTailCallElimCallsMarkedTail) {
00582   BasicBlock *BB = TI->getParent();
00583   Function *F = BB->getParent();
00584 
00585   if (&BB->front() == TI) // Make sure there is something before the terminator.
00586     return nullptr;
00587 
00588   // Scan backwards from the return, checking to see if there is a tail call in
00589   // this block.  If so, set CI to it.
00590   CallInst *CI = nullptr;
00591   BasicBlock::iterator BBI = TI;
00592   while (true) {
00593     CI = dyn_cast<CallInst>(BBI);
00594     if (CI && CI->getCalledFunction() == F)
00595       break;
00596 
00597     if (BBI == BB->begin())
00598       return nullptr;          // Didn't find a potential tail call.
00599     --BBI;
00600   }
00601 
00602   // If this call is marked as a tail call, and if there are dynamic allocas in
00603   // the function, we cannot perform this optimization.
00604   if (CI->isTailCall() && CannotTailCallElimCallsMarkedTail)
00605     return nullptr;
00606 
00607   // As a special case, detect code like this:
00608   //   double fabs(double f) { return __builtin_fabs(f); } // a 'fabs' call
00609   // and disable this xform in this case, because the code generator will
00610   // lower the call to fabs into inline code.
00611   if (BB == &F->getEntryBlock() &&
00612       FirstNonDbg(BB->front()) == CI &&
00613       FirstNonDbg(std::next(BB->begin())) == TI &&
00614       CI->getCalledFunction() &&
00615       !TTI->isLoweredToCall(CI->getCalledFunction())) {
00616     // A single-block function with just a call and a return. Check that
00617     // the arguments match.
00618     CallSite::arg_iterator I = CallSite(CI).arg_begin(),
00619                            E = CallSite(CI).arg_end();
00620     Function::arg_iterator FI = F->arg_begin(),
00621                            FE = F->arg_end();
00622     for (; I != E && FI != FE; ++I, ++FI)
00623       if (*I != &*FI) break;
00624     if (I == E && FI == FE)
00625       return nullptr;
00626   }
00627 
00628   return CI;
00629 }
00630 
00631 bool TailCallElim::EliminateRecursiveTailCall(CallInst *CI, ReturnInst *Ret,
00632                                        BasicBlock *&OldEntry,
00633                                        bool &TailCallsAreMarkedTail,
00634                                        SmallVectorImpl<PHINode *> &ArgumentPHIs,
00635                                        bool CannotTailCallElimCallsMarkedTail) {
00636   // If we are introducing accumulator recursion to eliminate operations after
00637   // the call instruction that are both associative and commutative, the initial
00638   // value for the accumulator is placed in this variable.  If this value is set
00639   // then we actually perform accumulator recursion elimination instead of
00640   // simple tail recursion elimination.  If the operation is an LLVM instruction
00641   // (eg: "add") then it is recorded in AccumulatorRecursionInstr.  If not, then
00642   // we are handling the case when the return instruction returns a constant C
00643   // which is different to the constant returned by other return instructions
00644   // (which is recorded in AccumulatorRecursionEliminationInitVal).  This is a
00645   // special case of accumulator recursion, the operation being "return C".
00646   Value *AccumulatorRecursionEliminationInitVal = nullptr;
00647   Instruction *AccumulatorRecursionInstr = nullptr;
00648 
00649   // Ok, we found a potential tail call.  We can currently only transform the
00650   // tail call if all of the instructions between the call and the return are
00651   // movable to above the call itself, leaving the call next to the return.
00652   // Check that this is the case now.
00653   BasicBlock::iterator BBI = CI;
00654   for (++BBI; &*BBI != Ret; ++BBI) {
00655     if (CanMoveAboveCall(BBI, CI)) continue;
00656 
00657     // If we can't move the instruction above the call, it might be because it
00658     // is an associative and commutative operation that could be transformed
00659     // using accumulator recursion elimination.  Check to see if this is the
00660     // case, and if so, remember the initial accumulator value for later.
00661     if ((AccumulatorRecursionEliminationInitVal =
00662                            CanTransformAccumulatorRecursion(BBI, CI))) {
00663       // Yes, this is accumulator recursion.  Remember which instruction
00664       // accumulates.
00665       AccumulatorRecursionInstr = BBI;
00666     } else {
00667       return false;   // Otherwise, we cannot eliminate the tail recursion!
00668     }
00669   }
00670 
00671   // We can only transform call/return pairs that either ignore the return value
00672   // of the call and return void, ignore the value of the call and return a
00673   // constant, return the value returned by the tail call, or that are being
00674   // accumulator recursion variable eliminated.
00675   if (Ret->getNumOperands() == 1 && Ret->getReturnValue() != CI &&
00676       !isa<UndefValue>(Ret->getReturnValue()) &&
00677       AccumulatorRecursionEliminationInitVal == nullptr &&
00678       !getCommonReturnValue(nullptr, CI)) {
00679     // One case remains that we are able to handle: the current return
00680     // instruction returns a constant, and all other return instructions
00681     // return a different constant.
00682     if (!isDynamicConstant(Ret->getReturnValue(), CI, Ret))
00683       return false; // Current return instruction does not return a constant.
00684     // Check that all other return instructions return a common constant.  If
00685     // so, record it in AccumulatorRecursionEliminationInitVal.
00686     AccumulatorRecursionEliminationInitVal = getCommonReturnValue(Ret, CI);
00687     if (!AccumulatorRecursionEliminationInitVal)
00688       return false;
00689   }
00690 
00691   BasicBlock *BB = Ret->getParent();
00692   Function *F = BB->getParent();
00693 
00694   emitOptimizationRemark(F->getContext(), "tailcallelim", *F, CI->getDebugLoc(),
00695                          "transforming tail recursion to loop");
00696 
00697   // OK! We can transform this tail call.  If this is the first one found,
00698   // create the new entry block, allowing us to branch back to the old entry.
00699   if (!OldEntry) {
00700     OldEntry = &F->getEntryBlock();
00701     BasicBlock *NewEntry = BasicBlock::Create(F->getContext(), "", F, OldEntry);
00702     NewEntry->takeName(OldEntry);
00703     OldEntry->setName("tailrecurse");
00704     BranchInst::Create(OldEntry, NewEntry);
00705 
00706     // If this tail call is marked 'tail' and if there are any allocas in the
00707     // entry block, move them up to the new entry block.
00708     TailCallsAreMarkedTail = CI->isTailCall();
00709     if (TailCallsAreMarkedTail)
00710       // Move all fixed sized allocas from OldEntry to NewEntry.
00711       for (BasicBlock::iterator OEBI = OldEntry->begin(), E = OldEntry->end(),
00712              NEBI = NewEntry->begin(); OEBI != E; )
00713         if (AllocaInst *AI = dyn_cast<AllocaInst>(OEBI++))
00714           if (isa<ConstantInt>(AI->getArraySize()))
00715             AI->moveBefore(NEBI);
00716 
00717     // Now that we have created a new block, which jumps to the entry
00718     // block, insert a PHI node for each argument of the function.
00719     // For now, we initialize each PHI to only have the real arguments
00720     // which are passed in.
00721     Instruction *InsertPos = OldEntry->begin();
00722     for (Function::arg_iterator I = F->arg_begin(), E = F->arg_end();
00723          I != E; ++I) {
00724       PHINode *PN = PHINode::Create(I->getType(), 2,
00725                                     I->getName() + ".tr", InsertPos);
00726       I->replaceAllUsesWith(PN); // Everyone use the PHI node now!
00727       PN->addIncoming(I, NewEntry);
00728       ArgumentPHIs.push_back(PN);
00729     }
00730   }
00731 
00732   // If this function has self recursive calls in the tail position where some
00733   // are marked tail and some are not, only transform one flavor or another.  We
00734   // have to choose whether we move allocas in the entry block to the new entry
00735   // block or not, so we can't make a good choice for both.  NOTE: We could do
00736   // slightly better here in the case that the function has no entry block
00737   // allocas.
00738   if (TailCallsAreMarkedTail && !CI->isTailCall())
00739     return false;
00740 
00741   // Ok, now that we know we have a pseudo-entry block WITH all of the
00742   // required PHI nodes, add entries into the PHI node for the actual
00743   // parameters passed into the tail-recursive call.
00744   for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i)
00745     ArgumentPHIs[i]->addIncoming(CI->getArgOperand(i), BB);
00746 
00747   // If we are introducing an accumulator variable to eliminate the recursion,
00748   // do so now.  Note that we _know_ that no subsequent tail recursion
00749   // eliminations will happen on this function because of the way the
00750   // accumulator recursion predicate is set up.
00751   //
00752   if (AccumulatorRecursionEliminationInitVal) {
00753     Instruction *AccRecInstr = AccumulatorRecursionInstr;
00754     // Start by inserting a new PHI node for the accumulator.
00755     pred_iterator PB = pred_begin(OldEntry), PE = pred_end(OldEntry);
00756     PHINode *AccPN =
00757       PHINode::Create(AccumulatorRecursionEliminationInitVal->getType(),
00758                       std::distance(PB, PE) + 1,
00759                       "accumulator.tr", OldEntry->begin());
00760 
00761     // Loop over all of the predecessors of the tail recursion block.  For the
00762     // real entry into the function we seed the PHI with the initial value,
00763     // computed earlier.  For any other existing branches to this block (due to
00764     // other tail recursions eliminated) the accumulator is not modified.
00765     // Because we haven't added the branch in the current block to OldEntry yet,
00766     // it will not show up as a predecessor.
00767     for (pred_iterator PI = PB; PI != PE; ++PI) {
00768       BasicBlock *P = *PI;
00769       if (P == &F->getEntryBlock())
00770         AccPN->addIncoming(AccumulatorRecursionEliminationInitVal, P);
00771       else
00772         AccPN->addIncoming(AccPN, P);
00773     }
00774 
00775     if (AccRecInstr) {
00776       // Add an incoming argument for the current block, which is computed by
00777       // our associative and commutative accumulator instruction.
00778       AccPN->addIncoming(AccRecInstr, BB);
00779 
00780       // Next, rewrite the accumulator recursion instruction so that it does not
00781       // use the result of the call anymore, instead, use the PHI node we just
00782       // inserted.
00783       AccRecInstr->setOperand(AccRecInstr->getOperand(0) != CI, AccPN);
00784     } else {
00785       // Add an incoming argument for the current block, which is just the
00786       // constant returned by the current return instruction.
00787       AccPN->addIncoming(Ret->getReturnValue(), BB);
00788     }
00789 
00790     // Finally, rewrite any return instructions in the program to return the PHI
00791     // node instead of the "initval" that they do currently.  This loop will
00792     // actually rewrite the return value we are destroying, but that's ok.
00793     for (Function::iterator BBI = F->begin(), E = F->end(); BBI != E; ++BBI)
00794       if (ReturnInst *RI = dyn_cast<ReturnInst>(BBI->getTerminator()))
00795         RI->setOperand(0, AccPN);
00796     ++NumAccumAdded;
00797   }
00798 
00799   // Now that all of the PHI nodes are in place, remove the call and
00800   // ret instructions, replacing them with an unconditional branch.
00801   BranchInst *NewBI = BranchInst::Create(OldEntry, Ret);
00802   NewBI->setDebugLoc(CI->getDebugLoc());
00803 
00804   BB->getInstList().erase(Ret);  // Remove return.
00805   BB->getInstList().erase(CI);   // Remove call.
00806   ++NumEliminated;
00807   return true;
00808 }
00809 
00810 bool TailCallElim::FoldReturnAndProcessPred(BasicBlock *BB,
00811                                        ReturnInst *Ret, BasicBlock *&OldEntry,
00812                                        bool &TailCallsAreMarkedTail,
00813                                        SmallVectorImpl<PHINode *> &ArgumentPHIs,
00814                                        bool CannotTailCallElimCallsMarkedTail) {
00815   bool Change = false;
00816 
00817   // If the return block contains nothing but the return and PHI's,
00818   // there might be an opportunity to duplicate the return in its
00819   // predecessors and perform TRC there. Look for predecessors that end
00820   // in unconditional branch and recursive call(s).
00821   SmallVector<BranchInst*, 8> UncondBranchPreds;
00822   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
00823     BasicBlock *Pred = *PI;
00824     TerminatorInst *PTI = Pred->getTerminator();
00825     if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
00826       if (BI->isUnconditional())
00827         UncondBranchPreds.push_back(BI);
00828   }
00829 
00830   while (!UncondBranchPreds.empty()) {
00831     BranchInst *BI = UncondBranchPreds.pop_back_val();
00832     BasicBlock *Pred = BI->getParent();
00833     if (CallInst *CI = FindTRECandidate(BI, CannotTailCallElimCallsMarkedTail)){
00834       DEBUG(dbgs() << "FOLDING: " << *BB
00835             << "INTO UNCOND BRANCH PRED: " << *Pred);
00836       ReturnInst *RI = FoldReturnIntoUncondBranch(Ret, BB, Pred);
00837 
00838       // Cleanup: if all predecessors of BB have been eliminated by
00839       // FoldReturnIntoUncondBranch, we would like to delete it, but we
00840       // can not just nuke it as it is being used as an iterator by our caller.
00841       // Just empty it, and the caller will erase it when it is safe to do so.
00842       // It is important to empty it, because the ret instruction in there is
00843       // still using a value which EliminateRecursiveTailCall will attempt
00844       // to remove.
00845       if (!BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
00846         BB->getInstList().clear();
00847 
00848       EliminateRecursiveTailCall(CI, RI, OldEntry, TailCallsAreMarkedTail,
00849                                  ArgumentPHIs,
00850                                  CannotTailCallElimCallsMarkedTail);
00851       ++NumRetDuped;
00852       Change = true;
00853     }
00854   }
00855 
00856   return Change;
00857 }
00858 
00859 bool
00860 TailCallElim::ProcessReturningBlock(ReturnInst *Ret, BasicBlock *&OldEntry,
00861                                     bool &TailCallsAreMarkedTail,
00862                                     SmallVectorImpl<PHINode *> &ArgumentPHIs,
00863                                     bool CannotTailCallElimCallsMarkedTail) {
00864   CallInst *CI = FindTRECandidate(Ret, CannotTailCallElimCallsMarkedTail);
00865   if (!CI)
00866     return false;
00867 
00868   return EliminateRecursiveTailCall(CI, Ret, OldEntry, TailCallsAreMarkedTail,
00869                                     ArgumentPHIs,
00870                                     CannotTailCallElimCallsMarkedTail);
00871 }