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