79 #define DEBUG_TYPE "loop-simplify" 81 STATISTIC(NumNested ,
"Number of nested loops split out");
91 for (
unsigned i = 0,
e = SplitPreds.
size(); i !=
e; ++i) {
92 if (&*BBI == SplitPreds[i])
103 for (
unsigned i = 0,
e = SplitPreds.
size(); i !=
e; ++i) {
106 FoundBB = SplitPreds[i];
115 FoundBB = SplitPreds[0];
125 bool PreserveLCSSA) {
148 LI, MSSAU, PreserveLCSSA);
153 << PreheaderBB->
getName() <<
"\n");
166 std::set<BasicBlock*> &Blocks) {
171 if (Blocks.insert(BB).second && BB != StopBlock)
178 }
while (!Worklist.
empty());
235 assert(!Header->
isEHPad() &&
"Can't insert backedge to EH pad");
238 if (!PN)
return nullptr;
244 for (
unsigned i = 0,
e = PN->getNumIncomingValues(); i !=
e; ++i) {
245 if (PN->getIncomingValue(i) != PN ||
246 !L->
contains(PN->getIncomingBlock(i))) {
248 if (PN->getIncomingBlock(i)->getTerminator()->isIndirectTerminator())
250 OuterLoopPreds.
push_back(PN->getIncomingBlock(i));
253 LLVM_DEBUG(
dbgs() <<
"LoopSimplify: Splitting out a new outer loop\n");
262 DT, LI, MSSAU, PreserveLCSSA);
290 std::set<BasicBlock*> BlocksInL;
299 const std::vector<Loop*> &SubLoops = L->
getSubLoops();
300 for (
size_t I = 0;
I != SubLoops.size(); )
301 if (BlocksInL.count(SubLoops[
I]->getHeader()))
310 for (
unsigned i = 0; i != L->
getBlocks().size(); ++i) {
312 if (!BlocksInL.count(BB)) {
315 if ((*LI)[BB] == L) {
337 "LCSSA is broken after separating nested loops!");
363 assert(!Header->isEHPad() &&
"Can't insert backedge to EH pad");
366 std::vector<BasicBlock*> BackedgeBlocks;
374 if (P != Preheader) BackedgeBlocks.push_back(P);
379 Header->getName() +
".backedge",
F);
381 BETerminator->setDebugLoc(Header->getFirstNonPHI()->getDebugLoc());
383 LLVM_DEBUG(
dbgs() <<
"LoopSimplify: Inserting unique backedge block " 384 << BEBlock->
getName() <<
"\n");
395 PN->
getName()+
".be", BETerminator);
399 unsigned PreheaderIdx = ~0U;
400 bool HasUniqueIncomingValue =
true;
401 Value *UniqueValue =
nullptr;
405 if (IBB == Preheader) {
408 NewPN->addIncoming(IV, IBB);
409 if (HasUniqueIncomingValue) {
412 else if (UniqueValue != IV)
413 HasUniqueIncomingValue =
false;
419 assert(PreheaderIdx != ~0U &&
"PHI has no preheader entry??");
420 if (PreheaderIdx != 0) {
434 if (HasUniqueIncomingValue) {
435 NewPN->replaceAllUsesWith(UniqueValue);
446 for (
unsigned i = 0,
e = BackedgeBlocks.size(); i !=
e; ++i) {
447 Instruction *TI = BackedgeBlocks[i]->getTerminator();
476 bool Changed =
false;
492 PE =
pred_end(*BB); PI != PE; ++PI) {
501 LLVM_DEBUG(
dbgs() <<
"LoopSimplify: Deleting edge from dead predecessor " 502 <<
P->getName() <<
"\n");
520 for (
BasicBlock *ExitingBlock : ExitingBlocks)
521 if (
BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
522 if (BI->isConditional()) {
523 if (
UndefValue *Cond = dyn_cast<UndefValue>(BI->getCondition())) {
526 <<
"LoopSimplify: Resolving \"br i1 undef\" to exit in " 527 << ExitingBlock->getName() <<
"\n");
530 !L->
contains(BI->getSuccessor(0))));
563 PreserveLCSSA, AC, MSSAU)) {
613 auto HasUniqueExitBlock = [&]() {
615 for (
auto *ExitingBB : ExitingBlocks)
622 else if (UniqueExit != SuccBB)
628 if (HasUniqueExitBlock()) {
629 for (
unsigned i = 0,
e = ExitingBlocks.size(); i !=
e; ++i) {
635 if (!CI || CI->
getParent() != ExitingBlock)
continue;
639 bool AllInvariant =
true;
640 bool AnyInvariant =
false;
648 AllInvariant =
false;
659 if (!AllInvariant)
continue;
670 << ExitingBlock->
getName() <<
"\n");
677 const std::vector<DomTreeNodeBase<BasicBlock> *> &Children =
679 while (!Children.empty()) {
686 ExitBlockSet.
insert(ExitingBlock);
691 ExitingBlock, PreserveLCSSA);
693 ExitingBlock, PreserveLCSSA);
713 bool Changed =
false;
719 assert(DT &&
"DT not available.");
720 assert(LI &&
"LI not available.");
722 "Requested to preserve LCSSA, but it's already broken.");
733 for (
unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
734 Loop *L2 = Worklist[Idx];
735 Worklist.append(L2->
begin(), L2->
end());
738 while (!Worklist.empty())
739 Changed |=
simplifyOneLoop(Worklist.pop_back_val(), Worklist, DT, LI, SE,
740 AC, MSSAU, PreserveLCSSA);
778 void verifyAnalysis()
const override;
784 "Canonicalize natural loops",
false,
false)
799 bool Changed =
false;
800 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
801 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
802 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
805 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
807 std::unique_ptr<MemorySSAUpdater> MSSAU;
809 auto *MSSAAnalysis = getAnalysisIfAvailable<MemorySSAWrapperPass>();
811 MSSA = &MSSAAnalysis->getMSSA();
812 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
816 bool PreserveLCSSA = mustPreserveAnalysisID(
LCSSAID);
820 Changed |=
simplifyLoop(*
I, DT, LI, SE, AC, MSSAU.get(), PreserveLCSSA);
826 assert(InLCSSA &&
"LCSSA is broken after loop-simplify.");
834 bool Changed =
false;
840 std::unique_ptr<MemorySSAUpdater> MSSAU;
842 auto *MSSA = &MSSAAnalysis->getMSSA();
843 MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
878 static void verifyLoop(
Loop *L) {
890 bool HasIndBrPred =
false;
893 if (isa<IndirectBrInst>((*PI)->getTerminator())) {
898 "LoopSimplify has no excuse for missing loop header info!");
904 bool HasIndBrExiting =
false;
907 for (
unsigned i = 0,
e = ExitingBlocks.
size(); i !=
e; ++i) {
908 if (isa<IndirectBrInst>((ExitingBlocks[i])->getTerminator())) {
909 HasIndBrExiting =
true;
915 "LoopSimplify has no excuse for missing exit block info!");
916 (void)HasIndBrExiting;
921 void LoopSimplify::verifyAnalysis()
const {
Legacy wrapper pass to provide the GlobalsAAResult object.
Pass interface - Implemented by all 'passes'.
static void addBlockAndPredsToSet(BasicBlock *InputBB, BasicBlock *StopBlock, std::set< BasicBlock *> &Blocks)
Add the specified block, and all of its predecessors, to the specified set, if it's not already in th...
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
loop Canonicalize natural loops
A parsed version of the target data layout string in and methods for querying it. ...
Pass * createLoopSimplifyPass()
This class is the base class for the comparison instructions.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
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...
void splitBlock(NodeT *NewBB)
splitBlock - BB is split and now it has one successor.
bool VerifyMemorySSA
Enables verification of MemorySSA.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
iterator erase(iterator where)
AnalysisPass to compute dependence information in a function.
This class represents lattice values for constants.
This is the interface for a simple mod/ref and alias analysis over globals.
ArrayRef< BasicBlock *>::const_iterator block_iterator
static void placeSplitBlockCarefully(BasicBlock *NewBB, SmallVectorImpl< BasicBlock *> &SplitPreds, Loop *L)
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
bool isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const
Return true if this Loop and all inner subloops are in LCSSA form.
Legacy pass manager pass to access dependence information.
void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Notify the BasicBlock that the predecessor Pred is no longer able to reach it.
void push_back(const T &Elt)
void moveToHeader(BlockT *BB)
This method is used to move BB (which must be part of this loop) to be the loop header of the loop (t...
LoopT * removeChildLoop(iterator I)
This removes the specified child from being a subloop of this loop.
The main scalar evolution driver.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
void replaceSuccessorWith(BasicBlock *OldBB, BasicBlock *NewBB)
Replace specified successor OldBB to point at the provided block.
void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild)
This is used when splitting loops up.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
BasicBlock * getSuccessor(unsigned i) const
STATISTIC(NumFunctions, "Total number of functions")
Analysis pass which computes a DominatorTree.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Value * getCondition() const
static Loop * separateNestedLoop(Loop *L, BasicBlock *Preheader, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, bool PreserveLCSSA, AssumptionCache *AC, MemorySSAUpdater *MSSAU)
If this loop has multiple backedges, try to pull one of them out into a nested loop.
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...
LLVMContext & getContext() const
Get the context in which this basic block lives.
void eraseNode(NodeT *BB)
eraseNode - Removes a node from the dominator tree.
iterator begin()
Instruction iterator methods.
unsigned getMDKindID(StringRef Name) const
getMDKindID - Return a unique non-zero ID for the specified metadata kind.
static PHINode * findPHIToPartitionLoops(Loop *L, DominatorTree *DT, AssumptionCache *AC)
The first part of loop-nestification is to find a PHI node that tells us how to partition the loops...
AnalysisUsage & addRequired()
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
#define INITIALIZE_PASS_DEPENDENCY(depName)
Legacy analysis pass which computes MemorySSA.
unsigned getNumBackEdges() const
Calculate the number of back edges to the loop header.
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
This is the interface for a SCEV-based alias analysis.
MemorySSA * getMemorySSA() const
Get handle on MemorySSA.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
'undef' values are things that do not have specified contents.
void addBlockEntry(BlockT *BB)
This adds a basic block directly to the basic block list.
Encapsulates MemorySSA, including all data associated with memory accesses.
std::vector< Loop *>::const_iterator iterator
iterator/begin/end - The interface to the top-level loops in the current function.
Analysis pass that exposes the LoopInfo for a function.
BlockT * getHeader() const
Analysis pass which computes BranchProbabilityInfo.
std::vector< Loop *>::const_iterator iterator
Type * getType() const
All values are typed, get the type of this value.
bool insert(const value_type &X)
Insert a new element into the SetVector.
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
const std::vector< DomTreeNodeBase * > & getChildren() const
AnalysisUsage & addPreservedID(const void *ID)
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Legacy analysis pass which computes BranchProbabilityInfo.
bool formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Ensure that all exit blocks of the loop are dedicated exits.
void forgetLoopDispositions(const Loop *L)
Called when the client has changed the disposition of values in this loop.
bool FoldBranchToCommonDest(BranchInst *BI, MemorySSAUpdater *MSSAU=nullptr, unsigned BonusInstThreshold=1)
If this basic block is ONLY a setcc and a branch, and if a predecessor branches to us and one of our ...
static bool runOnFunction(Function &F, bool PostInlining)
BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock *> Preds, const char *Suffix, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
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.
void updatePhisWhenInsertingUniqueBackedgeBlock(BasicBlock *LoopHeader, BasicBlock *LoopPreheader, BasicBlock *BackedgeBlock)
Update MemorySSA when inserting a unique backedge block for a loop.
LLVM Basic Block Representation.
Conditional or Unconditional Branch instruction.
char & BreakCriticalEdgesID
iterator_range< filter_iterator< BasicBlock::const_iterator, std::function< bool(const Instruction &)> > > instructionsWithoutDebug() const
Return a const iterator range over the instructions in the block, skipping any debug instructions...
void changeImmediateDominator(DomTreeNodeBase< NodeT > *N, DomTreeNodeBase< NodeT > *NewIDom)
changeImmediateDominator - This method is used to update the dominator tree information when a node's...
DomTreeNodeBase * getIDom() const
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static bool simplifyOneLoop(Loop *L, SmallVectorImpl< Loop *> &Worklist, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
Simplify one loop and queue further loops for simplification.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Represent the analysis usage information of a pass.
void splice(iterator where, iplist_impl &L2)
Analysis pass providing a never-invalidated alias analysis result.
FunctionPass class - This class is used to implement most global optimizations.
Interval::pred_iterator pred_end(Interval *I)
Analysis pass providing a never-invalidated alias analysis result.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
self_iterator getIterator()
void forgetValue(Value *V)
This method should be called by the client when it has changed a value in a way that may effect its v...
void getExitingBlocks(SmallVectorImpl< BlockT *> &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
bool formLCSSA(Loop &L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution *SE)
Put loop into LCSSA form.
A function analysis which provides an AssumptionCache.
const InstListType & getInstList() const
Return the underlying instruction list container.
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.
Iterator for intrusive lists based on ilist_node.
void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Legacy wrapper pass to provide the SCEVAAResult object.
void setIncomingBlock(unsigned i, BasicBlock *BB)
void verifyMemorySSA() const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Module.h This file contains the declarations for the Module class.
LoopT * AllocateLoop(ArgsTy &&... Args)
An analysis that produces MemorySSA for a function.
LLVM_NODISCARD T pop_back_val()
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
bool isConditional() const
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
unsigned getNumIncomingValues() const
Return the number of incoming edges.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Analysis pass that exposes the ScalarEvolution for a function.
LoopT * getParentLoop() const
const std::vector< LoopT * > & getSubLoops() const
Return the loops contained entirely within this loop.
Analysis pass providing a never-invalidated alias analysis result.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
void forgetLoop(const Loop *L)
This method should be called by the client when it has changed a loop in a way that may effect Scalar...
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
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.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
void changeTopLevelLoop(LoopT *OldLoop, LoopT *NewLoop)
Replace the specified loop in the top-level loops list with the indicated loop.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
block_iterator block_end() const
void changeLoopFor(BlockT *BB, LoopT *L)
Change the top-level loop that contains BB to the specified loop.
void preserve()
Mark an analysis as preserved.
void removeBlockFromLoop(BlockT *BB)
This removes the specified basic block from the current loop, updating the Blocks as appropriate...
void initializeLoopSimplifyPass(PassRegistry &)
bool isIndirectTerminator() const
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.
bool isEHPad() const
Return true if this basic block is an exception handling block.
LLVM Value Representation.
succ_range successors(Instruction *I)
static BasicBlock * insertUniqueBackedgeBlock(Loop *L, BasicBlock *Preheader, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU)
This method is called when the specified loop has more than one backedge in it.
BasicBlock * InsertPreheaderForLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, MemorySSAUpdater *MSSAU, bool PreserveLCSSA)
InsertPreheaderForLoop - Once we discover that a loop doesn't have a preheader, this method is called...
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
The legacy pass manager's analysis pass to compute loop information.
INITIALIZE_PASS_BEGIN(LoopSimplify, "loop-simplify", "Canonicalize natural loops", false, false) INITIALIZE_PASS_END(LoopSimplify
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.
Legacy analysis pass which computes a DominatorTree.
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form...
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
void setIncomingValue(unsigned i, Value *V)
block_iterator block_begin() const
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
unsigned changeToUnreachable(Instruction *I, bool UseLLVMTrap, bool PreserveLCSSA=false, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Insert an unreachable instruction before the specified instruction, making it and the rest of the cod...
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
const BasicBlock * getParent() const
Legacy wrapper pass to provide the BasicAAResult object.
void forgetTopmostLoop(const Loop *L)
bool makeLoopInvariant(Value *V, bool &Changed, Instruction *InsertPt=nullptr, MemorySSAUpdater *MSSAU=nullptr) const
If the given value is an instruction inside of the loop and it can be hoisted, do so to make it trivi...