40 #define DEBUG_TYPE "loop-simplify"
65 STATISTIC(NumInserted,
"Number of pre-header or exit blocks inserted");
66 STATISTIC(NumNested ,
"Number of nested loops split out");
69 struct LoopSimplify :
public LoopPass {
99 void verifyAnalysis()
const;
116 "Canonicalize natural loops",
true,
false)
131 bool Changed =
false;
132 LI = &getAnalysis<LoopInfo>();
133 AA = getAnalysisIfAvailable<AliasAnalysis>();
134 DT = &getAnalysis<DominatorTree>();
135 SE = getAnalysisIfAvailable<ScalarEvolution>();
137 Changed |= ProcessLoop(L, LPM);
146 bool Changed =
false;
159 PE =
pred_end(*BB); PI != PE; ++PI) {
167 E = BadPreds.
end();
I != E; ++
I) {
169 DEBUG(
dbgs() <<
"LoopSimplify: Deleting edge from dead predecessor "
170 << (*I)->getName() <<
"\n");
174 (*SI)->removePredecessor(*
I);
178 (*I)->getTerminator()->eraseFromParent();
190 E = ExitingBlocks.
end();
I != E; ++
I)
191 if (
BranchInst *BI = dyn_cast<BranchInst>((*I)->getTerminator()))
192 if (BI->isConditional()) {
193 if (
UndefValue *Cond = dyn_cast<UndefValue>(BI->getCondition())) {
195 DEBUG(
dbgs() <<
"LoopSimplify: Resolving \"br i1 undef\" to exit in "
196 << (*I)->getName() <<
"\n");
199 !L->
contains(BI->getSuccessor(0))));
229 E = ExitBlockSet.end();
I != E; ++
I) {
236 if (RewriteLoopExitBlock(L, ExitBlock)) {
252 if (SeparateNestedLoop(L, LPM, Preheader)) {
264 LoopLatch = InsertUniqueBackedgeBlock(L, Preheader);
278 if (AA) AA->deleteValue(PN);
279 if (SE) SE->forgetValue(PN);
293 bool UniqueExit =
true;
294 if (!ExitBlocks.
empty())
295 for (
unsigned i = 1, e = ExitBlocks.
size(); i != e; ++i)
296 if (ExitBlocks[i] != ExitBlocks[0]) {
301 for (
unsigned i = 0, e = ExitingBlocks.
size(); i != e; ++i) {
307 if (!CI || CI->
getParent() != ExitingBlock)
continue;
311 bool AllInvariant =
true;
315 if (isa<DbgInfoIntrinsic>(Inst))
321 AllInvariant =
false;
325 if (!AllInvariant)
continue;
334 DEBUG(
dbgs() <<
"LoopSimplify: Eliminating exiting block "
335 << ExitingBlock->
getName() <<
"\n");
347 LI->removeBlock(ExitingBlock);
350 const std::vector<DomTreeNodeBase<BasicBlock> *> &Children =
352 while (!Children.empty()) {
354 DT->changeImmediateDominator(Child, Node->
getIDom());
356 DT->eraseNode(ExitingBlock);
398 ".split-lp", PP, NewBBs);
399 PreheaderBB = NewBBs[0];
404 DEBUG(
dbgs() <<
"LoopSimplify: Creating pre-header "
405 << PreheaderBB->
getName() <<
"\n");
429 assert(!LoopBlocks.
empty() &&
"No edges coming in from outside the loop?");
436 ".loopexit",
".nonloopexit",
438 NewExitBB = NewBBs[0];
443 DEBUG(
dbgs() <<
"LoopSimplify: Creating dedicated exit block "
444 << NewExitBB->getName() <<
"\n");
452 std::set<BasicBlock*> &Blocks) {
453 std::vector<BasicBlock *> WorkList;
454 WorkList.push_back(InputBB);
457 if (Blocks.insert(BB).second && BB != StopBlock)
462 WorkList.push_back(WBB);
464 }
while(!WorkList.empty());
500 for (
unsigned i = 0, e = SplitPreds.
size(); i != e; ++i) {
501 if (&*BBI == SplitPreds[i])
512 for (
unsigned i = 0, e = SplitPreds.
size(); i != e; ++i) {
516 FoundBB = SplitPreds[i];
525 FoundBB = SplitPreds[0];
554 assert(!L->
getHeader()->isLandingPad() &&
555 "Can't insert backedge to landing pad");
558 if (PN == 0)
return 0;
564 for (
unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
565 if (PN->getIncomingValue(i) != PN ||
566 !L->
contains(PN->getIncomingBlock(i))) {
568 if (isa<IndirectBrInst>(PN->getIncomingBlock(i)->getTerminator()))
570 OuterLoopPreds.
push_back(PN->getIncomingBlock(i));
573 DEBUG(
dbgs() <<
"LoopSimplify: Splitting out a new outer loop\n");
594 Parent->replaceChildLoopWith(L, NewOuter);
596 LI->changeTopLevelLoop(L, NewOuter);
614 std::set<BasicBlock*> BlocksInL;
617 if (DT->dominates(Header, P))
623 const std::vector<Loop*> &SubLoops = L->
getSubLoops();
624 for (
size_t I = 0;
I != SubLoops.size(); )
625 if (BlocksInL.count(SubLoops[
I]->getHeader()))
632 for (
unsigned i = 0; i != L->
getBlocks().size(); ++i) {
634 if (!BlocksInL.count(BB)) {
638 LI->changeLoopFor(BB, NewOuter);
654 LoopSimplify::InsertUniqueBackedgeBlock(
Loop *L,
BasicBlock *Preheader) {
666 assert(!Header->isLandingPad() &&
"Can't insert backedge to landing pad");
669 std::vector<BasicBlock*> BackedgeBlocks;
677 if (P != Preheader) BackedgeBlocks.push_back(P);
682 Header->getName()+
".backedge",
F);
685 DEBUG(
dbgs() <<
"LoopSimplify: Inserting unique backedge block "
686 << BEBlock->
getName() <<
"\n");
697 PN->
getName()+
".be", BETerminator);
698 if (AA) AA->copyValue(PN, NewPN);
702 unsigned PreheaderIdx = ~0U;
703 bool HasUniqueIncomingValue =
true;
704 Value *UniqueValue = 0;
708 if (IBB == Preheader) {
711 NewPN->addIncoming(IV, IBB);
712 if (HasUniqueIncomingValue) {
713 if (UniqueValue == 0)
715 else if (UniqueValue != IV)
716 HasUniqueIncomingValue =
false;
722 assert(PreheaderIdx != ~0U &&
"PHI has no preheader entry??");
723 if (PreheaderIdx != 0) {
737 if (HasUniqueIncomingValue) {
738 NewPN->replaceAllUsesWith(UniqueValue);
739 if (AA) AA->deleteValue(NewPN);
746 for (
unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
760 DT->splitBlock(BEBlock);
765 void LoopSimplify::verifyAnalysis()
const {
773 bool HasIndBrPred =
false;
776 if (isa<IndirectBrInst>((*PI)->getTerminator())) {
780 assert(HasIndBrPred &&
781 "LoopSimplify has no excuse for missing loop header info!");
787 bool HasIndBrExiting =
false;
790 for (
unsigned i = 0, e = ExitingBlocks.
size(); i != e; ++i) {
791 if (isa<IndirectBrInst>((ExitingBlocks[i])->getTerminator())) {
792 HasIndBrExiting =
true;
797 assert(HasIndBrExiting &&
798 "LoopSimplify has no excuse for missing exit block info!");
799 (void)HasIndBrExiting;
unsigned getNumBackEdges() const
void push_back(const T &Elt)
loop Canonicalize natural loops
Pass * createLoopSimplifyPass()
Abstract base class of comparison instructions.
AnalysisUsage & addPreserved()
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)
static PassRegistry * getPassRegistry()
const Instruction & back() const
static void PlaceSplitBlockCarefully(BasicBlock *NewBB, SmallVectorImpl< BasicBlock * > &SplitPreds, Loop *L)
enable_if_c<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
static PHINode * FindPHIToPartitionLoops(Loop *L, DominatorTree *DT, AliasAnalysis *AA, LoopInfo *LI)
LoopT * getParentLoop() const
const Function * getParent() const
Return the enclosing method, or null if none.
const std::vector< BlockT * > & getBlocks() const
void setDebugLoc(const DebugLoc &Loc)
setDebugLoc - Set the debug location information for this instruction.
BlockT * getHeader() const
LoopInfoBase< BlockT, LoopT > * LI
LoopT * removeChildLoop(iterator I)
StringRef getName() const
BlockT * getLoopLatch() const
DomTreeNodeBase< NodeT > * getIDom() const
static void AddBlockAndPredsToSet(BasicBlock *InputBB, BasicBlock *StopBlock, std::set< BasicBlock * > &Blocks)
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
BasicBlock * InsertPreheaderForLoop(Loop *L, Pass *P)
INITIALIZE_PASS_BEGIN(LoopSimplify,"loop-simplify","Canonicalize natural loops", true, false) INITIALIZE_PASS_END(LoopSimplify
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Instruction * getFirstNonPHI()
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=0)
void getExitingBlocks(SmallVectorImpl< BlockT * > &ExitingBlocks) const
ID
LLVM Calling Convention Representation.
void getExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Interval::succ_iterator succ_begin(Interval *I)
BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, Pass *P=0)
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
bool LLVM_ATTRIBUTE_UNUSED_RESULT empty() const
void addChildLoop(LoopT *NewChild)
BasicBlock * getSuccessor(unsigned i) const
void insertLoopIntoQueue(Loop *L)
AnalysisUsage & addPreservedID(const void *ID)
void setSuccessor(unsigned idx, BasicBlock *B)
void replaceAllUsesWith(Value *V)
unsigned getNumIncomingValues() const
Interval::succ_iterator succ_end(Interval *I)
unsigned getNumSuccessors() const
BlockT * getLoopPreheader() const
LLVM Basic Block Representation.
BasicBlock * getSuccessor(unsigned idx) const
char & BreakCriticalEdgesID
Instr is a loop (backwards branch).
Interval::pred_iterator pred_begin(Interval *I)
const DebugLoc & getDebugLoc() const
getDebugLoc - Return the debug location for this node as a DebugLoc.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=0)
BasicBlock * getIncomingBlock(unsigned i) const
bool contains(const LoopT *L) const
const InstListType & getInstList() const
Return the underlying instruction list container.
bool makeLoopInvariant(Value *V, bool &Changed, Instruction *InsertPt=0) const
Interval::pred_iterator pred_end(Interval *I)
void addBlockEntry(BlockT *BB)
bool hasDedicatedExits() const
static UndefValue * get(Type *T)
virtual void deleteValue(Value *V)
Value * SimplifyInstruction(Instruction *I, const DataLayout *TD=0, const TargetLibraryInfo *TLI=0, const DominatorTree *DT=0)
iterator erase(iterator where)
void removeBlockFromLoop(BlockT *BB)
bool FoldBranchToCommonDest(BranchInst *BI)
const std::vector< DomTreeNodeBase< NodeT > * > & getChildren() const
bool isConditional() const
SmallPtrSetIterator - This implements a const_iterator for SmallPtrSet.
A SetVector that performs no allocations if smaller than a certain size.
void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
const BasicBlockListType & getBasicBlockList() const
void setIncomingBlock(unsigned i, BasicBlock *BB)
Value * getIncomingValue(unsigned i) const
void eraseFromParent()
Unlink 'this' from the containing function and delete it.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
void splice(iterator where, iplist &L2)
raw_ostream & dbgs()
dbgs - Return a circular-buffered debug stream.
STATISTIC(NumInserted,"Number of pre-header or exit blocks inserted")
BasicBlock * getSinglePredecessor()
Return this block if it has a single predecessor block. Otherwise return a null pointer.
std::vector< BlockT * >::const_iterator block_iterator
block_iterator block_end() const
Value * getCondition() const
void moveToHeader(BlockT *BB)
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
bool isLandingPad() const
Return true if this basic block is a landing pad.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=0, BasicBlock *InsertBefore=0)
Creates a new BasicBlock.
void initializeLoopSimplifyPass(PassRegistry &)
LLVM Value Representation.
const std::vector< LoopT * > & getSubLoops() const
block_iterator block_begin() const
loop Canonicalize natural true
void SplitLandingPadPredecessors(BasicBlock *OrigBB, ArrayRef< BasicBlock * > Preds, const char *Suffix, const char *Suffix2, Pass *P, SmallVectorImpl< BasicBlock * > &NewBBs)
void setIncomingValue(unsigned i, Value *V)
const BasicBlock * getParent() const