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