LLVM  10.0.0
LoopSimplifyCFG.cpp
Go to the documentation of this file.
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 
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Analysis/LoopInfo.h"
26 #include "llvm/Analysis/LoopPass.h"
32 #include "llvm/IR/Dominators.h"
33 #include "llvm/InitializePasses.h"
35 #include "llvm/Transforms/Scalar.h"
37 #include "llvm/Transforms/Utils.h"
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "loop-simplifycfg"
44 
45 static cl::opt<bool> EnableTermFolding("enable-loop-simplifycfg-term-folding",
46  cl::init(true));
47 
48 STATISTIC(NumTerminatorsFolded,
49  "Number of terminators folded to unconditional branches");
50 STATISTIC(NumLoopBlocksDeleted,
51  "Number of loop blocks deleted");
52 STATISTIC(NumLoopExitsDeleted,
53  "Number of loop exiting edges deleted");
54 
55 /// If \p BB is a switch or a conditional branch, but only one of its successors
56 /// can be reached from this block in runtime, return this successor. Otherwise,
57 /// return nullptr.
59  Instruction *TI = BB->getTerminator();
60  if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
61  if (BI->isUnconditional())
62  return nullptr;
63  if (BI->getSuccessor(0) == BI->getSuccessor(1))
64  return BI->getSuccessor(0);
65  ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
66  if (!Cond)
67  return nullptr;
68  return Cond->isZero() ? BI->getSuccessor(1) : BI->getSuccessor(0);
69  }
70 
71  if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
72  auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
73  if (!CI)
74  return nullptr;
75  for (auto Case : SI->cases())
76  if (Case.getCaseValue() == CI)
77  return Case.getCaseSuccessor();
78  return SI->getDefaultDest();
79  }
80 
81  return nullptr;
82 }
83 
84 /// Removes \p BB from all loops from [FirstLoop, LastLoop) in parent chain.
85 static void removeBlockFromLoops(BasicBlock *BB, Loop *FirstLoop,
86  Loop *LastLoop = nullptr) {
87  assert((!LastLoop || LastLoop->contains(FirstLoop->getHeader())) &&
88  "First loop is supposed to be inside of last loop!");
89  assert(FirstLoop->contains(BB) && "Must be a loop block!");
90  for (Loop *Current = FirstLoop; Current != LastLoop;
91  Current = Current->getParentLoop())
92  Current->removeBlockFromLoop(BB);
93 }
94 
95 /// Find innermost loop that contains at least one block from \p BBs and
96 /// contains the header of loop \p L.
98  Loop &L, LoopInfo &LI) {
99  Loop *Innermost = nullptr;
100  for (BasicBlock *BB : BBs) {
101  Loop *BBL = LI.getLoopFor(BB);
102  while (BBL && !BBL->contains(L.getHeader()))
103  BBL = BBL->getParentLoop();
104  if (BBL == &L)
105  BBL = BBL->getParentLoop();
106  if (!BBL)
107  continue;
108  if (!Innermost || BBL->getLoopDepth() > Innermost->getLoopDepth())
109  Innermost = BBL;
110  }
111  return Innermost;
112 }
113 
114 namespace {
115 /// Helper class that can turn branches and switches with constant conditions
116 /// into unconditional branches.
117 class ConstantTerminatorFoldingImpl {
118 private:
119  Loop &L;
120  LoopInfo &LI;
121  DominatorTree &DT;
122  ScalarEvolution &SE;
123  MemorySSAUpdater *MSSAU;
125  DomTreeUpdater DTU;
127 
128  // Whether or not the current loop has irreducible CFG.
129  bool HasIrreducibleCFG = false;
130  // Whether or not the current loop will still exist after terminator constant
131  // folding will be done. In theory, there are two ways how it can happen:
132  // 1. Loop's latch(es) become unreachable from loop header;
133  // 2. Loop's header becomes unreachable from method entry.
134  // In practice, the second situation is impossible because we only modify the
135  // current loop and its preheader and do not affect preheader's reachibility
136  // from any other block. So this variable set to true means that loop's latch
137  // has become unreachable from loop header.
138  bool DeleteCurrentLoop = false;
139 
140  // The blocks of the original loop that will still be reachable from entry
141  // after the constant folding.
142  SmallPtrSet<BasicBlock *, 8> LiveLoopBlocks;
143  // The blocks of the original loop that will become unreachable from entry
144  // after the constant folding.
145  SmallVector<BasicBlock *, 8> DeadLoopBlocks;
146  // The exits of the original loop that will still be reachable from entry
147  // after the constant folding.
148  SmallPtrSet<BasicBlock *, 8> LiveExitBlocks;
149  // The exits of the original loop that will become unreachable from entry
150  // after the constant folding.
151  SmallVector<BasicBlock *, 8> DeadExitBlocks;
152  // The blocks that will still be a part of the current loop after folding.
153  SmallPtrSet<BasicBlock *, 8> BlocksInLoopAfterFolding;
154  // The blocks that have terminators with constant condition that can be
155  // folded. Note: fold candidates should be in L but not in any of its
156  // subloops to avoid complex LI updates.
157  SmallVector<BasicBlock *, 8> FoldCandidates;
158 
159  void dump() const {
160  dbgs() << "Constant terminator folding for loop " << L << "\n";
161  dbgs() << "After terminator constant-folding, the loop will";
162  if (!DeleteCurrentLoop)
163  dbgs() << " not";
164  dbgs() << " be destroyed\n";
165  auto PrintOutVector = [&](const char *Message,
167  dbgs() << Message << "\n";
168  for (const BasicBlock *BB : S)
169  dbgs() << "\t" << BB->getName() << "\n";
170  };
171  auto PrintOutSet = [&](const char *Message,
173  dbgs() << Message << "\n";
174  for (const BasicBlock *BB : S)
175  dbgs() << "\t" << BB->getName() << "\n";
176  };
177  PrintOutVector("Blocks in which we can constant-fold terminator:",
178  FoldCandidates);
179  PrintOutSet("Live blocks from the original loop:", LiveLoopBlocks);
180  PrintOutVector("Dead blocks from the original loop:", DeadLoopBlocks);
181  PrintOutSet("Live exit blocks:", LiveExitBlocks);
182  PrintOutVector("Dead exit blocks:", DeadExitBlocks);
183  if (!DeleteCurrentLoop)
184  PrintOutSet("The following blocks will still be part of the loop:",
185  BlocksInLoopAfterFolding);
186  }
187 
188  /// Whether or not the current loop has irreducible CFG.
189  bool hasIrreducibleCFG(LoopBlocksDFS &DFS) {
190  assert(DFS.isComplete() && "DFS is expected to be finished");
191  // Index of a basic block in RPO traversal.
193  unsigned Current = 0;
194  for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I)
195  RPO[*I] = Current++;
196 
197  for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {
198  BasicBlock *BB = *I;
199  for (auto *Succ : successors(BB))
200  if (L.contains(Succ) && !LI.isLoopHeader(Succ) && RPO[BB] > RPO[Succ])
201  // If an edge goes from a block with greater order number into a block
202  // with lesses number, and it is not a loop backedge, then it can only
203  // be a part of irreducible non-loop cycle.
204  return true;
205  }
206  return false;
207  }
208 
209  /// Fill all information about status of blocks and exits of the current loop
210  /// if constant folding of all branches will be done.
211  void analyze() {
212  DFS.perform(&LI);
213  assert(DFS.isComplete() && "DFS is expected to be finished");
214 
215  // TODO: The algorithm below relies on both RPO and Postorder traversals.
216  // When the loop has only reducible CFG inside, then the invariant "all
217  // predecessors of X are processed before X in RPO" is preserved. However
218  // an irreducible loop can break this invariant (e.g. latch does not have to
219  // be the last block in the traversal in this case, and the algorithm relies
220  // on this). We can later decide to support such cases by altering the
221  // algorithms, but so far we just give up analyzing them.
222  if (hasIrreducibleCFG(DFS)) {
223  HasIrreducibleCFG = true;
224  return;
225  }
226 
227  // Collect live and dead loop blocks and exits.
228  LiveLoopBlocks.insert(L.getHeader());
229  for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {
230  BasicBlock *BB = *I;
231 
232  // If a loop block wasn't marked as live so far, then it's dead.
233  if (!LiveLoopBlocks.count(BB)) {
234  DeadLoopBlocks.push_back(BB);
235  continue;
236  }
237 
238  BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
239 
240  // If a block has only one live successor, it's a candidate on constant
241  // folding. Only handle blocks from current loop: branches in child loops
242  // are skipped because if they can be folded, they should be folded during
243  // the processing of child loops.
244  bool TakeFoldCandidate = TheOnlySucc && LI.getLoopFor(BB) == &L;
245  if (TakeFoldCandidate)
246  FoldCandidates.push_back(BB);
247 
248  // Handle successors.
249  for (BasicBlock *Succ : successors(BB))
250  if (!TakeFoldCandidate || TheOnlySucc == Succ) {
251  if (L.contains(Succ))
252  LiveLoopBlocks.insert(Succ);
253  else
254  LiveExitBlocks.insert(Succ);
255  }
256  }
257 
258  // Sanity check: amount of dead and live loop blocks should match the total
259  // number of blocks in loop.
260  assert(L.getNumBlocks() == LiveLoopBlocks.size() + DeadLoopBlocks.size() &&
261  "Malformed block sets?");
262 
263  // Now, all exit blocks that are not marked as live are dead.
264  SmallVector<BasicBlock *, 8> ExitBlocks;
265  L.getExitBlocks(ExitBlocks);
266  SmallPtrSet<BasicBlock *, 8> UniqueDeadExits;
267  for (auto *ExitBlock : ExitBlocks)
268  if (!LiveExitBlocks.count(ExitBlock) &&
269  UniqueDeadExits.insert(ExitBlock).second)
270  DeadExitBlocks.push_back(ExitBlock);
271 
272  // Whether or not the edge From->To will still be present in graph after the
273  // folding.
274  auto IsEdgeLive = [&](BasicBlock *From, BasicBlock *To) {
275  if (!LiveLoopBlocks.count(From))
276  return false;
277  BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(From);
278  return !TheOnlySucc || TheOnlySucc == To || LI.getLoopFor(From) != &L;
279  };
280 
281  // The loop will not be destroyed if its latch is live.
282  DeleteCurrentLoop = !IsEdgeLive(L.getLoopLatch(), L.getHeader());
283 
284  // If we are going to delete the current loop completely, no extra analysis
285  // is needed.
286  if (DeleteCurrentLoop)
287  return;
288 
289  // Otherwise, we should check which blocks will still be a part of the
290  // current loop after the transform.
291  BlocksInLoopAfterFolding.insert(L.getLoopLatch());
292  // If the loop is live, then we should compute what blocks are still in
293  // loop after all branch folding has been done. A block is in loop if
294  // it has a live edge to another block that is in the loop; by definition,
295  // latch is in the loop.
296  auto BlockIsInLoop = [&](BasicBlock *BB) {
297  return any_of(successors(BB), [&](BasicBlock *Succ) {
298  return BlocksInLoopAfterFolding.count(Succ) && IsEdgeLive(BB, Succ);
299  });
300  };
301  for (auto I = DFS.beginPostorder(), E = DFS.endPostorder(); I != E; ++I) {
302  BasicBlock *BB = *I;
303  if (BlockIsInLoop(BB))
304  BlocksInLoopAfterFolding.insert(BB);
305  }
306 
307  // Sanity check: header must be in loop.
308  assert(BlocksInLoopAfterFolding.count(L.getHeader()) &&
309  "Header not in loop?");
310  assert(BlocksInLoopAfterFolding.size() <= LiveLoopBlocks.size() &&
311  "All blocks that stay in loop should be live!");
312  }
313 
314  /// We need to preserve static reachibility of all loop exit blocks (this is)
315  /// required by loop pass manager. In order to do it, we make the following
316  /// trick:
317  ///
318  /// preheader:
319  /// <preheader code>
320  /// br label %loop_header
321  ///
322  /// loop_header:
323  /// ...
324  /// br i1 false, label %dead_exit, label %loop_block
325  /// ...
326  ///
327  /// We cannot simply remove edge from the loop to dead exit because in this
328  /// case dead_exit (and its successors) may become unreachable. To avoid that,
329  /// we insert the following fictive preheader:
330  ///
331  /// preheader:
332  /// <preheader code>
333  /// switch i32 0, label %preheader-split,
334  /// [i32 1, label %dead_exit_1],
335  /// [i32 2, label %dead_exit_2],
336  /// ...
337  /// [i32 N, label %dead_exit_N],
338  ///
339  /// preheader-split:
340  /// br label %loop_header
341  ///
342  /// loop_header:
343  /// ...
344  /// br i1 false, label %dead_exit_N, label %loop_block
345  /// ...
346  ///
347  /// Doing so, we preserve static reachibility of all dead exits and can later
348  /// remove edges from the loop to these blocks.
349  void handleDeadExits() {
350  // If no dead exits, nothing to do.
351  if (DeadExitBlocks.empty())
352  return;
353 
354  // Construct split preheader and the dummy switch to thread edges from it to
355  // dead exits.
356  BasicBlock *Preheader = L.getLoopPreheader();
357  BasicBlock *NewPreheader = llvm::SplitBlock(
358  Preheader, Preheader->getTerminator(), &DT, &LI, MSSAU);
359 
360  IRBuilder<> Builder(Preheader->getTerminator());
361  SwitchInst *DummySwitch =
362  Builder.CreateSwitch(Builder.getInt32(0), NewPreheader);
363  Preheader->getTerminator()->eraseFromParent();
364 
365  unsigned DummyIdx = 1;
366  for (BasicBlock *BB : DeadExitBlocks) {
368  for (auto &PN : BB->phis())
369  DeadPhis.push_back(&PN);
370 
371  // Eliminate all Phis from dead exits.
372  for (Instruction *PN : DeadPhis) {
373  PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
374  PN->eraseFromParent();
375  }
376  assert(DummyIdx != 0 && "Too many dead exits!");
377  DummySwitch->addCase(Builder.getInt32(DummyIdx++), BB);
378  DTUpdates.push_back({DominatorTree::Insert, Preheader, BB});
379  ++NumLoopExitsDeleted;
380  }
381 
382  assert(L.getLoopPreheader() == NewPreheader && "Malformed CFG?");
383  if (Loop *OuterLoop = LI.getLoopFor(Preheader)) {
384  // When we break dead edges, the outer loop may become unreachable from
385  // the current loop. We need to fix loop info accordingly. For this, we
386  // find the most nested loop that still contains L and remove L from all
387  // loops that are inside of it.
388  Loop *StillReachable = getInnermostLoopFor(LiveExitBlocks, L, LI);
389 
390  // Okay, our loop is no longer in the outer loop (and maybe not in some of
391  // its parents as well). Make the fixup.
392  if (StillReachable != OuterLoop) {
393  LI.changeLoopFor(NewPreheader, StillReachable);
394  removeBlockFromLoops(NewPreheader, OuterLoop, StillReachable);
395  for (auto *BB : L.blocks())
396  removeBlockFromLoops(BB, OuterLoop, StillReachable);
397  OuterLoop->removeChildLoop(&L);
398  if (StillReachable)
399  StillReachable->addChildLoop(&L);
400  else
401  LI.addTopLevelLoop(&L);
402 
403  // Some values from loops in [OuterLoop, StillReachable) could be used
404  // in the current loop. Now it is not their child anymore, so such uses
405  // require LCSSA Phis.
406  Loop *FixLCSSALoop = OuterLoop;
407  while (FixLCSSALoop->getParentLoop() != StillReachable)
408  FixLCSSALoop = FixLCSSALoop->getParentLoop();
409  assert(FixLCSSALoop && "Should be a loop!");
410  // We need all DT updates to be done before forming LCSSA.
411  DTU.applyUpdates(DTUpdates);
412  if (MSSAU)
413  MSSAU->applyUpdates(DTUpdates, DT);
414  DTUpdates.clear();
415  formLCSSARecursively(*FixLCSSALoop, DT, &LI, &SE);
416  }
417  }
418 
419  if (MSSAU) {
420  // Clear all updates now. Facilitates deletes that follow.
421  DTU.applyUpdates(DTUpdates);
422  MSSAU->applyUpdates(DTUpdates, DT);
423  DTUpdates.clear();
424  if (VerifyMemorySSA)
425  MSSAU->getMemorySSA()->verifyMemorySSA();
426  }
427  }
428 
429  /// Delete loop blocks that have become unreachable after folding. Make all
430  /// relevant updates to DT and LI.
431  void deleteDeadLoopBlocks() {
432  if (MSSAU) {
433  SmallSetVector<BasicBlock *, 8> DeadLoopBlocksSet(DeadLoopBlocks.begin(),
434  DeadLoopBlocks.end());
435  MSSAU->removeBlocks(DeadLoopBlocksSet);
436  }
437 
438  // The function LI.erase has some invariants that need to be preserved when
439  // it tries to remove a loop which is not the top-level loop. In particular,
440  // it requires loop's preheader to be strictly in loop's parent. We cannot
441  // just remove blocks one by one, because after removal of preheader we may
442  // break this invariant for the dead loop. So we detatch and erase all dead
443  // loops beforehand.
444  for (auto *BB : DeadLoopBlocks)
445  if (LI.isLoopHeader(BB)) {
446  assert(LI.getLoopFor(BB) != &L && "Attempt to remove current loop!");
447  Loop *DL = LI.getLoopFor(BB);
448  if (DL->getParentLoop()) {
449  for (auto *PL = DL->getParentLoop(); PL; PL = PL->getParentLoop())
450  for (auto *BB : DL->getBlocks())
451  PL->removeBlockFromLoop(BB);
452  DL->getParentLoop()->removeChildLoop(DL);
453  LI.addTopLevelLoop(DL);
454  }
455  LI.erase(DL);
456  }
457 
458  for (auto *BB : DeadLoopBlocks) {
459  assert(BB != L.getHeader() &&
460  "Header of the current loop cannot be dead!");
461  LLVM_DEBUG(dbgs() << "Deleting dead loop block " << BB->getName()
462  << "\n");
463  LI.removeBlock(BB);
464  }
465 
466  DetatchDeadBlocks(DeadLoopBlocks, &DTUpdates, /*KeepOneInputPHIs*/true);
467  DTU.applyUpdates(DTUpdates);
468  DTUpdates.clear();
469  for (auto *BB : DeadLoopBlocks)
470  DTU.deleteBB(BB);
471 
472  NumLoopBlocksDeleted += DeadLoopBlocks.size();
473  }
474 
475  /// Constant-fold terminators of blocks acculumated in FoldCandidates into the
476  /// unconditional branches.
477  void foldTerminators() {
478  for (BasicBlock *BB : FoldCandidates) {
479  assert(LI.getLoopFor(BB) == &L && "Should be a loop block!");
480  BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
481  assert(TheOnlySucc && "Should have one live successor!");
482 
483  LLVM_DEBUG(dbgs() << "Replacing terminator of " << BB->getName()
484  << " with an unconditional branch to the block "
485  << TheOnlySucc->getName() << "\n");
486 
487  SmallPtrSet<BasicBlock *, 2> DeadSuccessors;
488  // Remove all BB's successors except for the live one.
489  unsigned TheOnlySuccDuplicates = 0;
490  for (auto *Succ : successors(BB))
491  if (Succ != TheOnlySucc) {
492  DeadSuccessors.insert(Succ);
493  // If our successor lies in a different loop, we don't want to remove
494  // the one-input Phi because it is a LCSSA Phi.
495  bool PreserveLCSSAPhi = !L.contains(Succ);
496  Succ->removePredecessor(BB, PreserveLCSSAPhi);
497  if (MSSAU)
498  MSSAU->removeEdge(BB, Succ);
499  } else
500  ++TheOnlySuccDuplicates;
501 
502  assert(TheOnlySuccDuplicates > 0 && "Should be!");
503  // If TheOnlySucc was BB's successor more than once, after transform it
504  // will be its successor only once. Remove redundant inputs from
505  // TheOnlySucc's Phis.
506  bool PreserveLCSSAPhi = !L.contains(TheOnlySucc);
507  for (unsigned Dup = 1; Dup < TheOnlySuccDuplicates; ++Dup)
508  TheOnlySucc->removePredecessor(BB, PreserveLCSSAPhi);
509  if (MSSAU && TheOnlySuccDuplicates > 1)
510  MSSAU->removeDuplicatePhiEdgesBetween(BB, TheOnlySucc);
511 
512  IRBuilder<> Builder(BB->getContext());
513  Instruction *Term = BB->getTerminator();
514  Builder.SetInsertPoint(Term);
515  Builder.CreateBr(TheOnlySucc);
516  Term->eraseFromParent();
517 
518  for (auto *DeadSucc : DeadSuccessors)
519  DTUpdates.push_back({DominatorTree::Delete, BB, DeadSucc});
520 
521  ++NumTerminatorsFolded;
522  }
523  }
524 
525 public:
526  ConstantTerminatorFoldingImpl(Loop &L, LoopInfo &LI, DominatorTree &DT,
527  ScalarEvolution &SE,
528  MemorySSAUpdater *MSSAU)
529  : L(L), LI(LI), DT(DT), SE(SE), MSSAU(MSSAU), DFS(&L),
531  bool run() {
532  assert(L.getLoopLatch() && "Should be single latch!");
533 
534  // Collect all available information about status of blocks after constant
535  // folding.
536  analyze();
537  BasicBlock *Header = L.getHeader();
538  (void)Header;
539 
540  LLVM_DEBUG(dbgs() << "In function " << Header->getParent()->getName()
541  << ": ");
542 
543  if (HasIrreducibleCFG) {
544  LLVM_DEBUG(dbgs() << "Loops with irreducible CFG are not supported!\n");
545  return false;
546  }
547 
548  // Nothing to constant-fold.
549  if (FoldCandidates.empty()) {
550  LLVM_DEBUG(
551  dbgs() << "No constant terminator folding candidates found in loop "
552  << Header->getName() << "\n");
553  return false;
554  }
555 
556  // TODO: Support deletion of the current loop.
557  if (DeleteCurrentLoop) {
558  LLVM_DEBUG(
559  dbgs()
560  << "Give up constant terminator folding in loop " << Header->getName()
561  << ": we don't currently support deletion of the current loop.\n");
562  return false;
563  }
564 
565  // TODO: Support blocks that are not dead, but also not in loop after the
566  // folding.
567  if (BlocksInLoopAfterFolding.size() + DeadLoopBlocks.size() !=
568  L.getNumBlocks()) {
569  LLVM_DEBUG(
570  dbgs() << "Give up constant terminator folding in loop "
571  << Header->getName() << ": we don't currently"
572  " support blocks that are not dead, but will stop "
573  "being a part of the loop after constant-folding.\n");
574  return false;
575  }
576 
577  SE.forgetTopmostLoop(&L);
578  // Dump analysis results.
579  LLVM_DEBUG(dump());
580 
581  LLVM_DEBUG(dbgs() << "Constant-folding " << FoldCandidates.size()
582  << " terminators in loop " << Header->getName() << "\n");
583 
584  // Make the actual transforms.
585  handleDeadExits();
586  foldTerminators();
587 
588  if (!DeadLoopBlocks.empty()) {
589  LLVM_DEBUG(dbgs() << "Deleting " << DeadLoopBlocks.size()
590  << " dead blocks in loop " << Header->getName() << "\n");
591  deleteDeadLoopBlocks();
592  } else {
593  // If we didn't do updates inside deleteDeadLoopBlocks, do them here.
594  DTU.applyUpdates(DTUpdates);
595  DTUpdates.clear();
596  }
597 
598  if (MSSAU && VerifyMemorySSA)
599  MSSAU->getMemorySSA()->verifyMemorySSA();
600 
601 #ifndef NDEBUG
602  // Make sure that we have preserved all data structures after the transform.
603 #if defined(EXPENSIVE_CHECKS)
605  "DT broken after transform!");
606 #else
608  "DT broken after transform!");
609 #endif
610  assert(DT.isReachableFromEntry(Header));
611  LI.verify(DT);
612 #endif
613 
614  return true;
615  }
616 
617  bool foldingBreaksCurrentLoop() const {
618  return DeleteCurrentLoop;
619  }
620 };
621 } // namespace
622 
623 /// Turn branches and switches with known constant conditions into unconditional
624 /// branches.
626  ScalarEvolution &SE,
627  MemorySSAUpdater *MSSAU,
628  bool &IsLoopDeleted) {
629  if (!EnableTermFolding)
630  return false;
631 
632  // To keep things simple, only process loops with single latch. We
633  // canonicalize most loops to this form. We can support multi-latch if needed.
634  if (!L.getLoopLatch())
635  return false;
636 
637  ConstantTerminatorFoldingImpl BranchFolder(L, LI, DT, SE, MSSAU);
638  bool Changed = BranchFolder.run();
639  IsLoopDeleted = Changed && BranchFolder.foldingBreaksCurrentLoop();
640  return Changed;
641 }
642 
644  LoopInfo &LI, MemorySSAUpdater *MSSAU) {
645  bool Changed = false;
647  // Copy blocks into a temporary array to avoid iterator invalidation issues
648  // as we remove them.
650 
651  for (auto &Block : Blocks) {
652  // Attempt to merge blocks in the trivial case. Don't modify blocks which
653  // belong to other loops.
654  BasicBlock *Succ = cast_or_null<BasicBlock>(Block);
655  if (!Succ)
656  continue;
657 
658  BasicBlock *Pred = Succ->getSinglePredecessor();
659  if (!Pred || !Pred->getSingleSuccessor() || LI.getLoopFor(Pred) != &L)
660  continue;
661 
662  // Merge Succ into Pred and delete it.
663  MergeBlockIntoPredecessor(Succ, &DTU, &LI, MSSAU);
664 
665  if (MSSAU && VerifyMemorySSA)
666  MSSAU->getMemorySSA()->verifyMemorySSA();
667 
668  Changed = true;
669  }
670 
671  return Changed;
672 }
673 
674 static bool simplifyLoopCFG(Loop &L, DominatorTree &DT, LoopInfo &LI,
675  ScalarEvolution &SE, MemorySSAUpdater *MSSAU,
676  bool &isLoopDeleted) {
677  bool Changed = false;
678 
679  // Constant-fold terminators with known constant conditions.
680  Changed |= constantFoldTerminators(L, DT, LI, SE, MSSAU, isLoopDeleted);
681 
682  if (isLoopDeleted)
683  return true;
684 
685  // Eliminate unconditional branches by merging blocks into their predecessors.
686  Changed |= mergeBlocksIntoPredecessors(L, DT, LI, MSSAU);
687 
688  if (Changed)
689  SE.forgetTopmostLoop(&L);
690 
691  return Changed;
692 }
693 
696  LPMUpdater &LPMU) {
698  if (AR.MSSA)
699  MSSAU = MemorySSAUpdater(AR.MSSA);
700  bool DeleteCurrentLoop = false;
701  if (!simplifyLoopCFG(L, AR.DT, AR.LI, AR.SE,
702  MSSAU.hasValue() ? MSSAU.getPointer() : nullptr,
703  DeleteCurrentLoop))
704  return PreservedAnalyses::all();
705 
706  if (DeleteCurrentLoop)
707  LPMU.markLoopAsDeleted(L, "loop-simplifycfg");
708 
709  auto PA = getLoopPassPreservedAnalyses();
710  if (AR.MSSA)
711  PA.preserve<MemorySSAAnalysis>();
712  return PA;
713 }
714 
715 namespace {
716 class LoopSimplifyCFGLegacyPass : public LoopPass {
717 public:
718  static char ID; // Pass ID, replacement for typeid
719  LoopSimplifyCFGLegacyPass() : LoopPass(ID) {
721  }
722 
723  bool runOnLoop(Loop *L, LPPassManager &LPM) override {
724  if (skipLoop(L))
725  return false;
726 
727  DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
728  LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
729  ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
732  MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
733  MSSAU = MemorySSAUpdater(MSSA);
734  if (VerifyMemorySSA)
735  MSSA->verifyMemorySSA();
736  }
737  bool DeleteCurrentLoop = false;
738  bool Changed = simplifyLoopCFG(
739  *L, DT, LI, SE, MSSAU.hasValue() ? MSSAU.getPointer() : nullptr,
740  DeleteCurrentLoop);
741  if (DeleteCurrentLoop)
742  LPM.markLoopAsDeleted(*L);
743  return Changed;
744  }
745 
746  void getAnalysisUsage(AnalysisUsage &AU) const override {
750  }
753  }
754 };
755 }
756 
758 INITIALIZE_PASS_BEGIN(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
759  "Simplify loop CFG", false, false)
762 INITIALIZE_PASS_END(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
763  "Simplify loop CFG", false, false)
764 
766  return new LoopSimplifyCFGLegacyPass();
767 }
Pass interface - Implemented by all &#39;passes&#39;.
Definition: Pass.h:78
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:67
static bool simplifyLoopCFG(Loop &L, DominatorTree &DT, LoopInfo &LI, ScalarEvolution &SE, MemorySSAUpdater *MSSAU, bool &isLoopDeleted)
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
Definition: LoopInfoImpl.h:209
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition: MemorySSA.cpp:84
This class represents lattice values for constants.
Definition: AllocatorList.h:23
This header provides classes for managing a pipeline of passes over loops in LLVM IR...
This is the interface for a simple mod/ref and alias analysis over globals.
BasicBlock * getSuccessor(unsigned Idx) const
Return the specified successor. This instruction must be a terminator.
static bool mergeBlocksIntoPredecessors(Loop &L, DominatorTree &DT, LoopInfo &LI, MemorySSAUpdater *MSSAU)
Legacy pass manager pass to access dependence information.
unsigned getLoopDepth() const
Return the nesting level of this loop.
Definition: LoopInfo.h:97
The main scalar evolution driver.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Definition: LoopInfoImpl.h:160
static Loop * getInnermostLoopFor(SmallPtrSetImpl< BasicBlock *> &BBs, Loop &L, LoopInfo &LI)
Find innermost loop that contains at least one block from BBs and contains the header of loop L...
static BasicBlock * getOnlyLiveSuccessor(BasicBlock *BB)
If BB is a switch or a conditional branch, but only one of its successors can be reached from this bl...
STATISTIC(NumFunctions, "Total number of functions")
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:144
BasicBlock * SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction - everything before SplitPt stays in Old and e...
bool isComplete() const
Return true if postorder numbers are assigned to all loop blocks.
Definition: LoopIterator.h:126
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Definition: Dominators.cpp:300
void verify(const DominatorTreeBase< BlockT, false > &DomTree) const
Definition: LoopInfoImpl.h:681
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:343
bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false)
Attempts to merge a block into its predecessor, if possible.
bool formLCSSARecursively(Loop &L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
Definition: LCSSA.cpp:386
void removeEdge(BasicBlock *From, BasicBlock *To)
Update the MemoryPhi in To following an edge deletion between From and To.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
Legacy analysis pass which computes MemorySSA.
Definition: MemorySSA.h:964
This is the interface for a SCEV-based alias analysis.
MemorySSA * getMemorySSA() const
Get handle on MemorySSA.
POIterator beginPostorder() const
Iterate over the cached postorder blocks.
Definition: LoopIterator.h:129
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
loop simplifycfg
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Definition: LoopInfo.h:939
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition: MemorySSA.h:704
void applyUpdates(ArrayRef< CFGUpdate > Updates, DominatorTree &DT)
Apply CFG updates, analogous with the DT edge updates.
void erase(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
Definition: LoopInfo.cpp:858
RPOIterator endRPO() const
Definition: LoopIterator.h:140
BlockT * getHeader() const
Definition: LoopInfo.h:105
void getExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all of the successor blocks of this loop.
Definition: LoopInfoImpl.h:62
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
Definition: LoopInfo.h:990
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
Definition: BasicBlock.cpp:275
void perform(LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
Definition: LoopInfo.cpp:1108
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:144
static cl::opt< bool > EnableTermFolding("enable-loop-simplifycfg-term-folding", cl::init(true))
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:435
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:154
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:240
LLVM Basic Block Representation.
Definition: BasicBlock.h:57
void deleteBB(BasicBlock *DelBB)
Delete DelBB.
Conditional or Unconditional Branch instruction.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
void removeDuplicatePhiEdgesBetween(const BasicBlock *From, const BasicBlock *To)
Update the MemoryPhi in To to have a single incoming edge from From, following a CFG change that repl...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:370
Represent the analysis usage information of a pass.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1189
const T * getPointer() const
Definition: Optional.h:253
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:381
static UndefValue * get(Type *T)
Static factory methods - Return an &#39;undef&#39; object of the specified type.
Definition: Constants.cpp:1514
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:160
size_t size() const
Definition: SmallVector.h:52
void markLoopAsDeleted(Loop &L, llvm::StringRef Name)
Loop passes should use this method to indicate they have deleted a loop from the nest.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
size_type size() const
Definition: SmallPtrSet.h:92
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
Definition: LoopInfo.h:115
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:297
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:443
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
BlockVerifier::State From
static bool constantFoldTerminators(Loop &L, DominatorTree &DT, LoopInfo &LI, ScalarEvolution &SE, MemorySSAUpdater *MSSAU, bool &IsLoopDeleted)
Turn branches and switches with known constant conditions into unconditional branches.
void applyUpdates(ArrayRef< DominatorTree::UpdateType > Updates)
Submit updates to all available trees.
void verifyMemorySSA() const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
Definition: MemorySSA.cpp:1872
An analysis that produces MemorySSA for a function.
Definition: MemorySSA.h:925
Pass * createLoopSimplifyCFGPass()
void markLoopAsDeleted(Loop &L)
Definition: LoopPass.cpp:144
loop Simplify loop CFG
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
Store the result of a depth first search within basic blocks contained by a single loop...
Definition: LoopIterator.h:97
static void DFS(BasicBlock *Root, SetVector< BasicBlock *> &Set)
bool isLoopHeader(const BlockT *BB) const
Definition: LoopInfo.h:952
void initializeLoopSimplifyCFGLegacyPassPass(PassRegistry &)
static void removeBlockFromLoops(BasicBlock *BB, Loop *FirstLoop, Loop *LastLoop=nullptr)
Removes BB from all loops from [FirstLoop, LastLoop) in parent chain.
POIterator endPostorder() const
Definition: LoopIterator.h:133
LoopT * getParentLoop() const
Definition: LoopInfo.h:106
unsigned getNumBlocks() const
Get the number of blocks in this loop in constant time.
Definition: LoopInfo.h:168
bool hasValue() const
Definition: Optional.h:259
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
Definition: LoopInfo.h:375
INITIALIZE_PASS_BEGIN(LoopSimplifyCFGLegacyPass, "loop-simplifycfg", "Simplify loop CFG", false, false) INITIALIZE_PASS_END(LoopSimplifyCFGLegacyPass
cl::opt< bool > EnableMSSALoopDependency
Enables memory ssa as a dependency for loop passes.
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:509
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:215
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:106
#define I(x, y, z)
Definition: MD5.cpp:58
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition: Constants.h:192
void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass&#39;s AnalysisUsage.
Definition: LoopUtils.cpp:138
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:332
Multiway switch.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void removeBlocks(const SmallSetVector< BasicBlock *, 8 > &DeadBlocks)
Remove all MemoryAcceses in a set of BasicBlocks about to be deleted.
Fast - This calling convention attempts to make calls as fast as possible (e.g.
Definition: CallingConv.h:42
rpo Deduce function attributes in RPO
succ_range successors(Instruction *I)
Definition: CFG.h:259
RPOIterator beginRPO() const
Reverse iterate over the cached postorder blocks.
Definition: LoopIterator.h:136
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
This is the interface for LLVM&#39;s primary stateless and local alias analysis.
A container for analyses that lazily runs them and caches their results.
This pass exposes codegen information to IR-level passes.
#define LLVM_DEBUG(X)
Definition: Debug.h:122
iterator_range< block_iterator > blocks() const
Definition: LoopInfo.h:161
void DetatchDeadBlocks(ArrayRef< BasicBlock *> BBs, SmallVectorImpl< DominatorTree::UpdateType > *Updates, bool KeepOneInputPHIs=false)
Replace contents of every block in BBs with single unreachable instruction.
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
Definition: LoopInfo.h:998
void forgetTopmostLoop(const Loop *L)