LoopSimplifyCFG.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  1. //===--------- LoopSimplifyCFG.cpp - Loop CFG Simplification Pass ---------===//
  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 implements the Loop SimplifyCFG Pass. This pass is responsible for
  10. // basic loop CFG cleanup, primarily to assist other loop passes. If you
  11. // encounter a noncanonical CFG construct that causes another loop pass to
  12. // perform suboptimally, this is the place to fix it up.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/Statistic.h"
  18. #include "llvm/Analysis/AssumptionCache.h"
  19. #include "llvm/Analysis/BasicAliasAnalysis.h"
  20. #include "llvm/Analysis/DependenceAnalysis.h"
  21. #include "llvm/Analysis/DomTreeUpdater.h"
  22. #include "llvm/Analysis/GlobalsModRef.h"
  23. #include "llvm/Analysis/LoopInfo.h"
  24. #include "llvm/Analysis/LoopIterator.h"
  25. #include "llvm/Analysis/LoopPass.h"
  26. #include "llvm/Analysis/MemorySSA.h"
  27. #include "llvm/Analysis/MemorySSAUpdater.h"
  28. #include "llvm/Analysis/ScalarEvolution.h"
  29. #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
  30. #include "llvm/Analysis/TargetTransformInfo.h"
  31. #include "llvm/IR/Dominators.h"
  32. #include "llvm/IR/IRBuilder.h"
  33. #include "llvm/InitializePasses.h"
  34. #include "llvm/Support/CommandLine.h"
  35. #include "llvm/Transforms/Scalar.h"
  36. #include "llvm/Transforms/Scalar/LoopPassManager.h"
  37. #include "llvm/Transforms/Utils.h"
  38. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  39. #include "llvm/Transforms/Utils/Local.h"
  40. #include "llvm/Transforms/Utils/LoopUtils.h"
  41. using namespace llvm;
  42. #define DEBUG_TYPE "loop-simplifycfg"
  43. static cl::opt<bool> EnableTermFolding("enable-loop-simplifycfg-term-folding",
  44. cl::init(true));
  45. STATISTIC(NumTerminatorsFolded,
  46. "Number of terminators folded to unconditional branches");
  47. STATISTIC(NumLoopBlocksDeleted,
  48. "Number of loop blocks deleted");
  49. STATISTIC(NumLoopExitsDeleted,
  50. "Number of loop exiting edges deleted");
  51. /// If \p BB is a switch or a conditional branch, but only one of its successors
  52. /// can be reached from this block in runtime, return this successor. Otherwise,
  53. /// return nullptr.
  54. static BasicBlock *getOnlyLiveSuccessor(BasicBlock *BB) {
  55. Instruction *TI = BB->getTerminator();
  56. if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
  57. if (BI->isUnconditional())
  58. return nullptr;
  59. if (BI->getSuccessor(0) == BI->getSuccessor(1))
  60. return BI->getSuccessor(0);
  61. ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
  62. if (!Cond)
  63. return nullptr;
  64. return Cond->isZero() ? BI->getSuccessor(1) : BI->getSuccessor(0);
  65. }
  66. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  67. auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
  68. if (!CI)
  69. return nullptr;
  70. for (auto Case : SI->cases())
  71. if (Case.getCaseValue() == CI)
  72. return Case.getCaseSuccessor();
  73. return SI->getDefaultDest();
  74. }
  75. return nullptr;
  76. }
  77. /// Removes \p BB from all loops from [FirstLoop, LastLoop) in parent chain.
  78. static void removeBlockFromLoops(BasicBlock *BB, Loop *FirstLoop,
  79. Loop *LastLoop = nullptr) {
  80. assert((!LastLoop || LastLoop->contains(FirstLoop->getHeader())) &&
  81. "First loop is supposed to be inside of last loop!");
  82. assert(FirstLoop->contains(BB) && "Must be a loop block!");
  83. for (Loop *Current = FirstLoop; Current != LastLoop;
  84. Current = Current->getParentLoop())
  85. Current->removeBlockFromLoop(BB);
  86. }
  87. /// Find innermost loop that contains at least one block from \p BBs and
  88. /// contains the header of loop \p L.
  89. static Loop *getInnermostLoopFor(SmallPtrSetImpl<BasicBlock *> &BBs,
  90. Loop &L, LoopInfo &LI) {
  91. Loop *Innermost = nullptr;
  92. for (BasicBlock *BB : BBs) {
  93. Loop *BBL = LI.getLoopFor(BB);
  94. while (BBL && !BBL->contains(L.getHeader()))
  95. BBL = BBL->getParentLoop();
  96. if (BBL == &L)
  97. BBL = BBL->getParentLoop();
  98. if (!BBL)
  99. continue;
  100. if (!Innermost || BBL->getLoopDepth() > Innermost->getLoopDepth())
  101. Innermost = BBL;
  102. }
  103. return Innermost;
  104. }
  105. namespace {
  106. /// Helper class that can turn branches and switches with constant conditions
  107. /// into unconditional branches.
  108. class ConstantTerminatorFoldingImpl {
  109. private:
  110. Loop &L;
  111. LoopInfo &LI;
  112. DominatorTree &DT;
  113. ScalarEvolution &SE;
  114. MemorySSAUpdater *MSSAU;
  115. LoopBlocksDFS DFS;
  116. DomTreeUpdater DTU;
  117. SmallVector<DominatorTree::UpdateType, 16> DTUpdates;
  118. // Whether or not the current loop has irreducible CFG.
  119. bool HasIrreducibleCFG = false;
  120. // Whether or not the current loop will still exist after terminator constant
  121. // folding will be done. In theory, there are two ways how it can happen:
  122. // 1. Loop's latch(es) become unreachable from loop header;
  123. // 2. Loop's header becomes unreachable from method entry.
  124. // In practice, the second situation is impossible because we only modify the
  125. // current loop and its preheader and do not affect preheader's reachibility
  126. // from any other block. So this variable set to true means that loop's latch
  127. // has become unreachable from loop header.
  128. bool DeleteCurrentLoop = false;
  129. // The blocks of the original loop that will still be reachable from entry
  130. // after the constant folding.
  131. SmallPtrSet<BasicBlock *, 8> LiveLoopBlocks;
  132. // The blocks of the original loop that will become unreachable from entry
  133. // after the constant folding.
  134. SmallVector<BasicBlock *, 8> DeadLoopBlocks;
  135. // The exits of the original loop that will still be reachable from entry
  136. // after the constant folding.
  137. SmallPtrSet<BasicBlock *, 8> LiveExitBlocks;
  138. // The exits of the original loop that will become unreachable from entry
  139. // after the constant folding.
  140. SmallVector<BasicBlock *, 8> DeadExitBlocks;
  141. // The blocks that will still be a part of the current loop after folding.
  142. SmallPtrSet<BasicBlock *, 8> BlocksInLoopAfterFolding;
  143. // The blocks that have terminators with constant condition that can be
  144. // folded. Note: fold candidates should be in L but not in any of its
  145. // subloops to avoid complex LI updates.
  146. SmallVector<BasicBlock *, 8> FoldCandidates;
  147. void dump() const {
  148. dbgs() << "Constant terminator folding for loop " << L << "\n";
  149. dbgs() << "After terminator constant-folding, the loop will";
  150. if (!DeleteCurrentLoop)
  151. dbgs() << " not";
  152. dbgs() << " be destroyed\n";
  153. auto PrintOutVector = [&](const char *Message,
  154. const SmallVectorImpl<BasicBlock *> &S) {
  155. dbgs() << Message << "\n";
  156. for (const BasicBlock *BB : S)
  157. dbgs() << "\t" << BB->getName() << "\n";
  158. };
  159. auto PrintOutSet = [&](const char *Message,
  160. const SmallPtrSetImpl<BasicBlock *> &S) {
  161. dbgs() << Message << "\n";
  162. for (const BasicBlock *BB : S)
  163. dbgs() << "\t" << BB->getName() << "\n";
  164. };
  165. PrintOutVector("Blocks in which we can constant-fold terminator:",
  166. FoldCandidates);
  167. PrintOutSet("Live blocks from the original loop:", LiveLoopBlocks);
  168. PrintOutVector("Dead blocks from the original loop:", DeadLoopBlocks);
  169. PrintOutSet("Live exit blocks:", LiveExitBlocks);
  170. PrintOutVector("Dead exit blocks:", DeadExitBlocks);
  171. if (!DeleteCurrentLoop)
  172. PrintOutSet("The following blocks will still be part of the loop:",
  173. BlocksInLoopAfterFolding);
  174. }
  175. /// Whether or not the current loop has irreducible CFG.
  176. bool hasIrreducibleCFG(LoopBlocksDFS &DFS) {
  177. assert(DFS.isComplete() && "DFS is expected to be finished");
  178. // Index of a basic block in RPO traversal.
  179. DenseMap<const BasicBlock *, unsigned> RPO;
  180. unsigned Current = 0;
  181. for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I)
  182. RPO[*I] = Current++;
  183. for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {
  184. BasicBlock *BB = *I;
  185. for (auto *Succ : successors(BB))
  186. if (L.contains(Succ) && !LI.isLoopHeader(Succ) && RPO[BB] > RPO[Succ])
  187. // If an edge goes from a block with greater order number into a block
  188. // with lesses number, and it is not a loop backedge, then it can only
  189. // be a part of irreducible non-loop cycle.
  190. return true;
  191. }
  192. return false;
  193. }
  194. /// Fill all information about status of blocks and exits of the current loop
  195. /// if constant folding of all branches will be done.
  196. void analyze() {
  197. DFS.perform(&LI);
  198. assert(DFS.isComplete() && "DFS is expected to be finished");
  199. // TODO: The algorithm below relies on both RPO and Postorder traversals.
  200. // When the loop has only reducible CFG inside, then the invariant "all
  201. // predecessors of X are processed before X in RPO" is preserved. However
  202. // an irreducible loop can break this invariant (e.g. latch does not have to
  203. // be the last block in the traversal in this case, and the algorithm relies
  204. // on this). We can later decide to support such cases by altering the
  205. // algorithms, but so far we just give up analyzing them.
  206. if (hasIrreducibleCFG(DFS)) {
  207. HasIrreducibleCFG = true;
  208. return;
  209. }
  210. // Collect live and dead loop blocks and exits.
  211. LiveLoopBlocks.insert(L.getHeader());
  212. for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {
  213. BasicBlock *BB = *I;
  214. // If a loop block wasn't marked as live so far, then it's dead.
  215. if (!LiveLoopBlocks.count(BB)) {
  216. DeadLoopBlocks.push_back(BB);
  217. continue;
  218. }
  219. BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
  220. // If a block has only one live successor, it's a candidate on constant
  221. // folding. Only handle blocks from current loop: branches in child loops
  222. // are skipped because if they can be folded, they should be folded during
  223. // the processing of child loops.
  224. bool TakeFoldCandidate = TheOnlySucc && LI.getLoopFor(BB) == &L;
  225. if (TakeFoldCandidate)
  226. FoldCandidates.push_back(BB);
  227. // Handle successors.
  228. for (BasicBlock *Succ : successors(BB))
  229. if (!TakeFoldCandidate || TheOnlySucc == Succ) {
  230. if (L.contains(Succ))
  231. LiveLoopBlocks.insert(Succ);
  232. else
  233. LiveExitBlocks.insert(Succ);
  234. }
  235. }
  236. // Amount of dead and live loop blocks should match the total number of
  237. // blocks in loop.
  238. assert(L.getNumBlocks() == LiveLoopBlocks.size() + DeadLoopBlocks.size() &&
  239. "Malformed block sets?");
  240. // Now, all exit blocks that are not marked as live are dead.
  241. SmallVector<BasicBlock *, 8> ExitBlocks;
  242. L.getExitBlocks(ExitBlocks);
  243. SmallPtrSet<BasicBlock *, 8> UniqueDeadExits;
  244. for (auto *ExitBlock : ExitBlocks)
  245. if (!LiveExitBlocks.count(ExitBlock) &&
  246. UniqueDeadExits.insert(ExitBlock).second)
  247. DeadExitBlocks.push_back(ExitBlock);
  248. // Whether or not the edge From->To will still be present in graph after the
  249. // folding.
  250. auto IsEdgeLive = [&](BasicBlock *From, BasicBlock *To) {
  251. if (!LiveLoopBlocks.count(From))
  252. return false;
  253. BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(From);
  254. return !TheOnlySucc || TheOnlySucc == To || LI.getLoopFor(From) != &L;
  255. };
  256. // The loop will not be destroyed if its latch is live.
  257. DeleteCurrentLoop = !IsEdgeLive(L.getLoopLatch(), L.getHeader());
  258. // If we are going to delete the current loop completely, no extra analysis
  259. // is needed.
  260. if (DeleteCurrentLoop)
  261. return;
  262. // Otherwise, we should check which blocks will still be a part of the
  263. // current loop after the transform.
  264. BlocksInLoopAfterFolding.insert(L.getLoopLatch());
  265. // If the loop is live, then we should compute what blocks are still in
  266. // loop after all branch folding has been done. A block is in loop if
  267. // it has a live edge to another block that is in the loop; by definition,
  268. // latch is in the loop.
  269. auto BlockIsInLoop = [&](BasicBlock *BB) {
  270. return any_of(successors(BB), [&](BasicBlock *Succ) {
  271. return BlocksInLoopAfterFolding.count(Succ) && IsEdgeLive(BB, Succ);
  272. });
  273. };
  274. for (auto I = DFS.beginPostorder(), E = DFS.endPostorder(); I != E; ++I) {
  275. BasicBlock *BB = *I;
  276. if (BlockIsInLoop(BB))
  277. BlocksInLoopAfterFolding.insert(BB);
  278. }
  279. assert(BlocksInLoopAfterFolding.count(L.getHeader()) &&
  280. "Header not in loop?");
  281. assert(BlocksInLoopAfterFolding.size() <= LiveLoopBlocks.size() &&
  282. "All blocks that stay in loop should be live!");
  283. }
  284. /// We need to preserve static reachibility of all loop exit blocks (this is)
  285. /// required by loop pass manager. In order to do it, we make the following
  286. /// trick:
  287. ///
  288. /// preheader:
  289. /// <preheader code>
  290. /// br label %loop_header
  291. ///
  292. /// loop_header:
  293. /// ...
  294. /// br i1 false, label %dead_exit, label %loop_block
  295. /// ...
  296. ///
  297. /// We cannot simply remove edge from the loop to dead exit because in this
  298. /// case dead_exit (and its successors) may become unreachable. To avoid that,
  299. /// we insert the following fictive preheader:
  300. ///
  301. /// preheader:
  302. /// <preheader code>
  303. /// switch i32 0, label %preheader-split,
  304. /// [i32 1, label %dead_exit_1],
  305. /// [i32 2, label %dead_exit_2],
  306. /// ...
  307. /// [i32 N, label %dead_exit_N],
  308. ///
  309. /// preheader-split:
  310. /// br label %loop_header
  311. ///
  312. /// loop_header:
  313. /// ...
  314. /// br i1 false, label %dead_exit_N, label %loop_block
  315. /// ...
  316. ///
  317. /// Doing so, we preserve static reachibility of all dead exits and can later
  318. /// remove edges from the loop to these blocks.
  319. void handleDeadExits() {
  320. // If no dead exits, nothing to do.
  321. if (DeadExitBlocks.empty())
  322. return;
  323. // Construct split preheader and the dummy switch to thread edges from it to
  324. // dead exits.
  325. BasicBlock *Preheader = L.getLoopPreheader();
  326. BasicBlock *NewPreheader = llvm::SplitBlock(
  327. Preheader, Preheader->getTerminator(), &DT, &LI, MSSAU);
  328. IRBuilder<> Builder(Preheader->getTerminator());
  329. SwitchInst *DummySwitch =
  330. Builder.CreateSwitch(Builder.getInt32(0), NewPreheader);
  331. Preheader->getTerminator()->eraseFromParent();
  332. unsigned DummyIdx = 1;
  333. for (BasicBlock *BB : DeadExitBlocks) {
  334. // Eliminate all Phis and LandingPads from dead exits.
  335. // TODO: Consider removing all instructions in this dead block.
  336. SmallVector<Instruction *, 4> DeadInstructions;
  337. for (auto &PN : BB->phis())
  338. DeadInstructions.push_back(&PN);
  339. if (auto *LandingPad = dyn_cast<LandingPadInst>(BB->getFirstNonPHI()))
  340. DeadInstructions.emplace_back(LandingPad);
  341. for (Instruction *I : DeadInstructions) {
  342. I->replaceAllUsesWith(UndefValue::get(I->getType()));
  343. I->eraseFromParent();
  344. }
  345. assert(DummyIdx != 0 && "Too many dead exits!");
  346. DummySwitch->addCase(Builder.getInt32(DummyIdx++), BB);
  347. DTUpdates.push_back({DominatorTree::Insert, Preheader, BB});
  348. ++NumLoopExitsDeleted;
  349. }
  350. assert(L.getLoopPreheader() == NewPreheader && "Malformed CFG?");
  351. if (Loop *OuterLoop = LI.getLoopFor(Preheader)) {
  352. // When we break dead edges, the outer loop may become unreachable from
  353. // the current loop. We need to fix loop info accordingly. For this, we
  354. // find the most nested loop that still contains L and remove L from all
  355. // loops that are inside of it.
  356. Loop *StillReachable = getInnermostLoopFor(LiveExitBlocks, L, LI);
  357. // Okay, our loop is no longer in the outer loop (and maybe not in some of
  358. // its parents as well). Make the fixup.
  359. if (StillReachable != OuterLoop) {
  360. LI.changeLoopFor(NewPreheader, StillReachable);
  361. removeBlockFromLoops(NewPreheader, OuterLoop, StillReachable);
  362. for (auto *BB : L.blocks())
  363. removeBlockFromLoops(BB, OuterLoop, StillReachable);
  364. OuterLoop->removeChildLoop(&L);
  365. if (StillReachable)
  366. StillReachable->addChildLoop(&L);
  367. else
  368. LI.addTopLevelLoop(&L);
  369. // Some values from loops in [OuterLoop, StillReachable) could be used
  370. // in the current loop. Now it is not their child anymore, so such uses
  371. // require LCSSA Phis.
  372. Loop *FixLCSSALoop = OuterLoop;
  373. while (FixLCSSALoop->getParentLoop() != StillReachable)
  374. FixLCSSALoop = FixLCSSALoop->getParentLoop();
  375. assert(FixLCSSALoop && "Should be a loop!");
  376. // We need all DT updates to be done before forming LCSSA.
  377. if (MSSAU)
  378. MSSAU->applyUpdates(DTUpdates, DT, /*UpdateDT=*/true);
  379. else
  380. DTU.applyUpdates(DTUpdates);
  381. DTUpdates.clear();
  382. formLCSSARecursively(*FixLCSSALoop, DT, &LI, &SE);
  383. }
  384. }
  385. if (MSSAU) {
  386. // Clear all updates now. Facilitates deletes that follow.
  387. MSSAU->applyUpdates(DTUpdates, DT, /*UpdateDT=*/true);
  388. DTUpdates.clear();
  389. if (VerifyMemorySSA)
  390. MSSAU->getMemorySSA()->verifyMemorySSA();
  391. }
  392. }
  393. /// Delete loop blocks that have become unreachable after folding. Make all
  394. /// relevant updates to DT and LI.
  395. void deleteDeadLoopBlocks() {
  396. if (MSSAU) {
  397. SmallSetVector<BasicBlock *, 8> DeadLoopBlocksSet(DeadLoopBlocks.begin(),
  398. DeadLoopBlocks.end());
  399. MSSAU->removeBlocks(DeadLoopBlocksSet);
  400. }
  401. // The function LI.erase has some invariants that need to be preserved when
  402. // it tries to remove a loop which is not the top-level loop. In particular,
  403. // it requires loop's preheader to be strictly in loop's parent. We cannot
  404. // just remove blocks one by one, because after removal of preheader we may
  405. // break this invariant for the dead loop. So we detatch and erase all dead
  406. // loops beforehand.
  407. for (auto *BB : DeadLoopBlocks)
  408. if (LI.isLoopHeader(BB)) {
  409. assert(LI.getLoopFor(BB) != &L && "Attempt to remove current loop!");
  410. Loop *DL = LI.getLoopFor(BB);
  411. if (!DL->isOutermost()) {
  412. for (auto *PL = DL->getParentLoop(); PL; PL = PL->getParentLoop())
  413. for (auto *BB : DL->getBlocks())
  414. PL->removeBlockFromLoop(BB);
  415. DL->getParentLoop()->removeChildLoop(DL);
  416. LI.addTopLevelLoop(DL);
  417. }
  418. LI.erase(DL);
  419. }
  420. for (auto *BB : DeadLoopBlocks) {
  421. assert(BB != L.getHeader() &&
  422. "Header of the current loop cannot be dead!");
  423. LLVM_DEBUG(dbgs() << "Deleting dead loop block " << BB->getName()
  424. << "\n");
  425. LI.removeBlock(BB);
  426. }
  427. detachDeadBlocks(DeadLoopBlocks, &DTUpdates, /*KeepOneInputPHIs*/true);
  428. DTU.applyUpdates(DTUpdates);
  429. DTUpdates.clear();
  430. for (auto *BB : DeadLoopBlocks)
  431. DTU.deleteBB(BB);
  432. NumLoopBlocksDeleted += DeadLoopBlocks.size();
  433. }
  434. /// Constant-fold terminators of blocks acculumated in FoldCandidates into the
  435. /// unconditional branches.
  436. void foldTerminators() {
  437. for (BasicBlock *BB : FoldCandidates) {
  438. assert(LI.getLoopFor(BB) == &L && "Should be a loop block!");
  439. BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
  440. assert(TheOnlySucc && "Should have one live successor!");
  441. LLVM_DEBUG(dbgs() << "Replacing terminator of " << BB->getName()
  442. << " with an unconditional branch to the block "
  443. << TheOnlySucc->getName() << "\n");
  444. SmallPtrSet<BasicBlock *, 2> DeadSuccessors;
  445. // Remove all BB's successors except for the live one.
  446. unsigned TheOnlySuccDuplicates = 0;
  447. for (auto *Succ : successors(BB))
  448. if (Succ != TheOnlySucc) {
  449. DeadSuccessors.insert(Succ);
  450. // If our successor lies in a different loop, we don't want to remove
  451. // the one-input Phi because it is a LCSSA Phi.
  452. bool PreserveLCSSAPhi = !L.contains(Succ);
  453. Succ->removePredecessor(BB, PreserveLCSSAPhi);
  454. if (MSSAU)
  455. MSSAU->removeEdge(BB, Succ);
  456. } else
  457. ++TheOnlySuccDuplicates;
  458. assert(TheOnlySuccDuplicates > 0 && "Should be!");
  459. // If TheOnlySucc was BB's successor more than once, after transform it
  460. // will be its successor only once. Remove redundant inputs from
  461. // TheOnlySucc's Phis.
  462. bool PreserveLCSSAPhi = !L.contains(TheOnlySucc);
  463. for (unsigned Dup = 1; Dup < TheOnlySuccDuplicates; ++Dup)
  464. TheOnlySucc->removePredecessor(BB, PreserveLCSSAPhi);
  465. if (MSSAU && TheOnlySuccDuplicates > 1)
  466. MSSAU->removeDuplicatePhiEdgesBetween(BB, TheOnlySucc);
  467. IRBuilder<> Builder(BB->getContext());
  468. Instruction *Term = BB->getTerminator();
  469. Builder.SetInsertPoint(Term);
  470. Builder.CreateBr(TheOnlySucc);
  471. Term->eraseFromParent();
  472. for (auto *DeadSucc : DeadSuccessors)
  473. DTUpdates.push_back({DominatorTree::Delete, BB, DeadSucc});
  474. ++NumTerminatorsFolded;
  475. }
  476. }
  477. public:
  478. ConstantTerminatorFoldingImpl(Loop &L, LoopInfo &LI, DominatorTree &DT,
  479. ScalarEvolution &SE,
  480. MemorySSAUpdater *MSSAU)
  481. : L(L), LI(LI), DT(DT), SE(SE), MSSAU(MSSAU), DFS(&L),
  482. DTU(DT, DomTreeUpdater::UpdateStrategy::Eager) {}
  483. bool run() {
  484. assert(L.getLoopLatch() && "Should be single latch!");
  485. // Collect all available information about status of blocks after constant
  486. // folding.
  487. analyze();
  488. BasicBlock *Header = L.getHeader();
  489. (void)Header;
  490. LLVM_DEBUG(dbgs() << "In function " << Header->getParent()->getName()
  491. << ": ");
  492. if (HasIrreducibleCFG) {
  493. LLVM_DEBUG(dbgs() << "Loops with irreducible CFG are not supported!\n");
  494. return false;
  495. }
  496. // Nothing to constant-fold.
  497. if (FoldCandidates.empty()) {
  498. LLVM_DEBUG(
  499. dbgs() << "No constant terminator folding candidates found in loop "
  500. << Header->getName() << "\n");
  501. return false;
  502. }
  503. // TODO: Support deletion of the current loop.
  504. if (DeleteCurrentLoop) {
  505. LLVM_DEBUG(
  506. dbgs()
  507. << "Give up constant terminator folding in loop " << Header->getName()
  508. << ": we don't currently support deletion of the current loop.\n");
  509. return false;
  510. }
  511. // TODO: Support blocks that are not dead, but also not in loop after the
  512. // folding.
  513. if (BlocksInLoopAfterFolding.size() + DeadLoopBlocks.size() !=
  514. L.getNumBlocks()) {
  515. LLVM_DEBUG(
  516. dbgs() << "Give up constant terminator folding in loop "
  517. << Header->getName() << ": we don't currently"
  518. " support blocks that are not dead, but will stop "
  519. "being a part of the loop after constant-folding.\n");
  520. return false;
  521. }
  522. SE.forgetTopmostLoop(&L);
  523. // Dump analysis results.
  524. LLVM_DEBUG(dump());
  525. LLVM_DEBUG(dbgs() << "Constant-folding " << FoldCandidates.size()
  526. << " terminators in loop " << Header->getName() << "\n");
  527. // Make the actual transforms.
  528. handleDeadExits();
  529. foldTerminators();
  530. if (!DeadLoopBlocks.empty()) {
  531. LLVM_DEBUG(dbgs() << "Deleting " << DeadLoopBlocks.size()
  532. << " dead blocks in loop " << Header->getName() << "\n");
  533. deleteDeadLoopBlocks();
  534. } else {
  535. // If we didn't do updates inside deleteDeadLoopBlocks, do them here.
  536. DTU.applyUpdates(DTUpdates);
  537. DTUpdates.clear();
  538. }
  539. if (MSSAU && VerifyMemorySSA)
  540. MSSAU->getMemorySSA()->verifyMemorySSA();
  541. #ifndef NDEBUG
  542. // Make sure that we have preserved all data structures after the transform.
  543. #if defined(EXPENSIVE_CHECKS)
  544. assert(DT.verify(DominatorTree::VerificationLevel::Full) &&
  545. "DT broken after transform!");
  546. #else
  547. assert(DT.verify(DominatorTree::VerificationLevel::Fast) &&
  548. "DT broken after transform!");
  549. #endif
  550. assert(DT.isReachableFromEntry(Header));
  551. LI.verify(DT);
  552. #endif
  553. return true;
  554. }
  555. bool foldingBreaksCurrentLoop() const {
  556. return DeleteCurrentLoop;
  557. }
  558. };
  559. } // namespace
  560. /// Turn branches and switches with known constant conditions into unconditional
  561. /// branches.
  562. static bool constantFoldTerminators(Loop &L, DominatorTree &DT, LoopInfo &LI,
  563. ScalarEvolution &SE,
  564. MemorySSAUpdater *MSSAU,
  565. bool &IsLoopDeleted) {
  566. if (!EnableTermFolding)
  567. return false;
  568. // To keep things simple, only process loops with single latch. We
  569. // canonicalize most loops to this form. We can support multi-latch if needed.
  570. if (!L.getLoopLatch())
  571. return false;
  572. ConstantTerminatorFoldingImpl BranchFolder(L, LI, DT, SE, MSSAU);
  573. bool Changed = BranchFolder.run();
  574. IsLoopDeleted = Changed && BranchFolder.foldingBreaksCurrentLoop();
  575. return Changed;
  576. }
  577. static bool mergeBlocksIntoPredecessors(Loop &L, DominatorTree &DT,
  578. LoopInfo &LI, MemorySSAUpdater *MSSAU) {
  579. bool Changed = false;
  580. DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
  581. // Copy blocks into a temporary array to avoid iterator invalidation issues
  582. // as we remove them.
  583. SmallVector<WeakTrackingVH, 16> Blocks(L.blocks());
  584. for (auto &Block : Blocks) {
  585. // Attempt to merge blocks in the trivial case. Don't modify blocks which
  586. // belong to other loops.
  587. BasicBlock *Succ = cast_or_null<BasicBlock>(Block);
  588. if (!Succ)
  589. continue;
  590. BasicBlock *Pred = Succ->getSinglePredecessor();
  591. if (!Pred || !Pred->getSingleSuccessor() || LI.getLoopFor(Pred) != &L)
  592. continue;
  593. // Merge Succ into Pred and delete it.
  594. MergeBlockIntoPredecessor(Succ, &DTU, &LI, MSSAU);
  595. if (MSSAU && VerifyMemorySSA)
  596. MSSAU->getMemorySSA()->verifyMemorySSA();
  597. Changed = true;
  598. }
  599. return Changed;
  600. }
  601. static bool simplifyLoopCFG(Loop &L, DominatorTree &DT, LoopInfo &LI,
  602. ScalarEvolution &SE, MemorySSAUpdater *MSSAU,
  603. bool &IsLoopDeleted) {
  604. bool Changed = false;
  605. // Constant-fold terminators with known constant conditions.
  606. Changed |= constantFoldTerminators(L, DT, LI, SE, MSSAU, IsLoopDeleted);
  607. if (IsLoopDeleted)
  608. return true;
  609. // Eliminate unconditional branches by merging blocks into their predecessors.
  610. Changed |= mergeBlocksIntoPredecessors(L, DT, LI, MSSAU);
  611. if (Changed)
  612. SE.forgetTopmostLoop(&L);
  613. return Changed;
  614. }
  615. PreservedAnalyses LoopSimplifyCFGPass::run(Loop &L, LoopAnalysisManager &AM,
  616. LoopStandardAnalysisResults &AR,
  617. LPMUpdater &LPMU) {
  618. Optional<MemorySSAUpdater> MSSAU;
  619. if (AR.MSSA)
  620. MSSAU = MemorySSAUpdater(AR.MSSA);
  621. bool DeleteCurrentLoop = false;
  622. if (!simplifyLoopCFG(L, AR.DT, AR.LI, AR.SE,
  623. MSSAU.hasValue() ? MSSAU.getPointer() : nullptr,
  624. DeleteCurrentLoop))
  625. return PreservedAnalyses::all();
  626. if (DeleteCurrentLoop)
  627. LPMU.markLoopAsDeleted(L, "loop-simplifycfg");
  628. auto PA = getLoopPassPreservedAnalyses();
  629. if (AR.MSSA)
  630. PA.preserve<MemorySSAAnalysis>();
  631. return PA;
  632. }
  633. namespace {
  634. class LoopSimplifyCFGLegacyPass : public LoopPass {
  635. public:
  636. static char ID; // Pass ID, replacement for typeid
  637. LoopSimplifyCFGLegacyPass() : LoopPass(ID) {
  638. initializeLoopSimplifyCFGLegacyPassPass(*PassRegistry::getPassRegistry());
  639. }
  640. bool runOnLoop(Loop *L, LPPassManager &LPM) override {
  641. if (skipLoop(L))
  642. return false;
  643. DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  644. LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  645. ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
  646. auto *MSSAA = getAnalysisIfAvailable<MemorySSAWrapperPass>();
  647. Optional<MemorySSAUpdater> MSSAU;
  648. if (MSSAA)
  649. MSSAU = MemorySSAUpdater(&MSSAA->getMSSA());
  650. if (MSSAA && VerifyMemorySSA)
  651. MSSAU->getMemorySSA()->verifyMemorySSA();
  652. bool DeleteCurrentLoop = false;
  653. bool Changed = simplifyLoopCFG(
  654. *L, DT, LI, SE, MSSAU.hasValue() ? MSSAU.getPointer() : nullptr,
  655. DeleteCurrentLoop);
  656. if (DeleteCurrentLoop)
  657. LPM.markLoopAsDeleted(*L);
  658. return Changed;
  659. }
  660. void getAnalysisUsage(AnalysisUsage &AU) const override {
  661. AU.addPreserved<MemorySSAWrapperPass>();
  662. AU.addPreserved<DependenceAnalysisWrapperPass>();
  663. getLoopAnalysisUsage(AU);
  664. }
  665. };
  666. } // end namespace
  667. char LoopSimplifyCFGLegacyPass::ID = 0;
  668. INITIALIZE_PASS_BEGIN(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
  669. "Simplify loop CFG", false, false)
  670. INITIALIZE_PASS_DEPENDENCY(LoopPass)
  671. INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
  672. INITIALIZE_PASS_END(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
  673. "Simplify loop CFG", false, false)
  674. Pass *llvm::createLoopSimplifyCFGPass() {
  675. return new LoopSimplifyCFGLegacyPass();
  676. }