43 #define DEBUG_TYPE "loop-simplifycfg" 49 "Number of terminators folded to unconditional branches");
51 "Number of loop blocks deleted");
53 "Number of loop exiting edges deleted");
60 if (
BranchInst *BI = dyn_cast<BranchInst>(TI)) {
61 if (BI->isUnconditional())
63 if (BI->getSuccessor(0) == BI->getSuccessor(1))
68 return Cond->
isZero() ? BI->getSuccessor(1) : BI->getSuccessor(0);
75 for (
auto Case :
SI->cases())
76 if (Case.getCaseValue() == CI)
77 return Case.getCaseSuccessor();
78 return SI->getDefaultDest();
86 Loop *LastLoop =
nullptr) {
88 "First loop is supposed to be inside of last loop!");
90 for (
Loop *Current = FirstLoop; Current != LastLoop;
92 Current->removeBlockFromLoop(BB);
99 Loop *Innermost =
nullptr;
117 class ConstantTerminatorFoldingImpl {
129 bool HasIrreducibleCFG =
false;
138 bool DeleteCurrentLoop =
false;
160 dbgs() <<
"Constant terminator folding for loop " << L <<
"\n";
161 dbgs() <<
"After terminator constant-folding, the loop will";
162 if (!DeleteCurrentLoop)
164 dbgs() <<
" be destroyed\n";
165 auto PrintOutVector = [&](
const char *Message,
167 dbgs() << Message <<
"\n";
169 dbgs() <<
"\t" << BB->getName() <<
"\n";
171 auto PrintOutSet = [&](
const char *Message,
173 dbgs() << Message <<
"\n";
175 dbgs() <<
"\t" << BB->getName() <<
"\n";
177 PrintOutVector(
"Blocks in which we can constant-fold terminator:",
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);
193 unsigned Current = 0;
222 if (hasIrreducibleCFG(DFS)) {
223 HasIrreducibleCFG =
true;
233 if (!LiveLoopBlocks.
count(BB)) {
244 bool TakeFoldCandidate = TheOnlySucc && LI.
getLoopFor(BB) == &L;
245 if (TakeFoldCandidate)
250 if (!TakeFoldCandidate || TheOnlySucc == Succ) {
252 LiveLoopBlocks.
insert(Succ);
254 LiveExitBlocks.
insert(Succ);
261 "Malformed block sets?");
267 for (
auto *ExitBlock : ExitBlocks)
268 if (!LiveExitBlocks.
count(ExitBlock) &&
269 UniqueDeadExits.
insert(ExitBlock).second)
275 if (!LiveLoopBlocks.
count(From))
278 return !TheOnlySucc || TheOnlySucc == To || LI.
getLoopFor(From) != &L;
286 if (DeleteCurrentLoop)
298 return BlocksInLoopAfterFolding.
count(Succ) && IsEdgeLive(BB, Succ);
303 if (BlockIsInLoop(BB))
304 BlocksInLoopAfterFolding.
insert(BB);
309 "Header not in loop?");
310 assert(BlocksInLoopAfterFolding.
size() <= LiveLoopBlocks.
size() &&
311 "All blocks that stay in loop should be live!");
349 void handleDeadExits() {
351 if (DeadExitBlocks.
empty())
362 Builder.CreateSwitch(Builder.getInt32(0), NewPreheader);
365 unsigned DummyIdx = 1;
368 for (
auto &PN : BB->phis())
374 PN->eraseFromParent();
376 assert(DummyIdx != 0 &&
"Too many dead exits!");
377 DummySwitch->addCase(Builder.getInt32(DummyIdx++), BB);
379 ++NumLoopExitsDeleted;
383 if (
Loop *OuterLoop = LI.getLoopFor(Preheader)) {
392 if (StillReachable != OuterLoop) {
393 LI.changeLoopFor(NewPreheader, StillReachable);
395 for (
auto *BB : L.
blocks())
397 OuterLoop->removeChildLoop(&L);
401 LI.addTopLevelLoop(&L);
406 Loop *FixLCSSALoop = OuterLoop;
409 assert(FixLCSSALoop &&
"Should be a loop!");
431 void deleteDeadLoopBlocks() {
434 DeadLoopBlocks.
end());
444 for (
auto *BB : DeadLoopBlocks)
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);
458 for (
auto *BB : DeadLoopBlocks) {
460 "Header of the current loop cannot be dead!");
469 for (
auto *BB : DeadLoopBlocks)
472 NumLoopBlocksDeleted += DeadLoopBlocks.size();
477 void foldTerminators() {
481 assert(TheOnlySucc &&
"Should have one live successor!");
484 <<
" with an unconditional branch to the block " 485 << TheOnlySucc->getName() <<
"\n");
489 unsigned TheOnlySuccDuplicates = 0;
491 if (Succ != TheOnlySucc) {
492 DeadSuccessors.
insert(Succ);
495 bool PreserveLCSSAPhi = !L.
contains(Succ);
496 Succ->removePredecessor(BB, PreserveLCSSAPhi);
500 ++TheOnlySuccDuplicates;
502 assert(TheOnlySuccDuplicates > 0 &&
"Should be!");
506 bool PreserveLCSSAPhi = !L.
contains(TheOnlySucc);
507 for (
unsigned Dup = 1; Dup < TheOnlySuccDuplicates; ++Dup)
508 TheOnlySucc->removePredecessor(BB, PreserveLCSSAPhi);
509 if (MSSAU && TheOnlySuccDuplicates > 1)
514 Builder.SetInsertPoint(Term);
515 Builder.CreateBr(TheOnlySucc);
516 Term->eraseFromParent();
518 for (
auto *DeadSucc : DeadSuccessors)
521 ++NumTerminatorsFolded;
529 : L(L), LI(LI), DT(DT), SE(SE), MSSAU(MSSAU),
DFS(&L),
543 if (HasIrreducibleCFG) {
544 LLVM_DEBUG(
dbgs() <<
"Loops with irreducible CFG are not supported!\n");
549 if (FoldCandidates.
empty()) {
551 dbgs() <<
"No constant terminator folding candidates found in loop " 557 if (DeleteCurrentLoop) {
560 <<
"Give up constant terminator folding in loop " << Header->
getName()
561 <<
": we don't currently support deletion of the current loop.\n");
567 if (BlocksInLoopAfterFolding.
size() + DeadLoopBlocks.
size() !=
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");
582 <<
" terminators in loop " << Header->
getName() <<
"\n");
588 if (!DeadLoopBlocks.
empty()) {
590 <<
" dead blocks in loop " << Header->
getName() <<
"\n");
591 deleteDeadLoopBlocks();
603 #if defined(EXPENSIVE_CHECKS) 605 "DT broken after transform!");
608 "DT broken after transform!");
617 bool foldingBreaksCurrentLoop()
const {
618 return DeleteCurrentLoop;
628 bool &IsLoopDeleted) {
637 ConstantTerminatorFoldingImpl
BranchFolder(L, LI, DT, SE, MSSAU);
638 bool Changed = BranchFolder.run();
639 IsLoopDeleted = Changed && BranchFolder.foldingBreaksCurrentLoop();
645 bool Changed =
false;
651 for (
auto &Block : Blocks) {
654 BasicBlock *Succ = cast_or_null<BasicBlock>(Block);
676 bool &isLoopDeleted) {
677 bool Changed =
false;
700 bool DeleteCurrentLoop =
false;
706 if (DeleteCurrentLoop)
716 class LoopSimplifyCFGLegacyPass :
public LoopPass {
719 LoopSimplifyCFGLegacyPass() :
LoopPass(ID) {
727 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
728 LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
729 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
732 MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
737 bool DeleteCurrentLoop =
false;
741 if (DeleteCurrentLoop)
759 "Simplify loop CFG",
false,
false)
766 return new LoopSimplifyCFGLegacyPass();
Pass interface - Implemented by all 'passes'.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
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.
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.
This class represents lattice values for constants.
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.
void push_back(const T &Elt)
The main scalar evolution driver.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
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...
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.
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
void verify(const DominatorTreeBase< BlockT, false > &DomTree) const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
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.
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)
Legacy analysis pass which computes MemorySSA.
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.
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
static constexpr UpdateKind Delete
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Encapsulates MemorySSA, including all data associated with memory accesses.
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.
RPOIterator endRPO() const
BlockT * getHeader() const
void getExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all of the successor blocks of this loop.
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
void perform(LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
static cl::opt< bool > EnableTermFolding("enable-loop-simplifycfg-term-folding", cl::init(true))
initializer< Ty > init(const Ty &Val)
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
A set of analyses that are preserved following a run of a transformation pass.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
static constexpr UpdateKind Insert
LLVM Basic Block Representation.
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.
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...
const T * getPointer() const
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
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
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.
A SetVector that performs no allocations if smaller than a certain size.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
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 ...
An analysis that produces MemorySSA for a function.
Pass * createLoopSimplifyCFGPass()
void markLoopAsDeleted(Loop &L)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Store the result of a depth first search within basic blocks contained by a single loop...
bool isLoopHeader(const BlockT *BB) const
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
LoopT * getParentLoop() const
unsigned getNumBlocks() const
Get the number of blocks in this loop in constant time.
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
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
Represents a single loop in the control flow graph.
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
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.
rpo Deduce function attributes in RPO
succ_range successors(Instruction *I)
RPOIterator beginRPO() const
Reverse iterate over the cached postorder blocks.
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's primary stateless and local alias analysis.
A container for analyses that lazily runs them and caches their results.
iterator_range< block_iterator > blocks() const
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...
void forgetTopmostLoop(const Loop *L)