TailRecursionElimination.cpp 34 KB

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