Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/Scalar/LoopSimplifyCFG.cpp
35269 views
//===--------- LoopSimplifyCFG.cpp - Loop CFG Simplification Pass ---------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the Loop SimplifyCFG Pass. This pass is responsible for9// basic loop CFG cleanup, primarily to assist other loop passes. If you10// encounter a noncanonical CFG construct that causes another loop pass to11// perform suboptimally, this is the place to fix it up.12//13//===----------------------------------------------------------------------===//1415#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"16#include "llvm/ADT/SmallVector.h"17#include "llvm/ADT/Statistic.h"18#include "llvm/Analysis/DomTreeUpdater.h"19#include "llvm/Analysis/LoopInfo.h"20#include "llvm/Analysis/LoopIterator.h"21#include "llvm/Analysis/MemorySSA.h"22#include "llvm/Analysis/MemorySSAUpdater.h"23#include "llvm/Analysis/ScalarEvolution.h"24#include "llvm/IR/Dominators.h"25#include "llvm/IR/IRBuilder.h"26#include "llvm/Support/CommandLine.h"27#include "llvm/Transforms/Scalar.h"28#include "llvm/Transforms/Scalar/LoopPassManager.h"29#include "llvm/Transforms/Utils/BasicBlockUtils.h"30#include "llvm/Transforms/Utils/LoopUtils.h"31#include <optional>32using namespace llvm;3334#define DEBUG_TYPE "loop-simplifycfg"3536static cl::opt<bool> EnableTermFolding("enable-loop-simplifycfg-term-folding",37cl::init(true));3839STATISTIC(NumTerminatorsFolded,40"Number of terminators folded to unconditional branches");41STATISTIC(NumLoopBlocksDeleted,42"Number of loop blocks deleted");43STATISTIC(NumLoopExitsDeleted,44"Number of loop exiting edges deleted");4546/// If \p BB is a switch or a conditional branch, but only one of its successors47/// can be reached from this block in runtime, return this successor. Otherwise,48/// return nullptr.49static BasicBlock *getOnlyLiveSuccessor(BasicBlock *BB) {50Instruction *TI = BB->getTerminator();51if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {52if (BI->isUnconditional())53return nullptr;54if (BI->getSuccessor(0) == BI->getSuccessor(1))55return BI->getSuccessor(0);56ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());57if (!Cond)58return nullptr;59return Cond->isZero() ? BI->getSuccessor(1) : BI->getSuccessor(0);60}6162if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {63auto *CI = dyn_cast<ConstantInt>(SI->getCondition());64if (!CI)65return nullptr;66for (auto Case : SI->cases())67if (Case.getCaseValue() == CI)68return Case.getCaseSuccessor();69return SI->getDefaultDest();70}7172return nullptr;73}7475/// Removes \p BB from all loops from [FirstLoop, LastLoop) in parent chain.76static void removeBlockFromLoops(BasicBlock *BB, Loop *FirstLoop,77Loop *LastLoop = nullptr) {78assert((!LastLoop || LastLoop->contains(FirstLoop->getHeader())) &&79"First loop is supposed to be inside of last loop!");80assert(FirstLoop->contains(BB) && "Must be a loop block!");81for (Loop *Current = FirstLoop; Current != LastLoop;82Current = Current->getParentLoop())83Current->removeBlockFromLoop(BB);84}8586/// Find innermost loop that contains at least one block from \p BBs and87/// contains the header of loop \p L.88static Loop *getInnermostLoopFor(SmallPtrSetImpl<BasicBlock *> &BBs,89Loop &L, LoopInfo &LI) {90Loop *Innermost = nullptr;91for (BasicBlock *BB : BBs) {92Loop *BBL = LI.getLoopFor(BB);93while (BBL && !BBL->contains(L.getHeader()))94BBL = BBL->getParentLoop();95if (BBL == &L)96BBL = BBL->getParentLoop();97if (!BBL)98continue;99if (!Innermost || BBL->getLoopDepth() > Innermost->getLoopDepth())100Innermost = BBL;101}102return Innermost;103}104105namespace {106/// Helper class that can turn branches and switches with constant conditions107/// into unconditional branches.108class ConstantTerminatorFoldingImpl {109private:110Loop &L;111LoopInfo &LI;112DominatorTree &DT;113ScalarEvolution &SE;114MemorySSAUpdater *MSSAU;115LoopBlocksDFS DFS;116DomTreeUpdater DTU;117SmallVector<DominatorTree::UpdateType, 16> DTUpdates;118119// Whether or not the current loop has irreducible CFG.120bool HasIrreducibleCFG = false;121// Whether or not the current loop will still exist after terminator constant122// folding will be done. In theory, there are two ways how it can happen:123// 1. Loop's latch(es) become unreachable from loop header;124// 2. Loop's header becomes unreachable from method entry.125// In practice, the second situation is impossible because we only modify the126// current loop and its preheader and do not affect preheader's reachibility127// from any other block. So this variable set to true means that loop's latch128// has become unreachable from loop header.129bool DeleteCurrentLoop = false;130131// The blocks of the original loop that will still be reachable from entry132// after the constant folding.133SmallPtrSet<BasicBlock *, 8> LiveLoopBlocks;134// The blocks of the original loop that will become unreachable from entry135// after the constant folding.136SmallVector<BasicBlock *, 8> DeadLoopBlocks;137// The exits of the original loop that will still be reachable from entry138// after the constant folding.139SmallPtrSet<BasicBlock *, 8> LiveExitBlocks;140// The exits of the original loop that will become unreachable from entry141// after the constant folding.142SmallVector<BasicBlock *, 8> DeadExitBlocks;143// The blocks that will still be a part of the current loop after folding.144SmallPtrSet<BasicBlock *, 8> BlocksInLoopAfterFolding;145// The blocks that have terminators with constant condition that can be146// folded. Note: fold candidates should be in L but not in any of its147// subloops to avoid complex LI updates.148SmallVector<BasicBlock *, 8> FoldCandidates;149150void dump() const {151dbgs() << "Constant terminator folding for loop " << L << "\n";152dbgs() << "After terminator constant-folding, the loop will";153if (!DeleteCurrentLoop)154dbgs() << " not";155dbgs() << " be destroyed\n";156auto PrintOutVector = [&](const char *Message,157const SmallVectorImpl<BasicBlock *> &S) {158dbgs() << Message << "\n";159for (const BasicBlock *BB : S)160dbgs() << "\t" << BB->getName() << "\n";161};162auto PrintOutSet = [&](const char *Message,163const SmallPtrSetImpl<BasicBlock *> &S) {164dbgs() << Message << "\n";165for (const BasicBlock *BB : S)166dbgs() << "\t" << BB->getName() << "\n";167};168PrintOutVector("Blocks in which we can constant-fold terminator:",169FoldCandidates);170PrintOutSet("Live blocks from the original loop:", LiveLoopBlocks);171PrintOutVector("Dead blocks from the original loop:", DeadLoopBlocks);172PrintOutSet("Live exit blocks:", LiveExitBlocks);173PrintOutVector("Dead exit blocks:", DeadExitBlocks);174if (!DeleteCurrentLoop)175PrintOutSet("The following blocks will still be part of the loop:",176BlocksInLoopAfterFolding);177}178179/// Whether or not the current loop has irreducible CFG.180bool hasIrreducibleCFG(LoopBlocksDFS &DFS) {181assert(DFS.isComplete() && "DFS is expected to be finished");182// Index of a basic block in RPO traversal.183DenseMap<const BasicBlock *, unsigned> RPO;184unsigned Current = 0;185for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I)186RPO[*I] = Current++;187188for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {189BasicBlock *BB = *I;190for (auto *Succ : successors(BB))191if (L.contains(Succ) && !LI.isLoopHeader(Succ) && RPO[BB] > RPO[Succ])192// If an edge goes from a block with greater order number into a block193// with lesses number, and it is not a loop backedge, then it can only194// be a part of irreducible non-loop cycle.195return true;196}197return false;198}199200/// Fill all information about status of blocks and exits of the current loop201/// if constant folding of all branches will be done.202void analyze() {203DFS.perform(&LI);204assert(DFS.isComplete() && "DFS is expected to be finished");205206// TODO: The algorithm below relies on both RPO and Postorder traversals.207// When the loop has only reducible CFG inside, then the invariant "all208// predecessors of X are processed before X in RPO" is preserved. However209// an irreducible loop can break this invariant (e.g. latch does not have to210// be the last block in the traversal in this case, and the algorithm relies211// on this). We can later decide to support such cases by altering the212// algorithms, but so far we just give up analyzing them.213if (hasIrreducibleCFG(DFS)) {214HasIrreducibleCFG = true;215return;216}217218// Collect live and dead loop blocks and exits.219LiveLoopBlocks.insert(L.getHeader());220for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {221BasicBlock *BB = *I;222223// If a loop block wasn't marked as live so far, then it's dead.224if (!LiveLoopBlocks.count(BB)) {225DeadLoopBlocks.push_back(BB);226continue;227}228229BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);230231// If a block has only one live successor, it's a candidate on constant232// folding. Only handle blocks from current loop: branches in child loops233// are skipped because if they can be folded, they should be folded during234// the processing of child loops.235bool TakeFoldCandidate = TheOnlySucc && LI.getLoopFor(BB) == &L;236if (TakeFoldCandidate)237FoldCandidates.push_back(BB);238239// Handle successors.240for (BasicBlock *Succ : successors(BB))241if (!TakeFoldCandidate || TheOnlySucc == Succ) {242if (L.contains(Succ))243LiveLoopBlocks.insert(Succ);244else245LiveExitBlocks.insert(Succ);246}247}248249// Amount of dead and live loop blocks should match the total number of250// blocks in loop.251assert(L.getNumBlocks() == LiveLoopBlocks.size() + DeadLoopBlocks.size() &&252"Malformed block sets?");253254// Now, all exit blocks that are not marked as live are dead, if all their255// predecessors are in the loop. This may not be the case, as the input loop256// may not by in loop-simplify/canonical form.257SmallVector<BasicBlock *, 8> ExitBlocks;258L.getExitBlocks(ExitBlocks);259SmallPtrSet<BasicBlock *, 8> UniqueDeadExits;260for (auto *ExitBlock : ExitBlocks)261if (!LiveExitBlocks.count(ExitBlock) &&262UniqueDeadExits.insert(ExitBlock).second &&263all_of(predecessors(ExitBlock),264[this](BasicBlock *Pred) { return L.contains(Pred); }))265DeadExitBlocks.push_back(ExitBlock);266267// Whether or not the edge From->To will still be present in graph after the268// folding.269auto IsEdgeLive = [&](BasicBlock *From, BasicBlock *To) {270if (!LiveLoopBlocks.count(From))271return false;272BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(From);273return !TheOnlySucc || TheOnlySucc == To || LI.getLoopFor(From) != &L;274};275276// The loop will not be destroyed if its latch is live.277DeleteCurrentLoop = !IsEdgeLive(L.getLoopLatch(), L.getHeader());278279// If we are going to delete the current loop completely, no extra analysis280// is needed.281if (DeleteCurrentLoop)282return;283284// Otherwise, we should check which blocks will still be a part of the285// current loop after the transform.286BlocksInLoopAfterFolding.insert(L.getLoopLatch());287// If the loop is live, then we should compute what blocks are still in288// loop after all branch folding has been done. A block is in loop if289// it has a live edge to another block that is in the loop; by definition,290// latch is in the loop.291auto BlockIsInLoop = [&](BasicBlock *BB) {292return any_of(successors(BB), [&](BasicBlock *Succ) {293return BlocksInLoopAfterFolding.count(Succ) && IsEdgeLive(BB, Succ);294});295};296for (auto I = DFS.beginPostorder(), E = DFS.endPostorder(); I != E; ++I) {297BasicBlock *BB = *I;298if (BlockIsInLoop(BB))299BlocksInLoopAfterFolding.insert(BB);300}301302assert(BlocksInLoopAfterFolding.count(L.getHeader()) &&303"Header not in loop?");304assert(BlocksInLoopAfterFolding.size() <= LiveLoopBlocks.size() &&305"All blocks that stay in loop should be live!");306}307308/// We need to preserve static reachibility of all loop exit blocks (this is)309/// required by loop pass manager. In order to do it, we make the following310/// trick:311///312/// preheader:313/// <preheader code>314/// br label %loop_header315///316/// loop_header:317/// ...318/// br i1 false, label %dead_exit, label %loop_block319/// ...320///321/// We cannot simply remove edge from the loop to dead exit because in this322/// case dead_exit (and its successors) may become unreachable. To avoid that,323/// we insert the following fictive preheader:324///325/// preheader:326/// <preheader code>327/// switch i32 0, label %preheader-split,328/// [i32 1, label %dead_exit_1],329/// [i32 2, label %dead_exit_2],330/// ...331/// [i32 N, label %dead_exit_N],332///333/// preheader-split:334/// br label %loop_header335///336/// loop_header:337/// ...338/// br i1 false, label %dead_exit_N, label %loop_block339/// ...340///341/// Doing so, we preserve static reachibility of all dead exits and can later342/// remove edges from the loop to these blocks.343void handleDeadExits() {344// If no dead exits, nothing to do.345if (DeadExitBlocks.empty())346return;347348// Construct split preheader and the dummy switch to thread edges from it to349// dead exits.350BasicBlock *Preheader = L.getLoopPreheader();351BasicBlock *NewPreheader = llvm::SplitBlock(352Preheader, Preheader->getTerminator(), &DT, &LI, MSSAU);353354IRBuilder<> Builder(Preheader->getTerminator());355SwitchInst *DummySwitch =356Builder.CreateSwitch(Builder.getInt32(0), NewPreheader);357Preheader->getTerminator()->eraseFromParent();358359unsigned DummyIdx = 1;360for (BasicBlock *BB : DeadExitBlocks) {361// Eliminate all Phis and LandingPads from dead exits.362// TODO: Consider removing all instructions in this dead block.363SmallVector<Instruction *, 4> DeadInstructions;364for (auto &PN : BB->phis())365DeadInstructions.push_back(&PN);366367if (auto *LandingPad = dyn_cast<LandingPadInst>(BB->getFirstNonPHI()))368DeadInstructions.emplace_back(LandingPad);369370for (Instruction *I : DeadInstructions) {371SE.forgetBlockAndLoopDispositions(I);372I->replaceAllUsesWith(PoisonValue::get(I->getType()));373I->eraseFromParent();374}375376assert(DummyIdx != 0 && "Too many dead exits!");377DummySwitch->addCase(Builder.getInt32(DummyIdx++), BB);378DTUpdates.push_back({DominatorTree::Insert, Preheader, BB});379++NumLoopExitsDeleted;380}381382assert(L.getLoopPreheader() == NewPreheader && "Malformed CFG?");383if (Loop *OuterLoop = LI.getLoopFor(Preheader)) {384// When we break dead edges, the outer loop may become unreachable from385// the current loop. We need to fix loop info accordingly. For this, we386// find the most nested loop that still contains L and remove L from all387// loops that are inside of it.388Loop *StillReachable = getInnermostLoopFor(LiveExitBlocks, L, LI);389390// Okay, our loop is no longer in the outer loop (and maybe not in some of391// its parents as well). Make the fixup.392if (StillReachable != OuterLoop) {393LI.changeLoopFor(NewPreheader, StillReachable);394removeBlockFromLoops(NewPreheader, OuterLoop, StillReachable);395for (auto *BB : L.blocks())396removeBlockFromLoops(BB, OuterLoop, StillReachable);397OuterLoop->removeChildLoop(&L);398if (StillReachable)399StillReachable->addChildLoop(&L);400else401LI.addTopLevelLoop(&L);402403// Some values from loops in [OuterLoop, StillReachable) could be used404// in the current loop. Now it is not their child anymore, so such uses405// require LCSSA Phis.406Loop *FixLCSSALoop = OuterLoop;407while (FixLCSSALoop->getParentLoop() != StillReachable)408FixLCSSALoop = FixLCSSALoop->getParentLoop();409assert(FixLCSSALoop && "Should be a loop!");410// We need all DT updates to be done before forming LCSSA.411if (MSSAU)412MSSAU->applyUpdates(DTUpdates, DT, /*UpdateDT=*/true);413else414DTU.applyUpdates(DTUpdates);415DTUpdates.clear();416formLCSSARecursively(*FixLCSSALoop, DT, &LI, &SE);417SE.forgetBlockAndLoopDispositions();418}419}420421if (MSSAU) {422// Clear all updates now. Facilitates deletes that follow.423MSSAU->applyUpdates(DTUpdates, DT, /*UpdateDT=*/true);424DTUpdates.clear();425if (VerifyMemorySSA)426MSSAU->getMemorySSA()->verifyMemorySSA();427}428}429430/// Delete loop blocks that have become unreachable after folding. Make all431/// relevant updates to DT and LI.432void deleteDeadLoopBlocks() {433if (MSSAU) {434SmallSetVector<BasicBlock *, 8> DeadLoopBlocksSet(DeadLoopBlocks.begin(),435DeadLoopBlocks.end());436MSSAU->removeBlocks(DeadLoopBlocksSet);437}438439// The function LI.erase has some invariants that need to be preserved when440// it tries to remove a loop which is not the top-level loop. In particular,441// it requires loop's preheader to be strictly in loop's parent. We cannot442// just remove blocks one by one, because after removal of preheader we may443// break this invariant for the dead loop. So we detatch and erase all dead444// loops beforehand.445for (auto *BB : DeadLoopBlocks)446if (LI.isLoopHeader(BB)) {447assert(LI.getLoopFor(BB) != &L && "Attempt to remove current loop!");448Loop *DL = LI.getLoopFor(BB);449if (!DL->isOutermost()) {450for (auto *PL = DL->getParentLoop(); PL; PL = PL->getParentLoop())451for (auto *BB : DL->getBlocks())452PL->removeBlockFromLoop(BB);453DL->getParentLoop()->removeChildLoop(DL);454LI.addTopLevelLoop(DL);455}456LI.erase(DL);457}458459for (auto *BB : DeadLoopBlocks) {460assert(BB != L.getHeader() &&461"Header of the current loop cannot be dead!");462LLVM_DEBUG(dbgs() << "Deleting dead loop block " << BB->getName()463<< "\n");464LI.removeBlock(BB);465}466467detachDeadBlocks(DeadLoopBlocks, &DTUpdates, /*KeepOneInputPHIs*/true);468DTU.applyUpdates(DTUpdates);469DTUpdates.clear();470for (auto *BB : DeadLoopBlocks)471DTU.deleteBB(BB);472473NumLoopBlocksDeleted += DeadLoopBlocks.size();474}475476/// Constant-fold terminators of blocks accumulated in FoldCandidates into the477/// unconditional branches.478void foldTerminators() {479for (BasicBlock *BB : FoldCandidates) {480assert(LI.getLoopFor(BB) == &L && "Should be a loop block!");481BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);482assert(TheOnlySucc && "Should have one live successor!");483484LLVM_DEBUG(dbgs() << "Replacing terminator of " << BB->getName()485<< " with an unconditional branch to the block "486<< TheOnlySucc->getName() << "\n");487488SmallPtrSet<BasicBlock *, 2> DeadSuccessors;489// Remove all BB's successors except for the live one.490unsigned TheOnlySuccDuplicates = 0;491for (auto *Succ : successors(BB))492if (Succ != TheOnlySucc) {493DeadSuccessors.insert(Succ);494// If our successor lies in a different loop, we don't want to remove495// the one-input Phi because it is a LCSSA Phi.496bool PreserveLCSSAPhi = !L.contains(Succ);497Succ->removePredecessor(BB, PreserveLCSSAPhi);498if (MSSAU)499MSSAU->removeEdge(BB, Succ);500} else501++TheOnlySuccDuplicates;502503assert(TheOnlySuccDuplicates > 0 && "Should be!");504// If TheOnlySucc was BB's successor more than once, after transform it505// will be its successor only once. Remove redundant inputs from506// TheOnlySucc's Phis.507bool PreserveLCSSAPhi = !L.contains(TheOnlySucc);508for (unsigned Dup = 1; Dup < TheOnlySuccDuplicates; ++Dup)509TheOnlySucc->removePredecessor(BB, PreserveLCSSAPhi);510if (MSSAU && TheOnlySuccDuplicates > 1)511MSSAU->removeDuplicatePhiEdgesBetween(BB, TheOnlySucc);512513IRBuilder<> Builder(BB->getContext());514Instruction *Term = BB->getTerminator();515Builder.SetInsertPoint(Term);516Builder.CreateBr(TheOnlySucc);517Term->eraseFromParent();518519for (auto *DeadSucc : DeadSuccessors)520DTUpdates.push_back({DominatorTree::Delete, BB, DeadSucc});521522++NumTerminatorsFolded;523}524}525526public:527ConstantTerminatorFoldingImpl(Loop &L, LoopInfo &LI, DominatorTree &DT,528ScalarEvolution &SE,529MemorySSAUpdater *MSSAU)530: L(L), LI(LI), DT(DT), SE(SE), MSSAU(MSSAU), DFS(&L),531DTU(DT, DomTreeUpdater::UpdateStrategy::Eager) {}532bool run() {533assert(L.getLoopLatch() && "Should be single latch!");534535// Collect all available information about status of blocks after constant536// folding.537analyze();538BasicBlock *Header = L.getHeader();539(void)Header;540541LLVM_DEBUG(dbgs() << "In function " << Header->getParent()->getName()542<< ": ");543544if (HasIrreducibleCFG) {545LLVM_DEBUG(dbgs() << "Loops with irreducible CFG are not supported!\n");546return false;547}548549// Nothing to constant-fold.550if (FoldCandidates.empty()) {551LLVM_DEBUG(552dbgs() << "No constant terminator folding candidates found in loop "553<< Header->getName() << "\n");554return false;555}556557// TODO: Support deletion of the current loop.558if (DeleteCurrentLoop) {559LLVM_DEBUG(560dbgs()561<< "Give up constant terminator folding in loop " << Header->getName()562<< ": we don't currently support deletion of the current loop.\n");563return false;564}565566// TODO: Support blocks that are not dead, but also not in loop after the567// folding.568if (BlocksInLoopAfterFolding.size() + DeadLoopBlocks.size() !=569L.getNumBlocks()) {570LLVM_DEBUG(571dbgs() << "Give up constant terminator folding in loop "572<< Header->getName() << ": we don't currently"573" support blocks that are not dead, but will stop "574"being a part of the loop after constant-folding.\n");575return false;576}577578// TODO: Tokens may breach LCSSA form by default. However, the transform for579// dead exit blocks requires LCSSA form to be maintained for all values,580// tokens included, otherwise it may break use-def dominance (see PR56243).581if (!DeadExitBlocks.empty() && !L.isLCSSAForm(DT, /*IgnoreTokens*/ false)) {582assert(L.isLCSSAForm(DT, /*IgnoreTokens*/ true) &&583"LCSSA broken not by tokens?");584LLVM_DEBUG(dbgs() << "Give up constant terminator folding in loop "585<< Header->getName()586<< ": tokens uses potentially break LCSSA form.\n");587return false;588}589590SE.forgetTopmostLoop(&L);591// Dump analysis results.592LLVM_DEBUG(dump());593594LLVM_DEBUG(dbgs() << "Constant-folding " << FoldCandidates.size()595<< " terminators in loop " << Header->getName() << "\n");596597if (!DeadLoopBlocks.empty())598SE.forgetBlockAndLoopDispositions();599600// Make the actual transforms.601handleDeadExits();602foldTerminators();603604if (!DeadLoopBlocks.empty()) {605LLVM_DEBUG(dbgs() << "Deleting " << DeadLoopBlocks.size()606<< " dead blocks in loop " << Header->getName() << "\n");607deleteDeadLoopBlocks();608} else {609// If we didn't do updates inside deleteDeadLoopBlocks, do them here.610DTU.applyUpdates(DTUpdates);611DTUpdates.clear();612}613614if (MSSAU && VerifyMemorySSA)615MSSAU->getMemorySSA()->verifyMemorySSA();616617#ifndef NDEBUG618// Make sure that we have preserved all data structures after the transform.619#if defined(EXPENSIVE_CHECKS)620assert(DT.verify(DominatorTree::VerificationLevel::Full) &&621"DT broken after transform!");622#else623assert(DT.verify(DominatorTree::VerificationLevel::Fast) &&624"DT broken after transform!");625#endif626assert(DT.isReachableFromEntry(Header));627LI.verify(DT);628#endif629630return true;631}632633bool foldingBreaksCurrentLoop() const {634return DeleteCurrentLoop;635}636};637} // namespace638639/// Turn branches and switches with known constant conditions into unconditional640/// branches.641static bool constantFoldTerminators(Loop &L, DominatorTree &DT, LoopInfo &LI,642ScalarEvolution &SE,643MemorySSAUpdater *MSSAU,644bool &IsLoopDeleted) {645if (!EnableTermFolding)646return false;647648// To keep things simple, only process loops with single latch. We649// canonicalize most loops to this form. We can support multi-latch if needed.650if (!L.getLoopLatch())651return false;652653ConstantTerminatorFoldingImpl BranchFolder(L, LI, DT, SE, MSSAU);654bool Changed = BranchFolder.run();655IsLoopDeleted = Changed && BranchFolder.foldingBreaksCurrentLoop();656return Changed;657}658659static bool mergeBlocksIntoPredecessors(Loop &L, DominatorTree &DT,660LoopInfo &LI, MemorySSAUpdater *MSSAU,661ScalarEvolution &SE) {662bool Changed = false;663DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);664// Copy blocks into a temporary array to avoid iterator invalidation issues665// as we remove them.666SmallVector<WeakTrackingVH, 16> Blocks(L.blocks());667668for (auto &Block : Blocks) {669// Attempt to merge blocks in the trivial case. Don't modify blocks which670// belong to other loops.671BasicBlock *Succ = cast_or_null<BasicBlock>(Block);672if (!Succ)673continue;674675BasicBlock *Pred = Succ->getSinglePredecessor();676if (!Pred || !Pred->getSingleSuccessor() || LI.getLoopFor(Pred) != &L)677continue;678679// Merge Succ into Pred and delete it.680MergeBlockIntoPredecessor(Succ, &DTU, &LI, MSSAU);681682if (MSSAU && VerifyMemorySSA)683MSSAU->getMemorySSA()->verifyMemorySSA();684685Changed = true;686}687688if (Changed)689SE.forgetBlockAndLoopDispositions();690691return Changed;692}693694static bool simplifyLoopCFG(Loop &L, DominatorTree &DT, LoopInfo &LI,695ScalarEvolution &SE, MemorySSAUpdater *MSSAU,696bool &IsLoopDeleted) {697bool Changed = false;698699// Constant-fold terminators with known constant conditions.700Changed |= constantFoldTerminators(L, DT, LI, SE, MSSAU, IsLoopDeleted);701702if (IsLoopDeleted)703return true;704705// Eliminate unconditional branches by merging blocks into their predecessors.706Changed |= mergeBlocksIntoPredecessors(L, DT, LI, MSSAU, SE);707708if (Changed)709SE.forgetTopmostLoop(&L);710711return Changed;712}713714PreservedAnalyses LoopSimplifyCFGPass::run(Loop &L, LoopAnalysisManager &AM,715LoopStandardAnalysisResults &AR,716LPMUpdater &LPMU) {717std::optional<MemorySSAUpdater> MSSAU;718if (AR.MSSA)719MSSAU = MemorySSAUpdater(AR.MSSA);720bool DeleteCurrentLoop = false;721if (!simplifyLoopCFG(L, AR.DT, AR.LI, AR.SE, MSSAU ? &*MSSAU : nullptr,722DeleteCurrentLoop))723return PreservedAnalyses::all();724725if (DeleteCurrentLoop)726LPMU.markLoopAsDeleted(L, "loop-simplifycfg");727728auto PA = getLoopPassPreservedAnalyses();729if (AR.MSSA)730PA.preserve<MemorySSAAnalysis>();731return PA;732}733734735