73 #define DEBUG_TYPE "loop-simplify" 75 STATISTIC(NumNested ,
"Number of nested loops split out");
85 for (
unsigned i = 0, e = SplitPreds.
size(); i != e; ++i) {
86 if (&*BBI == SplitPreds[i])
97 for (
unsigned i = 0, e = SplitPreds.
size(); i != e; ++i) {
100 FoundBB = SplitPreds[i];
109 FoundBB = SplitPreds[0];
140 LI,
nullptr, PreserveLCSSA);
145 << PreheaderBB->
getName() <<
"\n");
158 std::set<BasicBlock*> &Blocks) {
163 if (Blocks.insert(BB).second && BB != StopBlock)
170 }
while (!Worklist.
empty());
227 assert(!Header->
isEHPad() &&
"Can't insert backedge to EH pad");
230 if (!PN)
return nullptr;
236 for (
unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
237 if (PN->getIncomingValue(i) != PN ||
238 !L->
contains(PN->getIncomingBlock(i))) {
240 if (isa<IndirectBrInst>(PN->getIncomingBlock(i)->getTerminator()))
242 OuterLoopPreds.
push_back(PN->getIncomingBlock(i));
245 LLVM_DEBUG(
dbgs() <<
"LoopSimplify: Splitting out a new outer loop\n");
254 DT, LI,
nullptr, PreserveLCSSA);
282 std::set<BasicBlock*> BlocksInL;
291 const std::vector<Loop*> &SubLoops = L->
getSubLoops();
292 for (
size_t I = 0;
I != SubLoops.size(); )
293 if (BlocksInL.count(SubLoops[
I]->getHeader()))
302 for (
unsigned i = 0; i != L->
getBlocks().size(); ++i) {
304 if (!BlocksInL.count(BB)) {
307 if ((*LI)[BB] == L) {
329 "LCSSA is broken after separating nested loops!");
354 assert(!Header->isEHPad() &&
"Can't insert backedge to EH pad");
357 std::vector<BasicBlock*> BackedgeBlocks;
365 if (P != Preheader) BackedgeBlocks.push_back(P);
370 Header->getName() +
".backedge",
F);
372 BETerminator->setDebugLoc(Header->getFirstNonPHI()->getDebugLoc());
374 LLVM_DEBUG(
dbgs() <<
"LoopSimplify: Inserting unique backedge block " 375 << BEBlock->
getName() <<
"\n");
386 PN->
getName()+
".be", BETerminator);
390 unsigned PreheaderIdx = ~0U;
391 bool HasUniqueIncomingValue =
true;
392 Value *UniqueValue =
nullptr;
396 if (IBB == Preheader) {
399 NewPN->addIncoming(IV, IBB);
400 if (HasUniqueIncomingValue) {
403 else if (UniqueValue != IV)
404 HasUniqueIncomingValue =
false;
410 assert(PreheaderIdx != ~0U &&
"PHI has no preheader entry??");
411 if (PreheaderIdx != 0) {
425 if (HasUniqueIncomingValue) {
426 NewPN->replaceAllUsesWith(UniqueValue);
437 for (
unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
438 Instruction *TI = BackedgeBlocks[i]->getTerminator();
464 bool PreserveLCSSA) {
465 bool Changed =
false;
478 PE =
pred_end(*BB); PI != PE; ++PI) {
487 LLVM_DEBUG(
dbgs() <<
"LoopSimplify: Deleting edge from dead predecessor " 488 <<
P->getName() <<
"\n");
502 for (
BasicBlock *ExitingBlock : ExitingBlocks)
503 if (
BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator()))
504 if (BI->isConditional()) {
505 if (
UndefValue *Cond = dyn_cast<UndefValue>(BI->getCondition())) {
508 <<
"LoopSimplify: Resolving \"br i1 undef\" to exit in " 509 << ExitingBlock->getName() <<
"\n");
512 !L->
contains(BI->getSuccessor(0))));
589 auto HasUniqueExitBlock = [&]() {
591 for (
auto *ExitingBB : ExitingBlocks)
598 else if (UniqueExit != SuccBB)
604 if (HasUniqueExitBlock()) {
605 for (
unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
611 if (!CI || CI->
getParent() != ExitingBlock)
continue;
615 bool AllInvariant =
true;
616 bool AnyInvariant =
false;
624 AllInvariant =
false;
635 if (!AllInvariant)
continue;
646 << ExitingBlock->
getName() <<
"\n");
653 const std::vector<DomTreeNodeBase<BasicBlock> *> &Children =
655 while (!Children.empty()) {
662 ExitingBlock, PreserveLCSSA);
664 ExitingBlock, PreserveLCSSA);
680 bool PreserveLCSSA) {
681 bool Changed =
false;
687 assert(DT &&
"DT not available.");
688 assert(LI &&
"LI not available.");
690 "Requested to preserve LCSSA, but it's already broken.");
701 for (
unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
702 Loop *L2 = Worklist[Idx];
703 Worklist.append(L2->
begin(), L2->
end());
706 while (!Worklist.empty())
707 Changed |=
simplifyOneLoop(Worklist.pop_back_val(), Worklist, DT, LI, SE,
743 void verifyAnalysis()
const override;
749 "Canonicalize natural loops",
false,
false)
764 bool Changed =
false;
765 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
766 DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
767 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
770 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
772 bool PreserveLCSSA = mustPreserveAnalysisID(
LCSSAID);
782 assert(InLCSSA &&
"LCSSA is broken after loop-simplify.");
790 bool Changed =
false;
818 static void verifyLoop(
Loop *L) {
830 bool HasIndBrPred =
false;
833 if (isa<IndirectBrInst>((*PI)->getTerminator())) {
838 "LoopSimplify has no excuse for missing loop header info!");
844 bool HasIndBrExiting =
false;
847 for (
unsigned i = 0, e = ExitingBlocks.
size(); i != e; ++i) {
848 if (isa<IndirectBrInst>((ExitingBlocks[i])->getTerminator())) {
849 HasIndBrExiting =
true;
855 "LoopSimplify has no excuse for missing exit block info!");
856 (void)HasIndBrExiting;
861 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.
void removePredecessor(BasicBlock *Pred, bool DontDeleteUselessPHIs=false)
Notify the BasicBlock that the predecessor Pred is no longer able to reach it.
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.
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
BasicBlock * getSuccessor(unsigned Idx) const
Return the specified successor. This instruction must be a terminator.
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 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.
BasicBlock * InsertPreheaderForLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, bool PreserveLCSSA)
InsertPreheaderForLoop - Once we discover that a loop doesn't have a preheader, this method is called...
A cache of @llvm.assume calls within a function.
bool makeLoopInvariant(Value *V, bool &Changed, Instruction *InsertPt=nullptr) const
If the given value is an instruction inside of the loop and it can be hoisted, do so to make it trivi...
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.
static Loop * separateNestedLoop(Loop *L, BasicBlock *Preheader, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, bool PreserveLCSSA, AssumptionCache *AC)
If this loop has multiple backedges, try to pull one of them out into a nested loop.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Value * getCondition() const
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...
void setSuccessor(unsigned Idx, BasicBlock *BB)
Update the specified successor to point at the provided block.
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)
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.
unsigned changeToUnreachable(Instruction *I, bool UseLLVMTrap, bool PreserveLCSSA=false, DomTreeUpdater *DTU=nullptr)
Insert an unreachable instruction before the specified instruction, making it and the rest of the cod...
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
bool simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, bool PreserveLCSSA)
Simplify each loop in a loop nest recursively.
'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.
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
std::vector< Loop *>::const_iterator iterator
Type * getType() const
All values are typed, get the type of this value.
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...
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
void forgetLoopDispositions(const Loop *L)
Called when the client has changed the disposition of values in this loop.
static BasicBlock * insertUniqueBackedgeBlock(Loop *L, BasicBlock *Preheader, DominatorTree *DT, LoopInfo *LI)
This method is called when the specified loop has more than one backedge in it.
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...
bool FoldBranchToCommonDest(BranchInst *BI, 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 ...
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.
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")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool simplifyOneLoop(Loop *L, SmallVectorImpl< Loop *> &Worklist, DominatorTree *DT, LoopInfo *LI, ScalarEvolution *SE, AssumptionCache *AC, bool PreserveLCSSA)
Simplify one loop and queue further loops for simplification.
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.
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)
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)
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.
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 &)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool isEHPad() const
Return true if this basic block is an exception handling block.
LLVM Value Representation.
succ_range successors(Instruction *I)
bool formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI, bool PreserveLCSSA)
Ensure that all exit blocks of the loop are dedicated exits.
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.
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)