1 //===- TailRecursionElimination.cpp - Eliminate Tail Calls ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file transforms calls of the current function (self recursion) followed
10 // by a return instruction with a branch to the entry of the function, creating
11 // a loop.  This pass also implements the following extensions to the basic
12 // algorithm:
13 //
14 //  1. Trivial instructions between the call and return do not prevent the
15 //     transformation from taking place, though currently the analysis cannot
16 //     support moving any really useful instructions (only dead ones).
17 //  2. This pass transforms functions that are prevented from being tail
18 //     recursive by an associative and commutative expression to use an
19 //     accumulator variable, thus compiling the typical naive factorial or
20 //     'fib' implementation into efficient code.
21 //  3. TRE is performed if the function returns void, if the return
22 //     returns the result returned by the call, or if the function returns a
23 //     run-time constant on all exits from the function.  It is possible, though
24 //     unlikely, that the return returns something else (like constant 0), and
25 //     can still be TRE'd.  It can be TRE'd if ALL OTHER return instructions in
26 //     the function return the exact same value.
27 //  4. If it can prove that callees do not access their caller stack frame,
28 //     they are marked as eligible for tail call elimination (by the code
29 //     generator).
30 //
31 // There are several improvements that could be made:
32 //
33 //  1. If the function has any alloca instructions, these instructions will be
34 //     moved out of the entry block of the function, causing them to be
35 //     evaluated each time through the tail recursion.  Safely keeping allocas
36 //     in the entry block requires analysis to proves that the tail-called
37 //     function does not read or write the stack object.
38 //  2. Tail recursion is only performed if the call immediately precedes the
39 //     return instruction.  It's possible that there could be a jump between
40 //     the call and the return.
41 //  3. There can be intervening operations between the call and the return that
42 //     prevent the TRE from occurring.  For example, there could be GEP's and
43 //     stores to memory that will not be read or written by the call.  This
44 //     requires some substantial analysis (such as with DSA) to prove safe to
45 //     move ahead of the call, but doing so could allow many more TREs to be
46 //     performed, for example in TreeAdd/TreeAlloc from the treeadd benchmark.
47 //  4. The algorithm we use to detect if callees access their caller stack
48 //     frames is very primitive.
49 //
50 //===----------------------------------------------------------------------===//
51 
52 #include "llvm/Transforms/Scalar/TailRecursionElimination.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include "llvm/ADT/SmallPtrSet.h"
55 #include "llvm/ADT/Statistic.h"
56 #include "llvm/Analysis/CFG.h"
57 #include "llvm/Analysis/CaptureTracking.h"
58 #include "llvm/Analysis/DomTreeUpdater.h"
59 #include "llvm/Analysis/GlobalsModRef.h"
60 #include "llvm/Analysis/InlineCost.h"
61 #include "llvm/Analysis/InstructionSimplify.h"
62 #include "llvm/Analysis/Loads.h"
63 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
64 #include "llvm/Analysis/PostDominators.h"
65 #include "llvm/Analysis/TargetTransformInfo.h"
66 #include "llvm/IR/CFG.h"
67 #include "llvm/IR/Constants.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DerivedTypes.h"
70 #include "llvm/IR/DiagnosticInfo.h"
71 #include "llvm/IR/Dominators.h"
72 #include "llvm/IR/Function.h"
73 #include "llvm/IR/InstIterator.h"
74 #include "llvm/IR/Instructions.h"
75 #include "llvm/IR/IntrinsicInst.h"
76 #include "llvm/IR/Module.h"
77 #include "llvm/IR/ValueHandle.h"
78 #include "llvm/InitializePasses.h"
79 #include "llvm/Pass.h"
80 #include "llvm/Support/Debug.h"
81 #include "llvm/Support/raw_ostream.h"
82 #include "llvm/Transforms/Scalar.h"
83 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
84 using namespace llvm;
85 
86 #define DEBUG_TYPE "tailcallelim"
87 
88 STATISTIC(NumEliminated, "Number of tail calls removed");
89 STATISTIC(NumRetDuped,   "Number of return duplicated");
90 STATISTIC(NumAccumAdded, "Number of accumulators introduced");
91 
92 /// Scan the specified function for alloca instructions.
93 /// If it contains any dynamic allocas, returns false.
94 static bool canTRE(Function &F) {
95   // Because of PR962, we don't TRE dynamic allocas.
96   return llvm::all_of(instructions(F), [](Instruction &I) {
97     auto *AI = dyn_cast<AllocaInst>(&I);
98     return !AI || AI->isStaticAlloca();
99   });
100 }
101 
102 namespace {
103 struct AllocaDerivedValueTracker {
104   // Start at a root value and walk its use-def chain to mark calls that use the
105   // value or a derived value in AllocaUsers, and places where it may escape in
106   // EscapePoints.
107   void walk(Value *Root) {
108     SmallVector<Use *, 32> Worklist;
109     SmallPtrSet<Use *, 32> Visited;
110 
111     auto AddUsesToWorklist = [&](Value *V) {
112       for (auto &U : V->uses()) {
113         if (!Visited.insert(&U).second)
114           continue;
115         Worklist.push_back(&U);
116       }
117     };
118 
119     AddUsesToWorklist(Root);
120 
121     while (!Worklist.empty()) {
122       Use *U = Worklist.pop_back_val();
123       Instruction *I = cast<Instruction>(U->getUser());
124 
125       switch (I->getOpcode()) {
126       case Instruction::Call:
127       case Instruction::Invoke: {
128         auto &CB = cast<CallBase>(*I);
129         // If the alloca-derived argument is passed byval it is not an escape
130         // point, or a use of an alloca. Calling with byval copies the contents
131         // of the alloca into argument registers or stack slots, which exist
132         // beyond the lifetime of the current frame.
133         if (CB.isArgOperand(U) && CB.isByValArgument(CB.getArgOperandNo(U)))
134           continue;
135         bool IsNocapture =
136             CB.isDataOperand(U) && CB.doesNotCapture(CB.getDataOperandNo(U));
137         callUsesLocalStack(CB, IsNocapture);
138         if (IsNocapture) {
139           // If the alloca-derived argument is passed in as nocapture, then it
140           // can't propagate to the call's return. That would be capturing.
141           continue;
142         }
143         break;
144       }
145       case Instruction::Load: {
146         // The result of a load is not alloca-derived (unless an alloca has
147         // otherwise escaped, but this is a local analysis).
148         continue;
149       }
150       case Instruction::Store: {
151         if (U->getOperandNo() == 0)
152           EscapePoints.insert(I);
153         continue;  // Stores have no users to analyze.
154       }
155       case Instruction::BitCast:
156       case Instruction::GetElementPtr:
157       case Instruction::PHI:
158       case Instruction::Select:
159       case Instruction::AddrSpaceCast:
160         break;
161       default:
162         EscapePoints.insert(I);
163         break;
164       }
165 
166       AddUsesToWorklist(I);
167     }
168   }
169 
170   void callUsesLocalStack(CallBase &CB, bool IsNocapture) {
171     // Add it to the list of alloca users.
172     AllocaUsers.insert(&CB);
173 
174     // If it's nocapture then it can't capture this alloca.
175     if (IsNocapture)
176       return;
177 
178     // If it can write to memory, it can leak the alloca value.
179     if (!CB.onlyReadsMemory())
180       EscapePoints.insert(&CB);
181   }
182 
183   SmallPtrSet<Instruction *, 32> AllocaUsers;
184   SmallPtrSet<Instruction *, 32> EscapePoints;
185 };
186 }
187 
188 static bool markTails(Function &F, bool &AllCallsAreTailCalls,
189                       OptimizationRemarkEmitter *ORE) {
190   if (F.callsFunctionThatReturnsTwice())
191     return false;
192   AllCallsAreTailCalls = true;
193 
194   // The local stack holds all alloca instructions and all byval arguments.
195   AllocaDerivedValueTracker Tracker;
196   for (Argument &Arg : F.args()) {
197     if (Arg.hasByValAttr())
198       Tracker.walk(&Arg);
199   }
200   for (auto &BB : F) {
201     for (auto &I : BB)
202       if (AllocaInst *AI = dyn_cast<AllocaInst>(&I))
203         Tracker.walk(AI);
204   }
205 
206   bool Modified = false;
207 
208   // Track whether a block is reachable after an alloca has escaped. Blocks that
209   // contain the escaping instruction will be marked as being visited without an
210   // escaped alloca, since that is how the block began.
211   enum VisitType {
212     UNVISITED,
213     UNESCAPED,
214     ESCAPED
215   };
216   DenseMap<BasicBlock *, VisitType> Visited;
217 
218   // We propagate the fact that an alloca has escaped from block to successor.
219   // Visit the blocks that are propagating the escapedness first. To do this, we
220   // maintain two worklists.
221   SmallVector<BasicBlock *, 32> WorklistUnescaped, WorklistEscaped;
222 
223   // We may enter a block and visit it thinking that no alloca has escaped yet,
224   // then see an escape point and go back around a loop edge and come back to
225   // the same block twice. Because of this, we defer setting tail on calls when
226   // we first encounter them in a block. Every entry in this list does not
227   // statically use an alloca via use-def chain analysis, but may find an alloca
228   // through other means if the block turns out to be reachable after an escape
229   // point.
230   SmallVector<CallInst *, 32> DeferredTails;
231 
232   BasicBlock *BB = &F.getEntryBlock();
233   VisitType Escaped = UNESCAPED;
234   do {
235     for (auto &I : *BB) {
236       if (Tracker.EscapePoints.count(&I))
237         Escaped = ESCAPED;
238 
239       CallInst *CI = dyn_cast<CallInst>(&I);
240       if (!CI || CI->isTailCall() || isa<DbgInfoIntrinsic>(&I))
241         continue;
242 
243       bool IsNoTail = CI->isNoTailCall() || CI->hasOperandBundles();
244 
245       if (!IsNoTail && CI->doesNotAccessMemory()) {
246         // A call to a readnone function whose arguments are all things computed
247         // outside this function can be marked tail. Even if you stored the
248         // alloca address into a global, a readnone function can't load the
249         // global anyhow.
250         //
251         // Note that this runs whether we know an alloca has escaped or not. If
252         // it has, then we can't trust Tracker.AllocaUsers to be accurate.
253         bool SafeToTail = true;
254         for (auto &Arg : CI->arg_operands()) {
255           if (isa<Constant>(Arg.getUser()))
256             continue;
257           if (Argument *A = dyn_cast<Argument>(Arg.getUser()))
258             if (!A->hasByValAttr())
259               continue;
260           SafeToTail = false;
261           break;
262         }
263         if (SafeToTail) {
264           using namespace ore;
265           ORE->emit([&]() {
266             return OptimizationRemark(DEBUG_TYPE, "tailcall-readnone", CI)
267                    << "marked as tail call candidate (readnone)";
268           });
269           CI->setTailCall();
270           Modified = true;
271           continue;
272         }
273       }
274 
275       if (!IsNoTail && Escaped == UNESCAPED && !Tracker.AllocaUsers.count(CI)) {
276         DeferredTails.push_back(CI);
277       } else {
278         AllCallsAreTailCalls = false;
279       }
280     }
281 
282     for (auto *SuccBB : make_range(succ_begin(BB), succ_end(BB))) {
283       auto &State = Visited[SuccBB];
284       if (State < Escaped) {
285         State = Escaped;
286         if (State == ESCAPED)
287           WorklistEscaped.push_back(SuccBB);
288         else
289           WorklistUnescaped.push_back(SuccBB);
290       }
291     }
292 
293     if (!WorklistEscaped.empty()) {
294       BB = WorklistEscaped.pop_back_val();
295       Escaped = ESCAPED;
296     } else {
297       BB = nullptr;
298       while (!WorklistUnescaped.empty()) {
299         auto *NextBB = WorklistUnescaped.pop_back_val();
300         if (Visited[NextBB] == UNESCAPED) {
301           BB = NextBB;
302           Escaped = UNESCAPED;
303           break;
304         }
305       }
306     }
307   } while (BB);
308 
309   for (CallInst *CI : DeferredTails) {
310     if (Visited[CI->getParent()] != ESCAPED) {
311       // If the escape point was part way through the block, calls after the
312       // escape point wouldn't have been put into DeferredTails.
313       LLVM_DEBUG(dbgs() << "Marked as tail call candidate: " << *CI << "\n");
314       CI->setTailCall();
315       Modified = true;
316     } else {
317       AllCallsAreTailCalls = false;
318     }
319   }
320 
321   return Modified;
322 }
323 
324 /// Return true if it is safe to move the specified
325 /// instruction from after the call to before the call, assuming that all
326 /// instructions between the call and this instruction are movable.
327 ///
328 static bool canMoveAboveCall(Instruction *I, CallInst *CI, AliasAnalysis *AA) {
329   // FIXME: We can move load/store/call/free instructions above the call if the
330   // call does not mod/ref the memory location being processed.
331   if (I->mayHaveSideEffects())  // This also handles volatile loads.
332     return false;
333 
334   if (LoadInst *L = dyn_cast<LoadInst>(I)) {
335     // Loads may always be moved above calls without side effects.
336     if (CI->mayHaveSideEffects()) {
337       // Non-volatile loads may be moved above a call with side effects if it
338       // does not write to memory and the load provably won't trap.
339       // Writes to memory only matter if they may alias the pointer
340       // being loaded from.
341       const DataLayout &DL = L->getModule()->getDataLayout();
342       if (isModSet(AA->getModRefInfo(CI, MemoryLocation::get(L))) ||
343           !isSafeToLoadUnconditionally(L->getPointerOperand(), L->getType(),
344                                        MaybeAlign(L->getAlignment()), DL, L))
345         return false;
346     }
347   }
348 
349   // Otherwise, if this is a side-effect free instruction, check to make sure
350   // that it does not use the return value of the call.  If it doesn't use the
351   // return value of the call, it must only use things that are defined before
352   // the call, or movable instructions between the call and the instruction
353   // itself.
354   return !is_contained(I->operands(), CI);
355 }
356 
357 /// Return true if the specified value is the same when the return would exit
358 /// as it was when the initial iteration of the recursive function was executed.
359 ///
360 /// We currently handle static constants and arguments that are not modified as
361 /// part of the recursion.
362 static bool isDynamicConstant(Value *V, CallInst *CI, ReturnInst *RI) {
363   if (isa<Constant>(V)) return true; // Static constants are always dyn consts
364 
365   // Check to see if this is an immutable argument, if so, the value
366   // will be available to initialize the accumulator.
367   if (Argument *Arg = dyn_cast<Argument>(V)) {
368     // Figure out which argument number this is...
369     unsigned ArgNo = 0;
370     Function *F = CI->getParent()->getParent();
371     for (Function::arg_iterator AI = F->arg_begin(); &*AI != Arg; ++AI)
372       ++ArgNo;
373 
374     // If we are passing this argument into call as the corresponding
375     // argument operand, then the argument is dynamically constant.
376     // Otherwise, we cannot transform this function safely.
377     if (CI->getArgOperand(ArgNo) == Arg)
378       return true;
379   }
380 
381   // Switch cases are always constant integers. If the value is being switched
382   // on and the return is only reachable from one of its cases, it's
383   // effectively constant.
384   if (BasicBlock *UniquePred = RI->getParent()->getUniquePredecessor())
385     if (SwitchInst *SI = dyn_cast<SwitchInst>(UniquePred->getTerminator()))
386       if (SI->getCondition() == V)
387         return SI->getDefaultDest() != RI->getParent();
388 
389   // Not a constant or immutable argument, we can't safely transform.
390   return false;
391 }
392 
393 /// Check to see if the function containing the specified tail call consistently
394 /// returns the same runtime-constant value at all exit points except for
395 /// IgnoreRI. If so, return the returned value.
396 static Value *getCommonReturnValue(ReturnInst *IgnoreRI, CallInst *CI) {
397   Function *F = CI->getParent()->getParent();
398   Value *ReturnedValue = nullptr;
399 
400   for (BasicBlock &BBI : *F) {
401     ReturnInst *RI = dyn_cast<ReturnInst>(BBI.getTerminator());
402     if (RI == nullptr || RI == IgnoreRI) continue;
403 
404     // We can only perform this transformation if the value returned is
405     // evaluatable at the start of the initial invocation of the function,
406     // instead of at the end of the evaluation.
407     //
408     Value *RetOp = RI->getOperand(0);
409     if (!isDynamicConstant(RetOp, CI, RI))
410       return nullptr;
411 
412     if (ReturnedValue && RetOp != ReturnedValue)
413       return nullptr;     // Cannot transform if differing values are returned.
414     ReturnedValue = RetOp;
415   }
416   return ReturnedValue;
417 }
418 
419 /// If the specified instruction can be transformed using accumulator recursion
420 /// elimination, return the constant which is the start of the accumulator
421 /// value.  Otherwise return null.
422 static Value *canTransformAccumulatorRecursion(Instruction *I, CallInst *CI) {
423   if (!I->isAssociative() || !I->isCommutative()) return nullptr;
424   assert(I->getNumOperands() == 2 &&
425          "Associative/commutative operations should have 2 args!");
426 
427   // Exactly one operand should be the result of the call instruction.
428   if ((I->getOperand(0) == CI && I->getOperand(1) == CI) ||
429       (I->getOperand(0) != CI && I->getOperand(1) != CI))
430     return nullptr;
431 
432   // The only user of this instruction we allow is a single return instruction.
433   if (!I->hasOneUse() || !isa<ReturnInst>(I->user_back()))
434     return nullptr;
435 
436   // Ok, now we have to check all of the other return instructions in this
437   // function.  If they return non-constants or differing values, then we cannot
438   // transform the function safely.
439   return getCommonReturnValue(cast<ReturnInst>(I->user_back()), CI);
440 }
441 
442 static Instruction *firstNonDbg(BasicBlock::iterator I) {
443   while (isa<DbgInfoIntrinsic>(I))
444     ++I;
445   return &*I;
446 }
447 
448 namespace {
449 class TailRecursionEliminator {
450   Function &F;
451   const TargetTransformInfo *TTI;
452   AliasAnalysis *AA;
453   OptimizationRemarkEmitter *ORE;
454   DomTreeUpdater &DTU;
455 
456   // The below are shared state we want to have available when eliminating any
457   // calls in the function. There values should be populated by
458   // createTailRecurseLoopHeader the first time we find a call we can eliminate.
459   BasicBlock *HeaderBB = nullptr;
460   SmallVector<PHINode *, 8> ArgumentPHIs;
461   bool RemovableCallsMustBeMarkedTail = false;
462 
463   TailRecursionEliminator(Function &F, const TargetTransformInfo *TTI,
464                           AliasAnalysis *AA, OptimizationRemarkEmitter *ORE,
465                           DomTreeUpdater &DTU)
466       : F(F), TTI(TTI), AA(AA), ORE(ORE), DTU(DTU) {}
467 
468   CallInst *findTRECandidate(Instruction *TI,
469                              bool CannotTailCallElimCallsMarkedTail);
470 
471   void createTailRecurseLoopHeader(CallInst *CI);
472 
473   PHINode *insertAccumulator(Value *AccumulatorRecursionEliminationInitVal);
474 
475   bool eliminateCall(CallInst *CI);
476 
477   bool foldReturnAndProcessPred(ReturnInst *Ret,
478                                 bool CannotTailCallElimCallsMarkedTail);
479 
480   bool processReturningBlock(ReturnInst *Ret,
481                              bool CannotTailCallElimCallsMarkedTail);
482 
483   void cleanupAndFinalize();
484 
485 public:
486   static bool eliminate(Function &F, const TargetTransformInfo *TTI,
487                         AliasAnalysis *AA, OptimizationRemarkEmitter *ORE,
488                         DomTreeUpdater &DTU);
489 };
490 } // namespace
491 
492 CallInst *TailRecursionEliminator::findTRECandidate(
493     Instruction *TI, bool CannotTailCallElimCallsMarkedTail) {
494   BasicBlock *BB = TI->getParent();
495 
496   if (&BB->front() == TI) // Make sure there is something before the terminator.
497     return nullptr;
498 
499   // Scan backwards from the return, checking to see if there is a tail call in
500   // this block.  If so, set CI to it.
501   CallInst *CI = nullptr;
502   BasicBlock::iterator BBI(TI);
503   while (true) {
504     CI = dyn_cast<CallInst>(BBI);
505     if (CI && CI->getCalledFunction() == &F)
506       break;
507 
508     if (BBI == BB->begin())
509       return nullptr;          // Didn't find a potential tail call.
510     --BBI;
511   }
512 
513   // If this call is marked as a tail call, and if there are dynamic allocas in
514   // the function, we cannot perform this optimization.
515   if (CI->isTailCall() && CannotTailCallElimCallsMarkedTail)
516     return nullptr;
517 
518   // As a special case, detect code like this:
519   //   double fabs(double f) { return __builtin_fabs(f); } // a 'fabs' call
520   // and disable this xform in this case, because the code generator will
521   // lower the call to fabs into inline code.
522   if (BB == &F.getEntryBlock() &&
523       firstNonDbg(BB->front().getIterator()) == CI &&
524       firstNonDbg(std::next(BB->begin())) == TI && CI->getCalledFunction() &&
525       !TTI->isLoweredToCall(CI->getCalledFunction())) {
526     // A single-block function with just a call and a return. Check that
527     // the arguments match.
528     auto I = CI->arg_begin(), E = CI->arg_end();
529     Function::arg_iterator FI = F.arg_begin(), FE = F.arg_end();
530     for (; I != E && FI != FE; ++I, ++FI)
531       if (*I != &*FI) break;
532     if (I == E && FI == FE)
533       return nullptr;
534   }
535 
536   return CI;
537 }
538 
539 void TailRecursionEliminator::createTailRecurseLoopHeader(CallInst *CI) {
540   HeaderBB = &F.getEntryBlock();
541   BasicBlock *NewEntry = BasicBlock::Create(F.getContext(), "", &F, HeaderBB);
542   NewEntry->takeName(HeaderBB);
543   HeaderBB->setName("tailrecurse");
544   BranchInst *BI = BranchInst::Create(HeaderBB, NewEntry);
545   BI->setDebugLoc(CI->getDebugLoc());
546 
547   // If this function has self recursive calls in the tail position where some
548   // are marked tail and some are not, only transform one flavor or another.
549   // We have to choose whether we move allocas in the entry block to the new
550   // entry block or not, so we can't make a good choice for both. We make this
551   // decision here based on whether the first call we found to remove is
552   // marked tail.
553   // NOTE: We could do slightly better here in the case that the function has
554   // no entry block allocas.
555   RemovableCallsMustBeMarkedTail = CI->isTailCall();
556 
557   // If this tail call is marked 'tail' and if there are any allocas in the
558   // entry block, move them up to the new entry block.
559   if (RemovableCallsMustBeMarkedTail)
560     // Move all fixed sized allocas from HeaderBB to NewEntry.
561     for (BasicBlock::iterator OEBI = HeaderBB->begin(), E = HeaderBB->end(),
562                               NEBI = NewEntry->begin();
563          OEBI != E;)
564       if (AllocaInst *AI = dyn_cast<AllocaInst>(OEBI++))
565         if (isa<ConstantInt>(AI->getArraySize()))
566           AI->moveBefore(&*NEBI);
567 
568   // Now that we have created a new block, which jumps to the entry
569   // block, insert a PHI node for each argument of the function.
570   // For now, we initialize each PHI to only have the real arguments
571   // which are passed in.
572   Instruction *InsertPos = &HeaderBB->front();
573   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
574     PHINode *PN =
575         PHINode::Create(I->getType(), 2, I->getName() + ".tr", InsertPos);
576     I->replaceAllUsesWith(PN); // Everyone use the PHI node now!
577     PN->addIncoming(&*I, NewEntry);
578     ArgumentPHIs.push_back(PN);
579   }
580   // The entry block was changed from HeaderBB to NewEntry.
581   // The forward DominatorTree needs to be recalculated when the EntryBB is
582   // changed. In this corner-case we recalculate the entire tree.
583   DTU.recalculate(*NewEntry->getParent());
584 }
585 
586 PHINode *TailRecursionEliminator::insertAccumulator(
587     Value *AccumulatorRecursionEliminationInitVal) {
588   // Start by inserting a new PHI node for the accumulator.
589   pred_iterator PB = pred_begin(HeaderBB), PE = pred_end(HeaderBB);
590   PHINode *AccPN = PHINode::Create(
591       AccumulatorRecursionEliminationInitVal->getType(),
592       std::distance(PB, PE) + 1, "accumulator.tr", &HeaderBB->front());
593 
594   // Loop over all of the predecessors of the tail recursion block.  For the
595   // real entry into the function we seed the PHI with the initial value,
596   // computed earlier.  For any other existing branches to this block (due to
597   // other tail recursions eliminated) the accumulator is not modified.
598   // Because we haven't added the branch in the current block to HeaderBB yet,
599   // it will not show up as a predecessor.
600   for (pred_iterator PI = PB; PI != PE; ++PI) {
601     BasicBlock *P = *PI;
602     if (P == &F.getEntryBlock())
603       AccPN->addIncoming(AccumulatorRecursionEliminationInitVal, P);
604     else
605       AccPN->addIncoming(AccPN, P);
606   }
607 
608   return AccPN;
609 }
610 
611 bool TailRecursionEliminator::eliminateCall(CallInst *CI) {
612   ReturnInst *Ret = cast<ReturnInst>(CI->getParent()->getTerminator());
613 
614   // If we are introducing accumulator recursion to eliminate operations after
615   // the call instruction that are both associative and commutative, the initial
616   // value for the accumulator is placed in this variable.  If this value is set
617   // then we actually perform accumulator recursion elimination instead of
618   // simple tail recursion elimination.  If the operation is an LLVM instruction
619   // (eg: "add") then it is recorded in AccumulatorRecursionInstr.  If not, then
620   // we are handling the case when the return instruction returns a constant C
621   // which is different to the constant returned by other return instructions
622   // (which is recorded in AccumulatorRecursionEliminationInitVal).  This is a
623   // special case of accumulator recursion, the operation being "return C".
624   Value *AccumulatorRecursionEliminationInitVal = nullptr;
625   Instruction *AccumulatorRecursionInstr = nullptr;
626 
627   // Ok, we found a potential tail call.  We can currently only transform the
628   // tail call if all of the instructions between the call and the return are
629   // movable to above the call itself, leaving the call next to the return.
630   // Check that this is the case now.
631   BasicBlock::iterator BBI(CI);
632   for (++BBI; &*BBI != Ret; ++BBI) {
633     if (canMoveAboveCall(&*BBI, CI, AA))
634       continue;
635 
636     // If we can't move the instruction above the call, it might be because it
637     // is an associative and commutative operation that could be transformed
638     // using accumulator recursion elimination.  Check to see if this is the
639     // case, and if so, remember the initial accumulator value for later.
640     if ((AccumulatorRecursionEliminationInitVal =
641              canTransformAccumulatorRecursion(&*BBI, CI))) {
642       // Yes, this is accumulator recursion.  Remember which instruction
643       // accumulates.
644       AccumulatorRecursionInstr = &*BBI;
645     } else {
646       return false;   // Otherwise, we cannot eliminate the tail recursion!
647     }
648   }
649 
650   // We can only transform call/return pairs that either ignore the return value
651   // of the call and return void, ignore the value of the call and return a
652   // constant, return the value returned by the tail call, or that are being
653   // accumulator recursion variable eliminated.
654   if (Ret->getNumOperands() == 1 && Ret->getReturnValue() != CI &&
655       !isa<UndefValue>(Ret->getReturnValue()) &&
656       AccumulatorRecursionEliminationInitVal == nullptr &&
657       !getCommonReturnValue(nullptr, CI)) {
658     // One case remains that we are able to handle: the current return
659     // instruction returns a constant, and all other return instructions
660     // return a different constant.
661     if (!isDynamicConstant(Ret->getReturnValue(), CI, Ret))
662       return false; // Current return instruction does not return a constant.
663     // Check that all other return instructions return a common constant.  If
664     // so, record it in AccumulatorRecursionEliminationInitVal.
665     AccumulatorRecursionEliminationInitVal = getCommonReturnValue(Ret, CI);
666     if (!AccumulatorRecursionEliminationInitVal)
667       return false;
668   }
669 
670   BasicBlock *BB = Ret->getParent();
671 
672   using namespace ore;
673   ORE->emit([&]() {
674     return OptimizationRemark(DEBUG_TYPE, "tailcall-recursion", CI)
675            << "transforming tail recursion into loop";
676   });
677 
678   // OK! We can transform this tail call.  If this is the first one found,
679   // create the new entry block, allowing us to branch back to the old entry.
680   if (!HeaderBB)
681     createTailRecurseLoopHeader(CI);
682 
683   if (RemovableCallsMustBeMarkedTail && !CI->isTailCall())
684     return false;
685 
686   // Ok, now that we know we have a pseudo-entry block WITH all of the
687   // required PHI nodes, add entries into the PHI node for the actual
688   // parameters passed into the tail-recursive call.
689   for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i)
690     ArgumentPHIs[i]->addIncoming(CI->getArgOperand(i), BB);
691 
692   // If we are introducing an accumulator variable to eliminate the recursion,
693   // do so now.  Note that we _know_ that no subsequent tail recursion
694   // eliminations will happen on this function because of the way the
695   // accumulator recursion predicate is set up.
696   //
697   if (AccumulatorRecursionEliminationInitVal) {
698     PHINode *AccPN = insertAccumulator(AccumulatorRecursionEliminationInitVal);
699 
700     Instruction *AccRecInstr = AccumulatorRecursionInstr;
701     if (AccRecInstr) {
702       // Add an incoming argument for the current block, which is computed by
703       // our associative and commutative accumulator instruction.
704       AccPN->addIncoming(AccRecInstr, BB);
705 
706       // Next, rewrite the accumulator recursion instruction so that it does not
707       // use the result of the call anymore, instead, use the PHI node we just
708       // inserted.
709       AccRecInstr->setOperand(AccRecInstr->getOperand(0) != CI, AccPN);
710     } else {
711       // Add an incoming argument for the current block, which is just the
712       // constant returned by the current return instruction.
713       AccPN->addIncoming(Ret->getReturnValue(), BB);
714     }
715 
716     // Finally, rewrite any return instructions in the program to return the PHI
717     // node instead of the "initval" that they do currently.  This loop will
718     // actually rewrite the return value we are destroying, but that's ok.
719     for (BasicBlock &BBI : F)
720       if (ReturnInst *RI = dyn_cast<ReturnInst>(BBI.getTerminator()))
721         RI->setOperand(0, AccPN);
722     ++NumAccumAdded;
723   }
724 
725   // Now that all of the PHI nodes are in place, remove the call and
726   // ret instructions, replacing them with an unconditional branch.
727   BranchInst *NewBI = BranchInst::Create(HeaderBB, Ret);
728   NewBI->setDebugLoc(CI->getDebugLoc());
729 
730   BB->getInstList().erase(Ret);  // Remove return.
731   BB->getInstList().erase(CI);   // Remove call.
732   DTU.applyUpdates({{DominatorTree::Insert, BB, HeaderBB}});
733   ++NumEliminated;
734   return true;
735 }
736 
737 bool TailRecursionEliminator::foldReturnAndProcessPred(
738     ReturnInst *Ret, bool CannotTailCallElimCallsMarkedTail) {
739   BasicBlock *BB = Ret->getParent();
740 
741   bool Change = false;
742 
743   // Make sure this block is a trivial return block.
744   assert(BB->getFirstNonPHIOrDbg() == Ret &&
745          "Trying to fold non-trivial return block");
746 
747   // If the return block contains nothing but the return and PHI's,
748   // there might be an opportunity to duplicate the return in its
749   // predecessors and perform TRE there. Look for predecessors that end
750   // in unconditional branch and recursive call(s).
751   SmallVector<BranchInst*, 8> UncondBranchPreds;
752   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
753     BasicBlock *Pred = *PI;
754     Instruction *PTI = Pred->getTerminator();
755     if (BranchInst *BI = dyn_cast<BranchInst>(PTI))
756       if (BI->isUnconditional())
757         UncondBranchPreds.push_back(BI);
758   }
759 
760   while (!UncondBranchPreds.empty()) {
761     BranchInst *BI = UncondBranchPreds.pop_back_val();
762     BasicBlock *Pred = BI->getParent();
763     if (CallInst *CI =
764             findTRECandidate(BI, CannotTailCallElimCallsMarkedTail)) {
765       LLVM_DEBUG(dbgs() << "FOLDING: " << *BB
766                         << "INTO UNCOND BRANCH PRED: " << *Pred);
767       FoldReturnIntoUncondBranch(Ret, BB, Pred, &DTU);
768 
769       // Cleanup: if all predecessors of BB have been eliminated by
770       // FoldReturnIntoUncondBranch, delete it.  It is important to empty it,
771       // because the ret instruction in there is still using a value which
772       // eliminateRecursiveTailCall will attempt to remove.
773       if (!BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
774         DTU.deleteBB(BB);
775 
776       eliminateCall(CI);
777       ++NumRetDuped;
778       Change = true;
779     }
780   }
781 
782   return Change;
783 }
784 
785 bool TailRecursionEliminator::processReturningBlock(
786     ReturnInst *Ret, bool CannotTailCallElimCallsMarkedTail) {
787   CallInst *CI = findTRECandidate(Ret, CannotTailCallElimCallsMarkedTail);
788   if (!CI)
789     return false;
790 
791   return eliminateCall(CI);
792 }
793 
794 void TailRecursionEliminator::cleanupAndFinalize() {
795   // If we eliminated any tail recursions, it's possible that we inserted some
796   // silly PHI nodes which just merge an initial value (the incoming operand)
797   // with themselves.  Check to see if we did and clean up our mess if so.  This
798   // occurs when a function passes an argument straight through to its tail
799   // call.
800   for (PHINode *PN : ArgumentPHIs) {
801     // If the PHI Node is a dynamic constant, replace it with the value it is.
802     if (Value *PNV = SimplifyInstruction(PN, F.getParent()->getDataLayout())) {
803       PN->replaceAllUsesWith(PNV);
804       PN->eraseFromParent();
805     }
806   }
807 }
808 
809 bool TailRecursionEliminator::eliminate(Function &F,
810                                         const TargetTransformInfo *TTI,
811                                         AliasAnalysis *AA,
812                                         OptimizationRemarkEmitter *ORE,
813                                         DomTreeUpdater &DTU) {
814   if (F.getFnAttribute("disable-tail-calls").getValueAsString() == "true")
815     return false;
816 
817   bool MadeChange = false;
818   bool AllCallsAreTailCalls = false;
819   MadeChange |= markTails(F, AllCallsAreTailCalls, ORE);
820   if (!AllCallsAreTailCalls)
821     return MadeChange;
822 
823   // If this function is a varargs function, we won't be able to PHI the args
824   // right, so don't even try to convert it...
825   if (F.getFunctionType()->isVarArg())
826     return false;
827 
828   // If false, we cannot perform TRE on tail calls marked with the 'tail'
829   // attribute, because doing so would cause the stack size to increase (real
830   // TRE would deallocate variable sized allocas, TRE doesn't).
831   bool CanTRETailMarkedCall = canTRE(F);
832 
833   TailRecursionEliminator TRE(F, TTI, AA, ORE, DTU);
834 
835   // Change any tail recursive calls to loops.
836   //
837   // FIXME: The code generator produces really bad code when an 'escaping
838   // alloca' is changed from being a static alloca to being a dynamic alloca.
839   // Until this is resolved, disable this transformation if that would ever
840   // happen.  This bug is PR962.
841   for (Function::iterator BBI = F.begin(), E = F.end(); BBI != E; /*in loop*/) {
842     BasicBlock *BB = &*BBI++; // foldReturnAndProcessPred may delete BB.
843     if (ReturnInst *Ret = dyn_cast<ReturnInst>(BB->getTerminator())) {
844       bool Change = TRE.processReturningBlock(Ret, !CanTRETailMarkedCall);
845       if (!Change && BB->getFirstNonPHIOrDbg() == Ret)
846         Change = TRE.foldReturnAndProcessPred(Ret, !CanTRETailMarkedCall);
847       MadeChange |= Change;
848     }
849   }
850 
851   TRE.cleanupAndFinalize();
852 
853   return MadeChange;
854 }
855 
856 namespace {
857 struct TailCallElim : public FunctionPass {
858   static char ID; // Pass identification, replacement for typeid
859   TailCallElim() : FunctionPass(ID) {
860     initializeTailCallElimPass(*PassRegistry::getPassRegistry());
861   }
862 
863   void getAnalysisUsage(AnalysisUsage &AU) const override {
864     AU.addRequired<TargetTransformInfoWrapperPass>();
865     AU.addRequired<AAResultsWrapperPass>();
866     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
867     AU.addPreserved<GlobalsAAWrapperPass>();
868     AU.addPreserved<DominatorTreeWrapperPass>();
869     AU.addPreserved<PostDominatorTreeWrapperPass>();
870   }
871 
872   bool runOnFunction(Function &F) override {
873     if (skipFunction(F))
874       return false;
875 
876     auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
877     auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
878     auto *PDTWP = getAnalysisIfAvailable<PostDominatorTreeWrapperPass>();
879     auto *PDT = PDTWP ? &PDTWP->getPostDomTree() : nullptr;
880     // There is no noticable performance difference here between Lazy and Eager
881     // UpdateStrategy based on some test results. It is feasible to switch the
882     // UpdateStrategy to Lazy if we find it profitable later.
883     DomTreeUpdater DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Eager);
884 
885     return TailRecursionEliminator::eliminate(
886         F, &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F),
887         &getAnalysis<AAResultsWrapperPass>().getAAResults(),
888         &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(), DTU);
889   }
890 };
891 }
892 
893 char TailCallElim::ID = 0;
894 INITIALIZE_PASS_BEGIN(TailCallElim, "tailcallelim", "Tail Call Elimination",
895                       false, false)
896 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
897 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
898 INITIALIZE_PASS_END(TailCallElim, "tailcallelim", "Tail Call Elimination",
899                     false, false)
900 
901 // Public interface to the TailCallElimination pass
902 FunctionPass *llvm::createTailCallEliminationPass() {
903   return new TailCallElim();
904 }
905 
906 PreservedAnalyses TailCallElimPass::run(Function &F,
907                                         FunctionAnalysisManager &AM) {
908 
909   TargetTransformInfo &TTI = AM.getResult<TargetIRAnalysis>(F);
910   AliasAnalysis &AA = AM.getResult<AAManager>(F);
911   auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
912   auto *DT = AM.getCachedResult<DominatorTreeAnalysis>(F);
913   auto *PDT = AM.getCachedResult<PostDominatorTreeAnalysis>(F);
914   // There is no noticable performance difference here between Lazy and Eager
915   // UpdateStrategy based on some test results. It is feasible to switch the
916   // UpdateStrategy to Lazy if we find it profitable later.
917   DomTreeUpdater DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Eager);
918   bool Changed = TailRecursionEliminator::eliminate(F, &TTI, &AA, &ORE, DTU);
919 
920   if (!Changed)
921     return PreservedAnalyses::all();
922   PreservedAnalyses PA;
923   PA.preserve<GlobalsAA>();
924   PA.preserve<DominatorTreeAnalysis>();
925   PA.preserve<PostDominatorTreeAnalysis>();
926   return PA;
927 }
928