2016-01-29 23:35:36 +01:00
|
|
|
//===--------- LoopSimplifyCFG.cpp - Loop CFG Simplification Pass ---------===//
|
|
|
|
//
|
2019-01-19 09:50:56 +01:00
|
|
|
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
|
|
|
|
// See https://llvm.org/LICENSE.txt for license information.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
2016-01-29 23:35:36 +01:00
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
//
|
|
|
|
// This file implements the Loop SimplifyCFG Pass. This pass is responsible for
|
|
|
|
// basic loop CFG cleanup, primarily to assist other loop passes. If you
|
|
|
|
// encounter a noncanonical CFG construct that causes another loop pass to
|
|
|
|
// perform suboptimally, this is the place to fix it up.
|
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2016-05-03 23:47:32 +02:00
|
|
|
#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
|
2016-01-29 23:35:36 +01:00
|
|
|
#include "llvm/ADT/SmallVector.h"
|
|
|
|
#include "llvm/ADT/Statistic.h"
|
2016-12-19 09:22:17 +01:00
|
|
|
#include "llvm/Analysis/AssumptionCache.h"
|
2017-01-11 10:43:56 +01:00
|
|
|
#include "llvm/Analysis/BasicAliasAnalysis.h"
|
2016-01-29 23:35:36 +01:00
|
|
|
#include "llvm/Analysis/DependenceAnalysis.h"
|
2019-02-06 03:52:52 +01:00
|
|
|
#include "llvm/Analysis/DomTreeUpdater.h"
|
2016-01-29 23:35:36 +01:00
|
|
|
#include "llvm/Analysis/GlobalsModRef.h"
|
|
|
|
#include "llvm/Analysis/LoopInfo.h"
|
2020-06-05 11:45:42 +02:00
|
|
|
#include "llvm/Analysis/LoopIterator.h"
|
2016-01-29 23:35:36 +01:00
|
|
|
#include "llvm/Analysis/LoopPass.h"
|
2018-08-22 22:10:21 +02:00
|
|
|
#include "llvm/Analysis/MemorySSA.h"
|
|
|
|
#include "llvm/Analysis/MemorySSAUpdater.h"
|
2016-01-29 23:35:36 +01:00
|
|
|
#include "llvm/Analysis/ScalarEvolution.h"
|
|
|
|
#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
|
|
|
|
#include "llvm/Analysis/TargetTransformInfo.h"
|
|
|
|
#include "llvm/IR/Dominators.h"
|
2020-04-04 12:02:21 +02:00
|
|
|
#include "llvm/IR/IRBuilder.h"
|
Sink all InitializePasses.h includes
This file lists every pass in LLVM, and is included by Pass.h, which is
very popular. Every time we add, remove, or rename a pass in LLVM, it
caused lots of recompilation.
I found this fact by looking at this table, which is sorted by the
number of times a file was changed over the last 100,000 git commits
multiplied by the number of object files that depend on it in the
current checkout:
recompiles touches affected_files header
342380 95 3604 llvm/include/llvm/ADT/STLExtras.h
314730 234 1345 llvm/include/llvm/InitializePasses.h
307036 118 2602 llvm/include/llvm/ADT/APInt.h
213049 59 3611 llvm/include/llvm/Support/MathExtras.h
170422 47 3626 llvm/include/llvm/Support/Compiler.h
162225 45 3605 llvm/include/llvm/ADT/Optional.h
158319 63 2513 llvm/include/llvm/ADT/Triple.h
140322 39 3598 llvm/include/llvm/ADT/StringRef.h
137647 59 2333 llvm/include/llvm/Support/Error.h
131619 73 1803 llvm/include/llvm/Support/FileSystem.h
Before this change, touching InitializePasses.h would cause 1345 files
to recompile. After this change, touching it only causes 550 compiles in
an incremental rebuild.
Reviewers: bkramer, asbirlea, bollu, jdoerfert
Differential Revision: https://reviews.llvm.org/D70211
2019-11-13 22:15:01 +01:00
|
|
|
#include "llvm/InitializePasses.h"
|
2019-11-15 00:15:48 +01:00
|
|
|
#include "llvm/Support/CommandLine.h"
|
2016-05-03 23:47:32 +02:00
|
|
|
#include "llvm/Transforms/Scalar.h"
|
2017-01-11 10:43:56 +01:00
|
|
|
#include "llvm/Transforms/Scalar/LoopPassManager.h"
|
2018-03-28 19:44:36 +02:00
|
|
|
#include "llvm/Transforms/Utils.h"
|
Generalize MergeBlockIntoPredecessor. Replace uses of MergeBasicBlockIntoOnlyPred.
Summary:
Two utils methods have essentially the same functionality. This is an attempt to merge them into one.
1. lib/Transforms/Utils/Local.cpp : MergeBasicBlockIntoOnlyPred
2. lib/Transforms/Utils/BasicBlockUtils.cpp : MergeBlockIntoPredecessor
Prior to the patch:
1. MergeBasicBlockIntoOnlyPred
Updates either DomTree or DeferredDominance
Moves all instructions from Pred to BB, deletes Pred
Asserts BB has single predecessor
If address was taken, replace the block address with constant 1 (?)
2. MergeBlockIntoPredecessor
Updates DomTree, LoopInfo and MemoryDependenceResults
Moves all instruction from BB to Pred, deletes BB
Returns if doesn't have a single predecessor
Returns if BB's address was taken
After the patch:
Method 2. MergeBlockIntoPredecessor is attempting to become the new default:
Updates DomTree or DeferredDominance, and LoopInfo and MemoryDependenceResults
Moves all instruction from BB to Pred, deletes BB
Returns if doesn't have a single predecessor
Returns if BB's address was taken
Uses of MergeBasicBlockIntoOnlyPred that need to be replaced:
1. lib/Transforms/Scalar/LoopSimplifyCFG.cpp
Updated in this patch. No challenges.
2. lib/CodeGen/CodeGenPrepare.cpp
Updated in this patch.
i. eliminateFallThrough is straightforward, but I added using a temporary array to avoid the iterator invalidation.
ii. eliminateMostlyEmptyBlock(s) methods also now use a temporary array for blocks
Some interesting aspects:
- Since Pred is not deleted (BB is), the entry block does not need updating.
- The entry block was being updated with the deleted block in eliminateMostlyEmptyBlock. Added assert to make obvious that BB=SinglePred.
- isMergingEmptyBlockProfitable assumes BB is the one to be deleted.
- eliminateMostlyEmptyBlock(BB) does not delete BB on one path, it deletes its unique predecessor instead.
- adding some test owner as subscribers for the interesting tests modified:
test/CodeGen/X86/avx-cmp.ll
test/CodeGen/AMDGPU/nested-loop-conditions.ll
test/CodeGen/AMDGPU/si-annotate-cf.ll
test/CodeGen/X86/hoist-spill.ll
test/CodeGen/X86/2006-11-17-IllegalMove.ll
3. lib/Transforms/Scalar/JumpThreading.cpp
Not covered in this patch. It is the only use case using the DeferredDominance.
I would defer to Brian Rzycki to make this replacement.
Reviewers: chandlerc, spatel, davide, brzycki, bkramer, javed.absar
Subscribers: qcolombet, sanjoy, nemanjai, nhaehnle, jlebar, tpr, kbarton, RKSimon, wmi, arsenm, llvm-commits
Differential Revision: https://reviews.llvm.org/D48202
llvm-svn: 335183
2018-06-21 00:01:04 +02:00
|
|
|
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
|
|
|
|
#include "llvm/Transforms/Utils/Local.h"
|
[LPM] Factor all of the loop analysis usage updates into a common helper
routine.
We were getting this wrong in small ways and generally being very
inconsistent about it across loop passes. Instead, let's have a common
place where we do this. One minor downside is that this will require
some analyses like SCEV in more places than they are strictly needed.
However, this seems benign as these analyses are complete no-ops, and
without this consistency we can in many cases end up with the legacy
pass manager scheduling deciding to split up a loop pass pipeline in
order to run the function analysis half-way through. It is very, very
annoying to fix these without just being very pedantic across the board.
The only loop passes I've not updated here are ones that use
AU.setPreservesAll() such as IVUsers (an analysis) and the pass printer.
They seemed less relevant.
With this patch, almost all of the problems in PR24804 around loop pass
pipelines are fixed. The one remaining issue is that we run simplify-cfg
and instcombine in the middle of the loop pass pipeline. We've recently
added some loop variants of these passes that would seem substantially
cleaner to use, but this at least gets us much closer to the previous
state. Notably, the seven loop pass managers is down to three.
I've not updated the loop passes using LoopAccessAnalysis because that
analysis hasn't been fully wired into LoopSimplify/LCSSA, and it isn't
clear that those transforms want to support those forms anyways. They
all run late anyways, so this is harmless. Similarly, LSR is left alone
because it already carefully manages its forms and doesn't need to get
fused into a single loop pass manager with a bunch of other loop passes.
LoopReroll didn't use loop simplified form previously, and I've updated
the test case to match the trivially different output.
Finally, I've also factored all the pass initialization for the passes
that use this technique as well, so that should be done regularly and
reliably.
Thanks to James for the help reviewing and thinking about this stuff,
and Ben for help thinking about it as well!
Differential Revision: http://reviews.llvm.org/D17435
llvm-svn: 261316
2016-02-19 11:45:18 +01:00
|
|
|
#include "llvm/Transforms/Utils/LoopUtils.h"
|
2016-01-29 23:35:36 +01:00
|
|
|
using namespace llvm;
|
|
|
|
|
|
|
|
#define DEBUG_TYPE "loop-simplifycfg"
|
|
|
|
|
2018-11-23 10:14:53 +01:00
|
|
|
static cl::opt<bool> EnableTermFolding("enable-loop-simplifycfg-term-folding",
|
2019-02-13 07:12:48 +01:00
|
|
|
cl::init(true));
|
2018-11-23 10:14:53 +01:00
|
|
|
|
2018-11-20 06:43:32 +01:00
|
|
|
STATISTIC(NumTerminatorsFolded,
|
|
|
|
"Number of terminators folded to unconditional branches");
|
2018-12-24 07:06:17 +01:00
|
|
|
STATISTIC(NumLoopBlocksDeleted,
|
|
|
|
"Number of loop blocks deleted");
|
2018-12-24 08:41:33 +01:00
|
|
|
STATISTIC(NumLoopExitsDeleted,
|
|
|
|
"Number of loop exiting edges deleted");
|
2018-11-20 06:43:32 +01:00
|
|
|
|
|
|
|
/// If \p BB is a switch or a conditional branch, but only one of its successors
|
|
|
|
/// can be reached from this block in runtime, return this successor. Otherwise,
|
|
|
|
/// return nullptr.
|
|
|
|
static BasicBlock *getOnlyLiveSuccessor(BasicBlock *BB) {
|
|
|
|
Instruction *TI = BB->getTerminator();
|
|
|
|
if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
|
|
|
|
if (BI->isUnconditional())
|
|
|
|
return nullptr;
|
|
|
|
if (BI->getSuccessor(0) == BI->getSuccessor(1))
|
|
|
|
return BI->getSuccessor(0);
|
|
|
|
ConstantInt *Cond = dyn_cast<ConstantInt>(BI->getCondition());
|
|
|
|
if (!Cond)
|
|
|
|
return nullptr;
|
|
|
|
return Cond->isZero() ? BI->getSuccessor(1) : BI->getSuccessor(0);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
|
|
|
|
auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
|
|
|
|
if (!CI)
|
|
|
|
return nullptr;
|
|
|
|
for (auto Case : SI->cases())
|
|
|
|
if (Case.getCaseValue() == CI)
|
|
|
|
return Case.getCaseSuccessor();
|
|
|
|
return SI->getDefaultDest();
|
|
|
|
}
|
|
|
|
|
|
|
|
return nullptr;
|
|
|
|
}
|
|
|
|
|
2019-02-15 13:18:10 +01:00
|
|
|
/// Removes \p BB from all loops from [FirstLoop, LastLoop) in parent chain.
|
|
|
|
static void removeBlockFromLoops(BasicBlock *BB, Loop *FirstLoop,
|
|
|
|
Loop *LastLoop = nullptr) {
|
|
|
|
assert((!LastLoop || LastLoop->contains(FirstLoop->getHeader())) &&
|
|
|
|
"First loop is supposed to be inside of last loop!");
|
|
|
|
assert(FirstLoop->contains(BB) && "Must be a loop block!");
|
|
|
|
for (Loop *Current = FirstLoop; Current != LastLoop;
|
|
|
|
Current = Current->getParentLoop())
|
|
|
|
Current->removeBlockFromLoop(BB);
|
|
|
|
}
|
|
|
|
|
2019-02-17 16:22:48 +01:00
|
|
|
/// Find innermost loop that contains at least one block from \p BBs and
|
|
|
|
/// contains the header of loop \p L.
|
|
|
|
static Loop *getInnermostLoopFor(SmallPtrSetImpl<BasicBlock *> &BBs,
|
|
|
|
Loop &L, LoopInfo &LI) {
|
2019-02-17 19:21:51 +01:00
|
|
|
Loop *Innermost = nullptr;
|
2019-02-17 16:04:09 +01:00
|
|
|
for (BasicBlock *BB : BBs) {
|
|
|
|
Loop *BBL = LI.getLoopFor(BB);
|
2019-02-17 19:21:51 +01:00
|
|
|
while (BBL && !BBL->contains(L.getHeader()))
|
|
|
|
BBL = BBL->getParentLoop();
|
|
|
|
if (BBL == &L)
|
|
|
|
BBL = BBL->getParentLoop();
|
|
|
|
if (!BBL)
|
|
|
|
continue;
|
|
|
|
if (!Innermost || BBL->getLoopDepth() > Innermost->getLoopDepth())
|
|
|
|
Innermost = BBL;
|
2019-02-17 16:04:09 +01:00
|
|
|
}
|
2019-02-17 19:21:51 +01:00
|
|
|
return Innermost;
|
2019-02-17 16:04:09 +01:00
|
|
|
}
|
|
|
|
|
2019-01-12 19:36:22 +01:00
|
|
|
namespace {
|
2018-11-20 06:43:32 +01:00
|
|
|
/// Helper class that can turn branches and switches with constant conditions
|
|
|
|
/// into unconditional branches.
|
|
|
|
class ConstantTerminatorFoldingImpl {
|
|
|
|
private:
|
|
|
|
Loop &L;
|
|
|
|
LoopInfo &LI;
|
|
|
|
DominatorTree &DT;
|
2018-12-29 05:26:22 +01:00
|
|
|
ScalarEvolution &SE;
|
2018-11-30 11:06:23 +01:00
|
|
|
MemorySSAUpdater *MSSAU;
|
2019-02-15 12:39:35 +01:00
|
|
|
LoopBlocksDFS DFS;
|
2019-02-15 13:13:16 +01:00
|
|
|
DomTreeUpdater DTU;
|
2019-02-08 09:12:41 +01:00
|
|
|
SmallVector<DominatorTree::UpdateType, 16> DTUpdates;
|
2018-11-20 06:43:32 +01:00
|
|
|
|
2018-12-07 06:44:45 +01:00
|
|
|
// Whether or not the current loop has irreducible CFG.
|
|
|
|
bool HasIrreducibleCFG = false;
|
2018-11-20 06:43:32 +01:00
|
|
|
// Whether or not the current loop will still exist after terminator constant
|
|
|
|
// folding will be done. In theory, there are two ways how it can happen:
|
|
|
|
// 1. Loop's latch(es) become unreachable from loop header;
|
|
|
|
// 2. Loop's header becomes unreachable from method entry.
|
|
|
|
// In practice, the second situation is impossible because we only modify the
|
|
|
|
// current loop and its preheader and do not affect preheader's reachibility
|
|
|
|
// from any other block. So this variable set to true means that loop's latch
|
|
|
|
// has become unreachable from loop header.
|
|
|
|
bool DeleteCurrentLoop = false;
|
|
|
|
|
|
|
|
// The blocks of the original loop that will still be reachable from entry
|
|
|
|
// after the constant folding.
|
|
|
|
SmallPtrSet<BasicBlock *, 8> LiveLoopBlocks;
|
|
|
|
// The blocks of the original loop that will become unreachable from entry
|
|
|
|
// after the constant folding.
|
2018-12-28 07:08:51 +01:00
|
|
|
SmallVector<BasicBlock *, 8> DeadLoopBlocks;
|
2018-11-20 06:43:32 +01:00
|
|
|
// The exits of the original loop that will still be reachable from entry
|
|
|
|
// after the constant folding.
|
|
|
|
SmallPtrSet<BasicBlock *, 8> LiveExitBlocks;
|
|
|
|
// The exits of the original loop that will become unreachable from entry
|
|
|
|
// after the constant folding.
|
2018-11-22 13:33:41 +01:00
|
|
|
SmallVector<BasicBlock *, 8> DeadExitBlocks;
|
2018-11-20 06:43:32 +01:00
|
|
|
// The blocks that will still be a part of the current loop after folding.
|
|
|
|
SmallPtrSet<BasicBlock *, 8> BlocksInLoopAfterFolding;
|
|
|
|
// The blocks that have terminators with constant condition that can be
|
|
|
|
// folded. Note: fold candidates should be in L but not in any of its
|
|
|
|
// subloops to avoid complex LI updates.
|
|
|
|
SmallVector<BasicBlock *, 8> FoldCandidates;
|
|
|
|
|
|
|
|
void dump() const {
|
|
|
|
dbgs() << "Constant terminator folding for loop " << L << "\n";
|
|
|
|
dbgs() << "After terminator constant-folding, the loop will";
|
|
|
|
if (!DeleteCurrentLoop)
|
|
|
|
dbgs() << " not";
|
|
|
|
dbgs() << " be destroyed\n";
|
2018-11-22 13:33:41 +01:00
|
|
|
auto PrintOutVector = [&](const char *Message,
|
|
|
|
const SmallVectorImpl<BasicBlock *> &S) {
|
|
|
|
dbgs() << Message << "\n";
|
|
|
|
for (const BasicBlock *BB : S)
|
|
|
|
dbgs() << "\t" << BB->getName() << "\n";
|
|
|
|
};
|
2018-11-20 06:43:32 +01:00
|
|
|
auto PrintOutSet = [&](const char *Message,
|
|
|
|
const SmallPtrSetImpl<BasicBlock *> &S) {
|
|
|
|
dbgs() << Message << "\n";
|
|
|
|
for (const BasicBlock *BB : S)
|
|
|
|
dbgs() << "\t" << BB->getName() << "\n";
|
|
|
|
};
|
2018-11-22 13:33:41 +01:00
|
|
|
PrintOutVector("Blocks in which we can constant-fold terminator:",
|
|
|
|
FoldCandidates);
|
2018-11-20 06:43:32 +01:00
|
|
|
PrintOutSet("Live blocks from the original loop:", LiveLoopBlocks);
|
2018-12-28 07:08:51 +01:00
|
|
|
PrintOutVector("Dead blocks from the original loop:", DeadLoopBlocks);
|
2018-11-20 06:43:32 +01:00
|
|
|
PrintOutSet("Live exit blocks:", LiveExitBlocks);
|
2018-11-22 13:33:41 +01:00
|
|
|
PrintOutVector("Dead exit blocks:", DeadExitBlocks);
|
2018-11-20 06:43:32 +01:00
|
|
|
if (!DeleteCurrentLoop)
|
|
|
|
PrintOutSet("The following blocks will still be part of the loop:",
|
|
|
|
BlocksInLoopAfterFolding);
|
|
|
|
}
|
|
|
|
|
2018-12-07 06:44:45 +01:00
|
|
|
/// Whether or not the current loop has irreducible CFG.
|
|
|
|
bool hasIrreducibleCFG(LoopBlocksDFS &DFS) {
|
|
|
|
assert(DFS.isComplete() && "DFS is expected to be finished");
|
|
|
|
// Index of a basic block in RPO traversal.
|
|
|
|
DenseMap<const BasicBlock *, unsigned> RPO;
|
|
|
|
unsigned Current = 0;
|
|
|
|
for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I)
|
|
|
|
RPO[*I] = Current++;
|
|
|
|
|
|
|
|
for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {
|
|
|
|
BasicBlock *BB = *I;
|
|
|
|
for (auto *Succ : successors(BB))
|
|
|
|
if (L.contains(Succ) && !LI.isLoopHeader(Succ) && RPO[BB] > RPO[Succ])
|
|
|
|
// If an edge goes from a block with greater order number into a block
|
|
|
|
// with lesses number, and it is not a loop backedge, then it can only
|
|
|
|
// be a part of irreducible non-loop cycle.
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2018-11-20 06:43:32 +01:00
|
|
|
/// Fill all information about status of blocks and exits of the current loop
|
|
|
|
/// if constant folding of all branches will be done.
|
|
|
|
void analyze() {
|
|
|
|
DFS.perform(&LI);
|
|
|
|
assert(DFS.isComplete() && "DFS is expected to be finished");
|
|
|
|
|
2018-12-07 06:44:45 +01:00
|
|
|
// TODO: The algorithm below relies on both RPO and Postorder traversals.
|
|
|
|
// When the loop has only reducible CFG inside, then the invariant "all
|
|
|
|
// predecessors of X are processed before X in RPO" is preserved. However
|
|
|
|
// an irreducible loop can break this invariant (e.g. latch does not have to
|
|
|
|
// be the last block in the traversal in this case, and the algorithm relies
|
|
|
|
// on this). We can later decide to support such cases by altering the
|
|
|
|
// algorithms, but so far we just give up analyzing them.
|
|
|
|
if (hasIrreducibleCFG(DFS)) {
|
|
|
|
HasIrreducibleCFG = true;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2018-11-20 06:43:32 +01:00
|
|
|
// Collect live and dead loop blocks and exits.
|
|
|
|
LiveLoopBlocks.insert(L.getHeader());
|
|
|
|
for (auto I = DFS.beginRPO(), E = DFS.endRPO(); I != E; ++I) {
|
|
|
|
BasicBlock *BB = *I;
|
|
|
|
|
|
|
|
// If a loop block wasn't marked as live so far, then it's dead.
|
|
|
|
if (!LiveLoopBlocks.count(BB)) {
|
2018-12-28 07:08:51 +01:00
|
|
|
DeadLoopBlocks.push_back(BB);
|
2018-11-20 06:43:32 +01:00
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
|
|
|
|
|
|
|
|
// If a block has only one live successor, it's a candidate on constant
|
|
|
|
// folding. Only handle blocks from current loop: branches in child loops
|
|
|
|
// are skipped because if they can be folded, they should be folded during
|
|
|
|
// the processing of child loops.
|
2019-01-24 06:20:29 +01:00
|
|
|
bool TakeFoldCandidate = TheOnlySucc && LI.getLoopFor(BB) == &L;
|
|
|
|
if (TakeFoldCandidate)
|
2018-11-20 06:43:32 +01:00
|
|
|
FoldCandidates.push_back(BB);
|
|
|
|
|
|
|
|
// Handle successors.
|
|
|
|
for (BasicBlock *Succ : successors(BB))
|
2019-01-24 06:20:29 +01:00
|
|
|
if (!TakeFoldCandidate || TheOnlySucc == Succ) {
|
2018-11-22 11:48:30 +01:00
|
|
|
if (L.contains(Succ))
|
|
|
|
LiveLoopBlocks.insert(Succ);
|
|
|
|
else
|
|
|
|
LiveExitBlocks.insert(Succ);
|
|
|
|
}
|
2018-11-20 06:43:32 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Sanity check: amount of dead and live loop blocks should match the total
|
|
|
|
// number of blocks in loop.
|
|
|
|
assert(L.getNumBlocks() == LiveLoopBlocks.size() + DeadLoopBlocks.size() &&
|
|
|
|
"Malformed block sets?");
|
|
|
|
|
|
|
|
// Now, all exit blocks that are not marked as live are dead.
|
2018-11-22 11:48:30 +01:00
|
|
|
SmallVector<BasicBlock *, 8> ExitBlocks;
|
|
|
|
L.getExitBlocks(ExitBlocks);
|
2019-02-06 08:49:17 +01:00
|
|
|
SmallPtrSet<BasicBlock *, 8> UniqueDeadExits;
|
2018-11-20 06:43:32 +01:00
|
|
|
for (auto *ExitBlock : ExitBlocks)
|
2019-02-06 08:49:17 +01:00
|
|
|
if (!LiveExitBlocks.count(ExitBlock) &&
|
|
|
|
UniqueDeadExits.insert(ExitBlock).second)
|
2018-11-22 13:33:41 +01:00
|
|
|
DeadExitBlocks.push_back(ExitBlock);
|
2018-11-20 06:43:32 +01:00
|
|
|
|
|
|
|
// Whether or not the edge From->To will still be present in graph after the
|
|
|
|
// folding.
|
|
|
|
auto IsEdgeLive = [&](BasicBlock *From, BasicBlock *To) {
|
|
|
|
if (!LiveLoopBlocks.count(From))
|
|
|
|
return false;
|
|
|
|
BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(From);
|
2019-01-25 06:05:02 +01:00
|
|
|
return !TheOnlySucc || TheOnlySucc == To || LI.getLoopFor(From) != &L;
|
2018-11-20 06:43:32 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
// The loop will not be destroyed if its latch is live.
|
|
|
|
DeleteCurrentLoop = !IsEdgeLive(L.getLoopLatch(), L.getHeader());
|
|
|
|
|
|
|
|
// If we are going to delete the current loop completely, no extra analysis
|
|
|
|
// is needed.
|
|
|
|
if (DeleteCurrentLoop)
|
|
|
|
return;
|
|
|
|
|
|
|
|
// Otherwise, we should check which blocks will still be a part of the
|
|
|
|
// current loop after the transform.
|
|
|
|
BlocksInLoopAfterFolding.insert(L.getLoopLatch());
|
|
|
|
// If the loop is live, then we should compute what blocks are still in
|
|
|
|
// loop after all branch folding has been done. A block is in loop if
|
|
|
|
// it has a live edge to another block that is in the loop; by definition,
|
|
|
|
// latch is in the loop.
|
|
|
|
auto BlockIsInLoop = [&](BasicBlock *BB) {
|
|
|
|
return any_of(successors(BB), [&](BasicBlock *Succ) {
|
|
|
|
return BlocksInLoopAfterFolding.count(Succ) && IsEdgeLive(BB, Succ);
|
|
|
|
});
|
|
|
|
};
|
|
|
|
for (auto I = DFS.beginPostorder(), E = DFS.endPostorder(); I != E; ++I) {
|
|
|
|
BasicBlock *BB = *I;
|
|
|
|
if (BlockIsInLoop(BB))
|
|
|
|
BlocksInLoopAfterFolding.insert(BB);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Sanity check: header must be in loop.
|
|
|
|
assert(BlocksInLoopAfterFolding.count(L.getHeader()) &&
|
|
|
|
"Header not in loop?");
|
2018-11-22 13:43:27 +01:00
|
|
|
assert(BlocksInLoopAfterFolding.size() <= LiveLoopBlocks.size() &&
|
|
|
|
"All blocks that stay in loop should be live!");
|
2018-11-20 06:43:32 +01:00
|
|
|
}
|
|
|
|
|
2018-12-24 08:41:33 +01:00
|
|
|
/// We need to preserve static reachibility of all loop exit blocks (this is)
|
|
|
|
/// required by loop pass manager. In order to do it, we make the following
|
|
|
|
/// trick:
|
|
|
|
///
|
|
|
|
/// preheader:
|
|
|
|
/// <preheader code>
|
|
|
|
/// br label %loop_header
|
|
|
|
///
|
|
|
|
/// loop_header:
|
|
|
|
/// ...
|
|
|
|
/// br i1 false, label %dead_exit, label %loop_block
|
|
|
|
/// ...
|
|
|
|
///
|
|
|
|
/// We cannot simply remove edge from the loop to dead exit because in this
|
|
|
|
/// case dead_exit (and its successors) may become unreachable. To avoid that,
|
|
|
|
/// we insert the following fictive preheader:
|
|
|
|
///
|
|
|
|
/// preheader:
|
|
|
|
/// <preheader code>
|
|
|
|
/// switch i32 0, label %preheader-split,
|
|
|
|
/// [i32 1, label %dead_exit_1],
|
|
|
|
/// [i32 2, label %dead_exit_2],
|
|
|
|
/// ...
|
|
|
|
/// [i32 N, label %dead_exit_N],
|
|
|
|
///
|
|
|
|
/// preheader-split:
|
|
|
|
/// br label %loop_header
|
|
|
|
///
|
|
|
|
/// loop_header:
|
|
|
|
/// ...
|
|
|
|
/// br i1 false, label %dead_exit_N, label %loop_block
|
|
|
|
/// ...
|
|
|
|
///
|
|
|
|
/// Doing so, we preserve static reachibility of all dead exits and can later
|
|
|
|
/// remove edges from the loop to these blocks.
|
|
|
|
void handleDeadExits() {
|
|
|
|
// If no dead exits, nothing to do.
|
|
|
|
if (DeadExitBlocks.empty())
|
|
|
|
return;
|
|
|
|
|
|
|
|
// Construct split preheader and the dummy switch to thread edges from it to
|
|
|
|
// dead exits.
|
|
|
|
BasicBlock *Preheader = L.getLoopPreheader();
|
2019-02-21 20:54:05 +01:00
|
|
|
BasicBlock *NewPreheader = llvm::SplitBlock(
|
|
|
|
Preheader, Preheader->getTerminator(), &DT, &LI, MSSAU);
|
|
|
|
|
2018-12-24 08:41:33 +01:00
|
|
|
IRBuilder<> Builder(Preheader->getTerminator());
|
|
|
|
SwitchInst *DummySwitch =
|
|
|
|
Builder.CreateSwitch(Builder.getInt32(0), NewPreheader);
|
|
|
|
Preheader->getTerminator()->eraseFromParent();
|
|
|
|
|
|
|
|
unsigned DummyIdx = 1;
|
|
|
|
for (BasicBlock *BB : DeadExitBlocks) {
|
2020-07-29 12:47:36 +02:00
|
|
|
// Eliminate all Phis and LandingPads from dead exits.
|
|
|
|
// TODO: Consider removing all instructions in this dead block.
|
|
|
|
SmallVector<Instruction *, 4> DeadInstructions;
|
2018-12-24 08:41:33 +01:00
|
|
|
for (auto &PN : BB->phis())
|
2020-07-29 12:47:36 +02:00
|
|
|
DeadInstructions.push_back(&PN);
|
2018-12-24 08:41:33 +01:00
|
|
|
|
2020-07-29 12:47:36 +02:00
|
|
|
if (auto *LandingPad = dyn_cast<LandingPadInst>(BB->getFirstNonPHI()))
|
|
|
|
DeadInstructions.emplace_back(LandingPad);
|
|
|
|
|
|
|
|
for (Instruction *I : DeadInstructions) {
|
|
|
|
I->replaceAllUsesWith(UndefValue::get(I->getType()));
|
|
|
|
I->eraseFromParent();
|
2018-12-24 08:41:33 +01:00
|
|
|
}
|
2020-07-29 12:47:36 +02:00
|
|
|
|
2018-12-24 08:41:33 +01:00
|
|
|
assert(DummyIdx != 0 && "Too many dead exits!");
|
|
|
|
DummySwitch->addCase(Builder.getInt32(DummyIdx++), BB);
|
2019-02-08 09:12:41 +01:00
|
|
|
DTUpdates.push_back({DominatorTree::Insert, Preheader, BB});
|
2018-12-24 08:41:33 +01:00
|
|
|
++NumLoopExitsDeleted;
|
|
|
|
}
|
|
|
|
|
|
|
|
assert(L.getLoopPreheader() == NewPreheader && "Malformed CFG?");
|
|
|
|
if (Loop *OuterLoop = LI.getLoopFor(Preheader)) {
|
|
|
|
// When we break dead edges, the outer loop may become unreachable from
|
|
|
|
// the current loop. We need to fix loop info accordingly. For this, we
|
|
|
|
// find the most nested loop that still contains L and remove L from all
|
|
|
|
// loops that are inside of it.
|
2019-02-17 16:22:48 +01:00
|
|
|
Loop *StillReachable = getInnermostLoopFor(LiveExitBlocks, L, LI);
|
2018-12-24 08:41:33 +01:00
|
|
|
|
|
|
|
// Okay, our loop is no longer in the outer loop (and maybe not in some of
|
|
|
|
// its parents as well). Make the fixup.
|
|
|
|
if (StillReachable != OuterLoop) {
|
|
|
|
LI.changeLoopFor(NewPreheader, StillReachable);
|
2019-02-15 13:18:10 +01:00
|
|
|
removeBlockFromLoops(NewPreheader, OuterLoop, StillReachable);
|
|
|
|
for (auto *BB : L.blocks())
|
|
|
|
removeBlockFromLoops(BB, OuterLoop, StillReachable);
|
2018-12-24 08:41:33 +01:00
|
|
|
OuterLoop->removeChildLoop(&L);
|
|
|
|
if (StillReachable)
|
|
|
|
StillReachable->addChildLoop(&L);
|
|
|
|
else
|
|
|
|
LI.addTopLevelLoop(&L);
|
2019-01-17 13:51:10 +01:00
|
|
|
|
|
|
|
// Some values from loops in [OuterLoop, StillReachable) could be used
|
|
|
|
// in the current loop. Now it is not their child anymore, so such uses
|
|
|
|
// require LCSSA Phis.
|
|
|
|
Loop *FixLCSSALoop = OuterLoop;
|
|
|
|
while (FixLCSSALoop->getParentLoop() != StillReachable)
|
|
|
|
FixLCSSALoop = FixLCSSALoop->getParentLoop();
|
|
|
|
assert(FixLCSSALoop && "Should be a loop!");
|
2019-02-08 09:12:41 +01:00
|
|
|
// We need all DT updates to be done before forming LCSSA.
|
2019-02-21 20:54:05 +01:00
|
|
|
if (MSSAU)
|
2020-12-14 20:53:35 +01:00
|
|
|
MSSAU->applyUpdates(DTUpdates, DT, /*UpdateDT=*/true);
|
|
|
|
else
|
|
|
|
DTU.applyUpdates(DTUpdates);
|
2019-02-08 09:12:41 +01:00
|
|
|
DTUpdates.clear();
|
2019-01-17 13:51:10 +01:00
|
|
|
formLCSSARecursively(*FixLCSSALoop, DT, &LI, &SE);
|
2018-12-24 08:41:33 +01:00
|
|
|
}
|
|
|
|
}
|
2019-02-21 20:54:05 +01:00
|
|
|
|
|
|
|
if (MSSAU) {
|
|
|
|
// Clear all updates now. Facilitates deletes that follow.
|
2020-12-14 20:53:35 +01:00
|
|
|
MSSAU->applyUpdates(DTUpdates, DT, /*UpdateDT=*/true);
|
2019-02-21 20:54:05 +01:00
|
|
|
DTUpdates.clear();
|
|
|
|
if (VerifyMemorySSA)
|
|
|
|
MSSAU->getMemorySSA()->verifyMemorySSA();
|
|
|
|
}
|
2018-12-24 08:41:33 +01:00
|
|
|
}
|
|
|
|
|
2018-12-24 07:06:17 +01:00
|
|
|
/// Delete loop blocks that have become unreachable after folding. Make all
|
|
|
|
/// relevant updates to DT and LI.
|
|
|
|
void deleteDeadLoopBlocks() {
|
2018-12-28 07:08:51 +01:00
|
|
|
if (MSSAU) {
|
2019-07-13 00:30:30 +02:00
|
|
|
SmallSetVector<BasicBlock *, 8> DeadLoopBlocksSet(DeadLoopBlocks.begin(),
|
|
|
|
DeadLoopBlocks.end());
|
2018-12-28 07:08:51 +01:00
|
|
|
MSSAU->removeBlocks(DeadLoopBlocksSet);
|
|
|
|
}
|
2019-02-12 10:37:00 +01:00
|
|
|
|
|
|
|
// The function LI.erase has some invariants that need to be preserved when
|
|
|
|
// it tries to remove a loop which is not the top-level loop. In particular,
|
|
|
|
// it requires loop's preheader to be strictly in loop's parent. We cannot
|
|
|
|
// just remove blocks one by one, because after removal of preheader we may
|
|
|
|
// break this invariant for the dead loop. So we detatch and erase all dead
|
|
|
|
// loops beforehand.
|
|
|
|
for (auto *BB : DeadLoopBlocks)
|
|
|
|
if (LI.isLoopHeader(BB)) {
|
|
|
|
assert(LI.getLoopFor(BB) != &L && "Attempt to remove current loop!");
|
|
|
|
Loop *DL = LI.getLoopFor(BB);
|
2020-09-22 22:28:00 +02:00
|
|
|
if (!DL->isOutermost()) {
|
2019-02-12 10:37:00 +01:00
|
|
|
for (auto *PL = DL->getParentLoop(); PL; PL = PL->getParentLoop())
|
|
|
|
for (auto *BB : DL->getBlocks())
|
|
|
|
PL->removeBlockFromLoop(BB);
|
|
|
|
DL->getParentLoop()->removeChildLoop(DL);
|
|
|
|
LI.addTopLevelLoop(DL);
|
|
|
|
}
|
|
|
|
LI.erase(DL);
|
|
|
|
}
|
|
|
|
|
2018-12-24 07:06:17 +01:00
|
|
|
for (auto *BB : DeadLoopBlocks) {
|
|
|
|
assert(BB != L.getHeader() &&
|
|
|
|
"Header of the current loop cannot be dead!");
|
|
|
|
LLVM_DEBUG(dbgs() << "Deleting dead loop block " << BB->getName()
|
|
|
|
<< "\n");
|
|
|
|
LI.removeBlock(BB);
|
|
|
|
}
|
2019-01-17 13:25:40 +01:00
|
|
|
|
2019-02-12 08:48:07 +01:00
|
|
|
DetatchDeadBlocks(DeadLoopBlocks, &DTUpdates, /*KeepOneInputPHIs*/true);
|
2019-02-08 09:12:41 +01:00
|
|
|
DTU.applyUpdates(DTUpdates);
|
|
|
|
DTUpdates.clear();
|
|
|
|
for (auto *BB : DeadLoopBlocks)
|
2019-02-12 09:10:29 +01:00
|
|
|
DTU.deleteBB(BB);
|
2019-02-08 09:12:41 +01:00
|
|
|
|
2019-01-17 13:25:40 +01:00
|
|
|
NumLoopBlocksDeleted += DeadLoopBlocks.size();
|
2018-12-24 07:06:17 +01:00
|
|
|
}
|
|
|
|
|
2018-11-20 06:43:32 +01:00
|
|
|
/// Constant-fold terminators of blocks acculumated in FoldCandidates into the
|
|
|
|
/// unconditional branches.
|
|
|
|
void foldTerminators() {
|
|
|
|
for (BasicBlock *BB : FoldCandidates) {
|
|
|
|
assert(LI.getLoopFor(BB) == &L && "Should be a loop block!");
|
|
|
|
BasicBlock *TheOnlySucc = getOnlyLiveSuccessor(BB);
|
|
|
|
assert(TheOnlySucc && "Should have one live successor!");
|
|
|
|
|
|
|
|
LLVM_DEBUG(dbgs() << "Replacing terminator of " << BB->getName()
|
|
|
|
<< " with an unconditional branch to the block "
|
|
|
|
<< TheOnlySucc->getName() << "\n");
|
|
|
|
|
|
|
|
SmallPtrSet<BasicBlock *, 2> DeadSuccessors;
|
|
|
|
// Remove all BB's successors except for the live one.
|
2018-11-27 07:17:21 +01:00
|
|
|
unsigned TheOnlySuccDuplicates = 0;
|
2018-11-20 06:43:32 +01:00
|
|
|
for (auto *Succ : successors(BB))
|
|
|
|
if (Succ != TheOnlySucc) {
|
|
|
|
DeadSuccessors.insert(Succ);
|
2018-11-23 08:56:47 +01:00
|
|
|
// If our successor lies in a different loop, we don't want to remove
|
|
|
|
// the one-input Phi because it is a LCSSA Phi.
|
|
|
|
bool PreserveLCSSAPhi = !L.contains(Succ);
|
|
|
|
Succ->removePredecessor(BB, PreserveLCSSAPhi);
|
2018-11-30 11:06:23 +01:00
|
|
|
if (MSSAU)
|
|
|
|
MSSAU->removeEdge(BB, Succ);
|
2018-11-27 07:17:21 +01:00
|
|
|
} else
|
|
|
|
++TheOnlySuccDuplicates;
|
|
|
|
|
|
|
|
assert(TheOnlySuccDuplicates > 0 && "Should be!");
|
|
|
|
// If TheOnlySucc was BB's successor more than once, after transform it
|
|
|
|
// will be its successor only once. Remove redundant inputs from
|
|
|
|
// TheOnlySucc's Phis.
|
|
|
|
bool PreserveLCSSAPhi = !L.contains(TheOnlySucc);
|
|
|
|
for (unsigned Dup = 1; Dup < TheOnlySuccDuplicates; ++Dup)
|
|
|
|
TheOnlySucc->removePredecessor(BB, PreserveLCSSAPhi);
|
2018-11-30 11:06:23 +01:00
|
|
|
if (MSSAU && TheOnlySuccDuplicates > 1)
|
|
|
|
MSSAU->removeDuplicatePhiEdgesBetween(BB, TheOnlySucc);
|
2018-11-20 06:43:32 +01:00
|
|
|
|
|
|
|
IRBuilder<> Builder(BB->getContext());
|
|
|
|
Instruction *Term = BB->getTerminator();
|
|
|
|
Builder.SetInsertPoint(Term);
|
|
|
|
Builder.CreateBr(TheOnlySucc);
|
|
|
|
Term->eraseFromParent();
|
|
|
|
|
|
|
|
for (auto *DeadSucc : DeadSuccessors)
|
2019-02-08 09:12:41 +01:00
|
|
|
DTUpdates.push_back({DominatorTree::Delete, BB, DeadSucc});
|
2018-11-20 06:43:32 +01:00
|
|
|
|
|
|
|
++NumTerminatorsFolded;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public:
|
2018-11-30 11:06:23 +01:00
|
|
|
ConstantTerminatorFoldingImpl(Loop &L, LoopInfo &LI, DominatorTree &DT,
|
2018-12-29 05:26:22 +01:00
|
|
|
ScalarEvolution &SE,
|
2018-11-30 11:06:23 +01:00
|
|
|
MemorySSAUpdater *MSSAU)
|
2019-02-15 12:39:35 +01:00
|
|
|
: L(L), LI(LI), DT(DT), SE(SE), MSSAU(MSSAU), DFS(&L),
|
2019-02-08 09:12:41 +01:00
|
|
|
DTU(DT, DomTreeUpdater::UpdateStrategy::Eager) {}
|
2018-11-20 06:43:32 +01:00
|
|
|
bool run() {
|
|
|
|
assert(L.getLoopLatch() && "Should be single latch!");
|
|
|
|
|
|
|
|
// Collect all available information about status of blocks after constant
|
|
|
|
// folding.
|
|
|
|
analyze();
|
2019-02-19 12:13:58 +01:00
|
|
|
BasicBlock *Header = L.getHeader();
|
|
|
|
(void)Header;
|
2018-11-20 06:43:32 +01:00
|
|
|
|
2019-02-19 12:13:58 +01:00
|
|
|
LLVM_DEBUG(dbgs() << "In function " << Header->getParent()->getName()
|
2018-11-20 06:43:32 +01:00
|
|
|
<< ": ");
|
|
|
|
|
2018-12-07 06:44:45 +01:00
|
|
|
if (HasIrreducibleCFG) {
|
|
|
|
LLVM_DEBUG(dbgs() << "Loops with irreducible CFG are not supported!\n");
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2018-11-20 06:43:32 +01:00
|
|
|
// Nothing to constant-fold.
|
|
|
|
if (FoldCandidates.empty()) {
|
|
|
|
LLVM_DEBUG(
|
|
|
|
dbgs() << "No constant terminator folding candidates found in loop "
|
2019-02-19 12:13:58 +01:00
|
|
|
<< Header->getName() << "\n");
|
2018-11-20 06:43:32 +01:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: Support deletion of the current loop.
|
|
|
|
if (DeleteCurrentLoop) {
|
|
|
|
LLVM_DEBUG(
|
|
|
|
dbgs()
|
2019-02-19 12:13:58 +01:00
|
|
|
<< "Give up constant terminator folding in loop " << Header->getName()
|
2018-11-20 06:43:32 +01:00
|
|
|
<< ": we don't currently support deletion of the current loop.\n");
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: Support blocks that are not dead, but also not in loop after the
|
|
|
|
// folding.
|
2018-12-24 07:06:17 +01:00
|
|
|
if (BlocksInLoopAfterFolding.size() + DeadLoopBlocks.size() !=
|
|
|
|
L.getNumBlocks()) {
|
2018-11-20 06:43:32 +01:00
|
|
|
LLVM_DEBUG(
|
|
|
|
dbgs() << "Give up constant terminator folding in loop "
|
2019-02-19 12:13:58 +01:00
|
|
|
<< Header->getName() << ": we don't currently"
|
2018-11-20 06:43:32 +01:00
|
|
|
" support blocks that are not dead, but will stop "
|
|
|
|
"being a part of the loop after constant-folding.\n");
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2018-12-29 05:26:22 +01:00
|
|
|
SE.forgetTopmostLoop(&L);
|
2018-11-20 06:43:32 +01:00
|
|
|
// Dump analysis results.
|
|
|
|
LLVM_DEBUG(dump());
|
|
|
|
|
|
|
|
LLVM_DEBUG(dbgs() << "Constant-folding " << FoldCandidates.size()
|
2019-02-19 12:13:58 +01:00
|
|
|
<< " terminators in loop " << Header->getName() << "\n");
|
2018-11-20 06:43:32 +01:00
|
|
|
|
|
|
|
// Make the actual transforms.
|
2018-12-24 08:41:33 +01:00
|
|
|
handleDeadExits();
|
2018-11-20 06:43:32 +01:00
|
|
|
foldTerminators();
|
|
|
|
|
2018-12-24 07:06:17 +01:00
|
|
|
if (!DeadLoopBlocks.empty()) {
|
|
|
|
LLVM_DEBUG(dbgs() << "Deleting " << DeadLoopBlocks.size()
|
2019-02-19 12:13:58 +01:00
|
|
|
<< " dead blocks in loop " << Header->getName() << "\n");
|
2018-12-24 07:06:17 +01:00
|
|
|
deleteDeadLoopBlocks();
|
2019-02-08 09:12:41 +01:00
|
|
|
} else {
|
|
|
|
// If we didn't do updates inside deleteDeadLoopBlocks, do them here.
|
|
|
|
DTU.applyUpdates(DTUpdates);
|
|
|
|
DTUpdates.clear();
|
2018-12-24 07:06:17 +01:00
|
|
|
}
|
|
|
|
|
2019-02-21 20:54:05 +01:00
|
|
|
if (MSSAU && VerifyMemorySSA)
|
|
|
|
MSSAU->getMemorySSA()->verifyMemorySSA();
|
|
|
|
|
2018-11-20 06:43:32 +01:00
|
|
|
#ifndef NDEBUG
|
|
|
|
// Make sure that we have preserved all data structures after the transform.
|
2019-04-29 15:29:55 +02:00
|
|
|
#if defined(EXPENSIVE_CHECKS)
|
|
|
|
assert(DT.verify(DominatorTree::VerificationLevel::Full) &&
|
|
|
|
"DT broken after transform!");
|
|
|
|
#else
|
|
|
|
assert(DT.verify(DominatorTree::VerificationLevel::Fast) &&
|
|
|
|
"DT broken after transform!");
|
|
|
|
#endif
|
2019-02-19 12:13:58 +01:00
|
|
|
assert(DT.isReachableFromEntry(Header));
|
2018-11-20 06:43:32 +01:00
|
|
|
LI.verify(DT);
|
|
|
|
#endif
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
2019-02-19 12:14:05 +01:00
|
|
|
|
|
|
|
bool foldingBreaksCurrentLoop() const {
|
|
|
|
return DeleteCurrentLoop;
|
|
|
|
}
|
2018-11-20 06:43:32 +01:00
|
|
|
};
|
2019-01-12 19:36:22 +01:00
|
|
|
} // namespace
|
2018-11-20 06:43:32 +01:00
|
|
|
|
|
|
|
/// Turn branches and switches with known constant conditions into unconditional
|
|
|
|
/// branches.
|
2018-11-30 11:06:23 +01:00
|
|
|
static bool constantFoldTerminators(Loop &L, DominatorTree &DT, LoopInfo &LI,
|
2018-12-29 05:26:22 +01:00
|
|
|
ScalarEvolution &SE,
|
2019-02-19 12:14:05 +01:00
|
|
|
MemorySSAUpdater *MSSAU,
|
|
|
|
bool &IsLoopDeleted) {
|
2018-11-23 10:14:53 +01:00
|
|
|
if (!EnableTermFolding)
|
|
|
|
return false;
|
|
|
|
|
2018-11-20 06:43:32 +01:00
|
|
|
// To keep things simple, only process loops with single latch. We
|
|
|
|
// canonicalize most loops to this form. We can support multi-latch if needed.
|
|
|
|
if (!L.getLoopLatch())
|
|
|
|
return false;
|
|
|
|
|
2018-12-29 05:26:22 +01:00
|
|
|
ConstantTerminatorFoldingImpl BranchFolder(L, LI, DT, SE, MSSAU);
|
2019-02-19 12:14:05 +01:00
|
|
|
bool Changed = BranchFolder.run();
|
|
|
|
IsLoopDeleted = Changed && BranchFolder.foldingBreaksCurrentLoop();
|
|
|
|
return Changed;
|
2018-11-20 06:43:32 +01:00
|
|
|
}
|
|
|
|
|
2018-11-01 10:42:50 +01:00
|
|
|
static bool mergeBlocksIntoPredecessors(Loop &L, DominatorTree &DT,
|
|
|
|
LoopInfo &LI, MemorySSAUpdater *MSSAU) {
|
2016-01-29 23:35:36 +01:00
|
|
|
bool Changed = false;
|
2018-08-03 07:08:17 +02:00
|
|
|
DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
|
2016-01-29 23:35:36 +01:00
|
|
|
// Copy blocks into a temporary array to avoid iterator invalidation issues
|
|
|
|
// as we remove them.
|
2017-05-01 19:07:49 +02:00
|
|
|
SmallVector<WeakTrackingVH, 16> Blocks(L.blocks());
|
2016-01-29 23:35:36 +01:00
|
|
|
|
|
|
|
for (auto &Block : Blocks) {
|
|
|
|
// Attempt to merge blocks in the trivial case. Don't modify blocks which
|
|
|
|
// belong to other loops.
|
2016-01-30 00:12:52 +01:00
|
|
|
BasicBlock *Succ = cast_or_null<BasicBlock>(Block);
|
2016-01-29 23:35:36 +01:00
|
|
|
if (!Succ)
|
|
|
|
continue;
|
|
|
|
|
|
|
|
BasicBlock *Pred = Succ->getSinglePredecessor();
|
2016-05-03 23:47:32 +02:00
|
|
|
if (!Pred || !Pred->getSingleSuccessor() || LI.getLoopFor(Pred) != &L)
|
2016-01-29 23:35:36 +01:00
|
|
|
continue;
|
|
|
|
|
Generalize MergeBlockIntoPredecessor. Replace uses of MergeBasicBlockIntoOnlyPred.
Summary:
Two utils methods have essentially the same functionality. This is an attempt to merge them into one.
1. lib/Transforms/Utils/Local.cpp : MergeBasicBlockIntoOnlyPred
2. lib/Transforms/Utils/BasicBlockUtils.cpp : MergeBlockIntoPredecessor
Prior to the patch:
1. MergeBasicBlockIntoOnlyPred
Updates either DomTree or DeferredDominance
Moves all instructions from Pred to BB, deletes Pred
Asserts BB has single predecessor
If address was taken, replace the block address with constant 1 (?)
2. MergeBlockIntoPredecessor
Updates DomTree, LoopInfo and MemoryDependenceResults
Moves all instruction from BB to Pred, deletes BB
Returns if doesn't have a single predecessor
Returns if BB's address was taken
After the patch:
Method 2. MergeBlockIntoPredecessor is attempting to become the new default:
Updates DomTree or DeferredDominance, and LoopInfo and MemoryDependenceResults
Moves all instruction from BB to Pred, deletes BB
Returns if doesn't have a single predecessor
Returns if BB's address was taken
Uses of MergeBasicBlockIntoOnlyPred that need to be replaced:
1. lib/Transforms/Scalar/LoopSimplifyCFG.cpp
Updated in this patch. No challenges.
2. lib/CodeGen/CodeGenPrepare.cpp
Updated in this patch.
i. eliminateFallThrough is straightforward, but I added using a temporary array to avoid the iterator invalidation.
ii. eliminateMostlyEmptyBlock(s) methods also now use a temporary array for blocks
Some interesting aspects:
- Since Pred is not deleted (BB is), the entry block does not need updating.
- The entry block was being updated with the deleted block in eliminateMostlyEmptyBlock. Added assert to make obvious that BB=SinglePred.
- isMergingEmptyBlockProfitable assumes BB is the one to be deleted.
- eliminateMostlyEmptyBlock(BB) does not delete BB on one path, it deletes its unique predecessor instead.
- adding some test owner as subscribers for the interesting tests modified:
test/CodeGen/X86/avx-cmp.ll
test/CodeGen/AMDGPU/nested-loop-conditions.ll
test/CodeGen/AMDGPU/si-annotate-cf.ll
test/CodeGen/X86/hoist-spill.ll
test/CodeGen/X86/2006-11-17-IllegalMove.ll
3. lib/Transforms/Scalar/JumpThreading.cpp
Not covered in this patch. It is the only use case using the DeferredDominance.
I would defer to Brian Rzycki to make this replacement.
Reviewers: chandlerc, spatel, davide, brzycki, bkramer, javed.absar
Subscribers: qcolombet, sanjoy, nemanjai, nhaehnle, jlebar, tpr, kbarton, RKSimon, wmi, arsenm, llvm-commits
Differential Revision: https://reviews.llvm.org/D48202
llvm-svn: 335183
2018-06-21 00:01:04 +02:00
|
|
|
// Merge Succ into Pred and delete it.
|
2018-08-22 22:10:21 +02:00
|
|
|
MergeBlockIntoPredecessor(Succ, &DTU, &LI, MSSAU);
|
2018-06-19 11:43:36 +02:00
|
|
|
|
2019-11-20 22:44:51 +01:00
|
|
|
if (MSSAU && VerifyMemorySSA)
|
|
|
|
MSSAU->getMemorySSA()->verifyMemorySSA();
|
|
|
|
|
2016-01-29 23:35:36 +01:00
|
|
|
Changed = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
return Changed;
|
|
|
|
}
|
|
|
|
|
2018-11-01 10:42:50 +01:00
|
|
|
static bool simplifyLoopCFG(Loop &L, DominatorTree &DT, LoopInfo &LI,
|
2019-02-19 12:14:05 +01:00
|
|
|
ScalarEvolution &SE, MemorySSAUpdater *MSSAU,
|
2020-02-05 01:29:04 +01:00
|
|
|
bool &IsLoopDeleted) {
|
2018-11-01 10:42:50 +01:00
|
|
|
bool Changed = false;
|
|
|
|
|
2018-11-20 06:43:32 +01:00
|
|
|
// Constant-fold terminators with known constant conditions.
|
2020-02-05 01:29:04 +01:00
|
|
|
Changed |= constantFoldTerminators(L, DT, LI, SE, MSSAU, IsLoopDeleted);
|
2019-02-19 12:14:05 +01:00
|
|
|
|
2020-02-05 01:29:04 +01:00
|
|
|
if (IsLoopDeleted)
|
2019-02-19 12:14:05 +01:00
|
|
|
return true;
|
2018-11-20 06:43:32 +01:00
|
|
|
|
2018-11-01 10:42:50 +01:00
|
|
|
// Eliminate unconditional branches by merging blocks into their predecessors.
|
|
|
|
Changed |= mergeBlocksIntoPredecessors(L, DT, LI, MSSAU);
|
|
|
|
|
|
|
|
if (Changed)
|
|
|
|
SE.forgetTopmostLoop(&L);
|
|
|
|
|
|
|
|
return Changed;
|
|
|
|
}
|
|
|
|
|
2017-01-11 07:23:21 +01:00
|
|
|
PreservedAnalyses LoopSimplifyCFGPass::run(Loop &L, LoopAnalysisManager &AM,
|
|
|
|
LoopStandardAnalysisResults &AR,
|
2019-02-19 12:14:05 +01:00
|
|
|
LPMUpdater &LPMU) {
|
2018-08-22 22:10:21 +02:00
|
|
|
Optional<MemorySSAUpdater> MSSAU;
|
2019-08-17 03:02:12 +02:00
|
|
|
if (AR.MSSA)
|
2018-08-22 22:10:21 +02:00
|
|
|
MSSAU = MemorySSAUpdater(AR.MSSA);
|
2019-02-19 12:14:05 +01:00
|
|
|
bool DeleteCurrentLoop = false;
|
2018-08-22 22:10:21 +02:00
|
|
|
if (!simplifyLoopCFG(L, AR.DT, AR.LI, AR.SE,
|
2019-02-19 12:14:05 +01:00
|
|
|
MSSAU.hasValue() ? MSSAU.getPointer() : nullptr,
|
|
|
|
DeleteCurrentLoop))
|
2016-05-03 23:47:32 +02:00
|
|
|
return PreservedAnalyses::all();
|
2017-01-15 07:32:49 +01:00
|
|
|
|
2019-02-19 12:14:05 +01:00
|
|
|
if (DeleteCurrentLoop)
|
|
|
|
LPMU.markLoopAsDeleted(L, "loop-simplifycfg");
|
|
|
|
|
2019-06-11 20:27:49 +02:00
|
|
|
auto PA = getLoopPassPreservedAnalyses();
|
2019-08-17 03:02:12 +02:00
|
|
|
if (AR.MSSA)
|
2019-06-11 20:27:49 +02:00
|
|
|
PA.preserve<MemorySSAAnalysis>();
|
|
|
|
return PA;
|
2016-05-03 23:47:32 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
namespace {
|
|
|
|
class LoopSimplifyCFGLegacyPass : public LoopPass {
|
|
|
|
public:
|
|
|
|
static char ID; // Pass ID, replacement for typeid
|
|
|
|
LoopSimplifyCFGLegacyPass() : LoopPass(ID) {
|
|
|
|
initializeLoopSimplifyCFGLegacyPassPass(*PassRegistry::getPassRegistry());
|
|
|
|
}
|
|
|
|
|
2019-02-19 12:14:05 +01:00
|
|
|
bool runOnLoop(Loop *L, LPPassManager &LPM) override {
|
2016-05-03 23:47:32 +02:00
|
|
|
if (skipLoop(L))
|
|
|
|
return false;
|
|
|
|
|
|
|
|
DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
|
|
|
|
LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
|
2018-06-19 11:43:36 +02:00
|
|
|
ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
|
2018-08-22 22:10:21 +02:00
|
|
|
Optional<MemorySSAUpdater> MSSAU;
|
|
|
|
if (EnableMSSALoopDependency) {
|
|
|
|
MemorySSA *MSSA = &getAnalysis<MemorySSAWrapperPass>().getMSSA();
|
|
|
|
MSSAU = MemorySSAUpdater(MSSA);
|
|
|
|
if (VerifyMemorySSA)
|
|
|
|
MSSA->verifyMemorySSA();
|
|
|
|
}
|
2019-02-19 12:14:05 +01:00
|
|
|
bool DeleteCurrentLoop = false;
|
|
|
|
bool Changed = simplifyLoopCFG(
|
|
|
|
*L, DT, LI, SE, MSSAU.hasValue() ? MSSAU.getPointer() : nullptr,
|
|
|
|
DeleteCurrentLoop);
|
|
|
|
if (DeleteCurrentLoop)
|
|
|
|
LPM.markLoopAsDeleted(*L);
|
|
|
|
return Changed;
|
2016-05-03 23:47:32 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
void getAnalysisUsage(AnalysisUsage &AU) const override {
|
2018-08-22 22:10:21 +02:00
|
|
|
if (EnableMSSALoopDependency) {
|
|
|
|
AU.addRequired<MemorySSAWrapperPass>();
|
|
|
|
AU.addPreserved<MemorySSAWrapperPass>();
|
|
|
|
}
|
2016-05-13 00:19:39 +02:00
|
|
|
AU.addPreserved<DependenceAnalysisWrapperPass>();
|
2016-05-03 23:47:32 +02:00
|
|
|
getLoopAnalysisUsage(AU);
|
|
|
|
}
|
|
|
|
};
|
2020-02-05 01:29:04 +01:00
|
|
|
} // end namespace
|
2016-05-03 23:47:32 +02:00
|
|
|
|
|
|
|
char LoopSimplifyCFGLegacyPass::ID = 0;
|
|
|
|
INITIALIZE_PASS_BEGIN(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
|
|
|
|
"Simplify loop CFG", false, false)
|
|
|
|
INITIALIZE_PASS_DEPENDENCY(LoopPass)
|
2018-08-22 22:10:21 +02:00
|
|
|
INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
|
2016-05-03 23:47:32 +02:00
|
|
|
INITIALIZE_PASS_END(LoopSimplifyCFGLegacyPass, "loop-simplifycfg",
|
|
|
|
"Simplify loop CFG", false, false)
|
2016-01-29 23:35:36 +01:00
|
|
|
|
2016-05-03 23:47:32 +02:00
|
|
|
Pass *llvm::createLoopSimplifyCFGPass() {
|
|
|
|
return new LoopSimplifyCFGLegacyPass();
|
2016-01-29 23:35:36 +01:00
|
|
|
}
|