TailRecursionElimination.cpp 35 KB

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