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