LLVM  mainline
LoopSimplify.cpp
Go to the documentation of this file.
00001 //===- LoopSimplify.cpp - Loop Canonicalization Pass ----------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass performs several transformations to transform natural loops into a
00011 // simpler form, which makes subsequent analyses and transformations simpler and
00012 // more effective.
00013 //
00014 // Loop pre-header insertion guarantees that there is a single, non-critical
00015 // entry edge from outside of the loop to the loop header.  This simplifies a
00016 // number of analyses and transformations, such as LICM.
00017 //
00018 // Loop exit-block insertion guarantees that all exit blocks from the loop
00019 // (blocks which are outside of the loop that have predecessors inside of the
00020 // loop) only have predecessors from inside of the loop (and are thus dominated
00021 // by the loop header).  This simplifies transformations such as store-sinking
00022 // that are built into LICM.
00023 //
00024 // This pass also guarantees that loops will have exactly one backedge.
00025 //
00026 // Indirectbr instructions introduce several complications. If the loop
00027 // contains or is entered by an indirectbr instruction, it may not be possible
00028 // to transform the loop and make these guarantees. Client code should check
00029 // that these conditions are true before relying on them.
00030 //
00031 // Note that the simplifycfg pass will clean up blocks which are split out but
00032 // end up being unnecessary, so usage of this pass should not pessimize
00033 // generated code.
00034 //
00035 // This pass obviously modifies the CFG, but updates loop information and
00036 // dominator information.
00037 //
00038 //===----------------------------------------------------------------------===//
00039 
00040 #include "llvm/Transforms/Scalar.h"
00041 #include "llvm/ADT/DepthFirstIterator.h"
00042 #include "llvm/ADT/SetOperations.h"
00043 #include "llvm/ADT/SetVector.h"
00044 #include "llvm/ADT/SmallVector.h"
00045 #include "llvm/ADT/Statistic.h"
00046 #include "llvm/Analysis/AliasAnalysis.h"
00047 #include "llvm/Analysis/AssumptionCache.h"
00048 #include "llvm/Analysis/DependenceAnalysis.h"
00049 #include "llvm/Analysis/InstructionSimplify.h"
00050 #include "llvm/Analysis/LoopInfo.h"
00051 #include "llvm/Analysis/ScalarEvolution.h"
00052 #include "llvm/IR/CFG.h"
00053 #include "llvm/IR/Constants.h"
00054 #include "llvm/IR/DataLayout.h"
00055 #include "llvm/IR/Dominators.h"
00056 #include "llvm/IR/Function.h"
00057 #include "llvm/IR/Instructions.h"
00058 #include "llvm/IR/IntrinsicInst.h"
00059 #include "llvm/IR/LLVMContext.h"
00060 #include "llvm/IR/Module.h"
00061 #include "llvm/IR/Type.h"
00062 #include "llvm/Support/Debug.h"
00063 #include "llvm/Support/raw_ostream.h"
00064 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00065 #include "llvm/Transforms/Utils/Local.h"
00066 #include "llvm/Transforms/Utils/LoopUtils.h"
00067 using namespace llvm;
00068 
00069 #define DEBUG_TYPE "loop-simplify"
00070 
00071 STATISTIC(NumInserted, "Number of pre-header or exit blocks inserted");
00072 STATISTIC(NumNested  , "Number of nested loops split out");
00073 
00074 // If the block isn't already, move the new block to right after some 'outside
00075 // block' block.  This prevents the preheader from being placed inside the loop
00076 // body, e.g. when the loop hasn't been rotated.
00077 static void placeSplitBlockCarefully(BasicBlock *NewBB,
00078                                      SmallVectorImpl<BasicBlock *> &SplitPreds,
00079                                      Loop *L) {
00080   // Check to see if NewBB is already well placed.
00081   Function::iterator BBI = NewBB; --BBI;
00082   for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
00083     if (&*BBI == SplitPreds[i])
00084       return;
00085   }
00086 
00087   // If it isn't already after an outside block, move it after one.  This is
00088   // always good as it makes the uncond branch from the outside block into a
00089   // fall-through.
00090 
00091   // Figure out *which* outside block to put this after.  Prefer an outside
00092   // block that neighbors a BB actually in the loop.
00093   BasicBlock *FoundBB = nullptr;
00094   for (unsigned i = 0, e = SplitPreds.size(); i != e; ++i) {
00095     Function::iterator BBI = SplitPreds[i];
00096     if (++BBI != NewBB->getParent()->end() &&
00097         L->contains(BBI)) {
00098       FoundBB = SplitPreds[i];
00099       break;
00100     }
00101   }
00102 
00103   // If our heuristic for a *good* bb to place this after doesn't find
00104   // anything, just pick something.  It's likely better than leaving it within
00105   // the loop.
00106   if (!FoundBB)
00107     FoundBB = SplitPreds[0];
00108   NewBB->moveAfter(FoundBB);
00109 }
00110 
00111 /// InsertPreheaderForLoop - Once we discover that a loop doesn't have a
00112 /// preheader, this method is called to insert one.  This method has two phases:
00113 /// preheader insertion and analysis updating.
00114 ///
00115 BasicBlock *llvm::InsertPreheaderForLoop(Loop *L, Pass *PP) {
00116   BasicBlock *Header = L->getHeader();
00117 
00118   // Get analyses that we try to update.
00119   auto *AA = PP->getAnalysisIfAvailable<AliasAnalysis>();
00120   auto *DTWP = PP->getAnalysisIfAvailable<DominatorTreeWrapperPass>();
00121   auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
00122   auto *LIWP = PP->getAnalysisIfAvailable<LoopInfoWrapperPass>();
00123   auto *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
00124   bool PreserveLCSSA = PP->mustPreserveAnalysisID(LCSSAID);
00125 
00126   // Compute the set of predecessors of the loop that are not in the loop.
00127   SmallVector<BasicBlock*, 8> OutsideBlocks;
00128   for (pred_iterator PI = pred_begin(Header), PE = pred_end(Header);
00129        PI != PE; ++PI) {
00130     BasicBlock *P = *PI;
00131     if (!L->contains(P)) {         // Coming in from outside the loop?
00132       // If the loop is branched to from an indirect branch, we won't
00133       // be able to fully transform the loop, because it prohibits
00134       // edge splitting.
00135       if (isa<IndirectBrInst>(P->getTerminator())) return nullptr;
00136 
00137       // Keep track of it.
00138       OutsideBlocks.push_back(P);
00139     }
00140   }
00141 
00142   // Split out the loop pre-header.
00143   BasicBlock *PreheaderBB;
00144   PreheaderBB = SplitBlockPredecessors(Header, OutsideBlocks, ".preheader",
00145                                        AA, DT, LI, PreserveLCSSA);
00146 
00147   DEBUG(dbgs() << "LoopSimplify: Creating pre-header "
00148                << PreheaderBB->getName() << "\n");
00149 
00150   // Make sure that NewBB is put someplace intelligent, which doesn't mess up
00151   // code layout too horribly.
00152   placeSplitBlockCarefully(PreheaderBB, OutsideBlocks, L);
00153 
00154   return PreheaderBB;
00155 }
00156 
00157 /// \brief Ensure that the loop preheader dominates all exit blocks.
00158 ///
00159 /// This method is used to split exit blocks that have predecessors outside of
00160 /// the loop.
00161 static BasicBlock *rewriteLoopExitBlock(Loop *L, BasicBlock *Exit,
00162                                         AliasAnalysis *AA, DominatorTree *DT,
00163                                         LoopInfo *LI, Pass *PP) {
00164   SmallVector<BasicBlock*, 8> LoopBlocks;
00165   for (pred_iterator I = pred_begin(Exit), E = pred_end(Exit); I != E; ++I) {
00166     BasicBlock *P = *I;
00167     if (L->contains(P)) {
00168       // Don't do this if the loop is exited via an indirect branch.
00169       if (isa<IndirectBrInst>(P->getTerminator())) return nullptr;
00170 
00171       LoopBlocks.push_back(P);
00172     }
00173   }
00174 
00175   assert(!LoopBlocks.empty() && "No edges coming in from outside the loop?");
00176   BasicBlock *NewExitBB = nullptr;
00177 
00178   bool PreserveLCSSA = PP->mustPreserveAnalysisID(LCSSAID);
00179 
00180   NewExitBB = SplitBlockPredecessors(Exit, LoopBlocks, ".loopexit", AA, DT,
00181                                      LI, PreserveLCSSA);
00182 
00183   DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
00184                << NewExitBB->getName() << "\n");
00185   return NewExitBB;
00186 }
00187 
00188 /// Add the specified block, and all of its predecessors, to the specified set,
00189 /// if it's not already in there.  Stop predecessor traversal when we reach
00190 /// StopBlock.
00191 static void addBlockAndPredsToSet(BasicBlock *InputBB, BasicBlock *StopBlock,
00192                                   std::set<BasicBlock*> &Blocks) {
00193   SmallVector<BasicBlock *, 8> Worklist;
00194   Worklist.push_back(InputBB);
00195   do {
00196     BasicBlock *BB = Worklist.pop_back_val();
00197     if (Blocks.insert(BB).second && BB != StopBlock)
00198       // If BB is not already processed and it is not a stop block then
00199       // insert its predecessor in the work list
00200       for (pred_iterator I = pred_begin(BB), E = pred_end(BB); I != E; ++I) {
00201         BasicBlock *WBB = *I;
00202         Worklist.push_back(WBB);
00203       }
00204   } while (!Worklist.empty());
00205 }
00206 
00207 /// \brief The first part of loop-nestification is to find a PHI node that tells
00208 /// us how to partition the loops.
00209 static PHINode *findPHIToPartitionLoops(Loop *L, AliasAnalysis *AA,
00210                                         DominatorTree *DT,
00211                                         AssumptionCache *AC) {
00212   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
00213   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ) {
00214     PHINode *PN = cast<PHINode>(I);
00215     ++I;
00216     if (Value *V = SimplifyInstruction(PN, DL, nullptr, DT, AC)) {
00217       // This is a degenerate PHI already, don't modify it!
00218       PN->replaceAllUsesWith(V);
00219       if (AA) AA->deleteValue(PN);
00220       PN->eraseFromParent();
00221       continue;
00222     }
00223 
00224     // Scan this PHI node looking for a use of the PHI node by itself.
00225     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00226       if (PN->getIncomingValue(i) == PN &&
00227           L->contains(PN->getIncomingBlock(i)))
00228         // We found something tasty to remove.
00229         return PN;
00230   }
00231   return nullptr;
00232 }
00233 
00234 /// \brief If this loop has multiple backedges, try to pull one of them out into
00235 /// a nested loop.
00236 ///
00237 /// This is important for code that looks like
00238 /// this:
00239 ///
00240 ///  Loop:
00241 ///     ...
00242 ///     br cond, Loop, Next
00243 ///     ...
00244 ///     br cond2, Loop, Out
00245 ///
00246 /// To identify this common case, we look at the PHI nodes in the header of the
00247 /// loop.  PHI nodes with unchanging values on one backedge correspond to values
00248 /// that change in the "outer" loop, but not in the "inner" loop.
00249 ///
00250 /// If we are able to separate out a loop, return the new outer loop that was
00251 /// created.
00252 ///
00253 static Loop *separateNestedLoop(Loop *L, BasicBlock *Preheader,
00254                                 AliasAnalysis *AA, DominatorTree *DT,
00255                                 LoopInfo *LI, ScalarEvolution *SE, Pass *PP,
00256                                 AssumptionCache *AC) {
00257   // Don't try to separate loops without a preheader.
00258   if (!Preheader)
00259     return nullptr;
00260 
00261   // The header is not a landing pad; preheader insertion should ensure this.
00262   assert(!L->getHeader()->isLandingPad() &&
00263          "Can't insert backedge to landing pad");
00264 
00265   PHINode *PN = findPHIToPartitionLoops(L, AA, DT, AC);
00266   if (!PN) return nullptr;  // No known way to partition.
00267 
00268   // Pull out all predecessors that have varying values in the loop.  This
00269   // handles the case when a PHI node has multiple instances of itself as
00270   // arguments.
00271   SmallVector<BasicBlock*, 8> OuterLoopPreds;
00272   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00273     if (PN->getIncomingValue(i) != PN ||
00274         !L->contains(PN->getIncomingBlock(i))) {
00275       // We can't split indirectbr edges.
00276       if (isa<IndirectBrInst>(PN->getIncomingBlock(i)->getTerminator()))
00277         return nullptr;
00278       OuterLoopPreds.push_back(PN->getIncomingBlock(i));
00279     }
00280   }
00281   DEBUG(dbgs() << "LoopSimplify: Splitting out a new outer loop\n");
00282 
00283   // If ScalarEvolution is around and knows anything about values in
00284   // this loop, tell it to forget them, because we're about to
00285   // substantially change it.
00286   if (SE)
00287     SE->forgetLoop(L);
00288 
00289   bool PreserveLCSSA = PP->mustPreserveAnalysisID(LCSSAID);
00290 
00291   BasicBlock *Header = L->getHeader();
00292   BasicBlock *NewBB = SplitBlockPredecessors(Header, OuterLoopPreds, ".outer",
00293                                              AA, DT, LI, PreserveLCSSA);
00294 
00295   // Make sure that NewBB is put someplace intelligent, which doesn't mess up
00296   // code layout too horribly.
00297   placeSplitBlockCarefully(NewBB, OuterLoopPreds, L);
00298 
00299   // Create the new outer loop.
00300   Loop *NewOuter = new Loop();
00301 
00302   // Change the parent loop to use the outer loop as its child now.
00303   if (Loop *Parent = L->getParentLoop())
00304     Parent->replaceChildLoopWith(L, NewOuter);
00305   else
00306     LI->changeTopLevelLoop(L, NewOuter);
00307 
00308   // L is now a subloop of our outer loop.
00309   NewOuter->addChildLoop(L);
00310 
00311   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
00312        I != E; ++I)
00313     NewOuter->addBlockEntry(*I);
00314 
00315   // Now reset the header in L, which had been moved by
00316   // SplitBlockPredecessors for the outer loop.
00317   L->moveToHeader(Header);
00318 
00319   // Determine which blocks should stay in L and which should be moved out to
00320   // the Outer loop now.
00321   std::set<BasicBlock*> BlocksInL;
00322   for (pred_iterator PI=pred_begin(Header), E = pred_end(Header); PI!=E; ++PI) {
00323     BasicBlock *P = *PI;
00324     if (DT->dominates(Header, P))
00325       addBlockAndPredsToSet(P, Header, BlocksInL);
00326   }
00327 
00328   // Scan all of the loop children of L, moving them to OuterLoop if they are
00329   // not part of the inner loop.
00330   const std::vector<Loop*> &SubLoops = L->getSubLoops();
00331   for (size_t I = 0; I != SubLoops.size(); )
00332     if (BlocksInL.count(SubLoops[I]->getHeader()))
00333       ++I;   // Loop remains in L
00334     else
00335       NewOuter->addChildLoop(L->removeChildLoop(SubLoops.begin() + I));
00336 
00337   // Now that we know which blocks are in L and which need to be moved to
00338   // OuterLoop, move any blocks that need it.
00339   for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
00340     BasicBlock *BB = L->getBlocks()[i];
00341     if (!BlocksInL.count(BB)) {
00342       // Move this block to the parent, updating the exit blocks sets
00343       L->removeBlockFromLoop(BB);
00344       if ((*LI)[BB] == L)
00345         LI->changeLoopFor(BB, NewOuter);
00346       --i;
00347     }
00348   }
00349 
00350   return NewOuter;
00351 }
00352 
00353 /// \brief This method is called when the specified loop has more than one
00354 /// backedge in it.
00355 ///
00356 /// If this occurs, revector all of these backedges to target a new basic block
00357 /// and have that block branch to the loop header.  This ensures that loops
00358 /// have exactly one backedge.
00359 static BasicBlock *insertUniqueBackedgeBlock(Loop *L, BasicBlock *Preheader,
00360                                              AliasAnalysis *AA,
00361                                              DominatorTree *DT, LoopInfo *LI) {
00362   assert(L->getNumBackEdges() > 1 && "Must have > 1 backedge!");
00363 
00364   // Get information about the loop
00365   BasicBlock *Header = L->getHeader();
00366   Function *F = Header->getParent();
00367 
00368   // Unique backedge insertion currently depends on having a preheader.
00369   if (!Preheader)
00370     return nullptr;
00371 
00372   // The header is not a landing pad; preheader insertion should ensure this.
00373   assert(!Header->isLandingPad() && "Can't insert backedge to landing pad");
00374 
00375   // Figure out which basic blocks contain back-edges to the loop header.
00376   std::vector<BasicBlock*> BackedgeBlocks;
00377   for (pred_iterator I = pred_begin(Header), E = pred_end(Header); I != E; ++I){
00378     BasicBlock *P = *I;
00379 
00380     // Indirectbr edges cannot be split, so we must fail if we find one.
00381     if (isa<IndirectBrInst>(P->getTerminator()))
00382       return nullptr;
00383 
00384     if (P != Preheader) BackedgeBlocks.push_back(P);
00385   }
00386 
00387   // Create and insert the new backedge block...
00388   BasicBlock *BEBlock = BasicBlock::Create(Header->getContext(),
00389                                            Header->getName()+".backedge", F);
00390   BranchInst *BETerminator = BranchInst::Create(Header, BEBlock);
00391 
00392   DEBUG(dbgs() << "LoopSimplify: Inserting unique backedge block "
00393                << BEBlock->getName() << "\n");
00394 
00395   // Move the new backedge block to right after the last backedge block.
00396   Function::iterator InsertPos = BackedgeBlocks.back(); ++InsertPos;
00397   F->getBasicBlockList().splice(InsertPos, F->getBasicBlockList(), BEBlock);
00398 
00399   // Now that the block has been inserted into the function, create PHI nodes in
00400   // the backedge block which correspond to any PHI nodes in the header block.
00401   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
00402     PHINode *PN = cast<PHINode>(I);
00403     PHINode *NewPN = PHINode::Create(PN->getType(), BackedgeBlocks.size(),
00404                                      PN->getName()+".be", BETerminator);
00405     if (AA) AA->copyValue(PN, NewPN);
00406 
00407     // Loop over the PHI node, moving all entries except the one for the
00408     // preheader over to the new PHI node.
00409     unsigned PreheaderIdx = ~0U;
00410     bool HasUniqueIncomingValue = true;
00411     Value *UniqueValue = nullptr;
00412     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00413       BasicBlock *IBB = PN->getIncomingBlock(i);
00414       Value *IV = PN->getIncomingValue(i);
00415       if (IBB == Preheader) {
00416         PreheaderIdx = i;
00417       } else {
00418         NewPN->addIncoming(IV, IBB);
00419         if (HasUniqueIncomingValue) {
00420           if (!UniqueValue)
00421             UniqueValue = IV;
00422           else if (UniqueValue != IV)
00423             HasUniqueIncomingValue = false;
00424         }
00425       }
00426     }
00427 
00428     // Delete all of the incoming values from the old PN except the preheader's
00429     assert(PreheaderIdx != ~0U && "PHI has no preheader entry??");
00430     if (PreheaderIdx != 0) {
00431       PN->setIncomingValue(0, PN->getIncomingValue(PreheaderIdx));
00432       PN->setIncomingBlock(0, PN->getIncomingBlock(PreheaderIdx));
00433     }
00434     // Nuke all entries except the zero'th.
00435     for (unsigned i = 0, e = PN->getNumIncomingValues()-1; i != e; ++i)
00436       PN->removeIncomingValue(e-i, false);
00437 
00438     // Finally, add the newly constructed PHI node as the entry for the BEBlock.
00439     PN->addIncoming(NewPN, BEBlock);
00440 
00441     // As an optimization, if all incoming values in the new PhiNode (which is a
00442     // subset of the incoming values of the old PHI node) have the same value,
00443     // eliminate the PHI Node.
00444     if (HasUniqueIncomingValue) {
00445       NewPN->replaceAllUsesWith(UniqueValue);
00446       if (AA) AA->deleteValue(NewPN);
00447       BEBlock->getInstList().erase(NewPN);
00448     }
00449   }
00450 
00451   // Now that all of the PHI nodes have been inserted and adjusted, modify the
00452   // backedge blocks to just to the BEBlock instead of the header.
00453   for (unsigned i = 0, e = BackedgeBlocks.size(); i != e; ++i) {
00454     TerminatorInst *TI = BackedgeBlocks[i]->getTerminator();
00455     for (unsigned Op = 0, e = TI->getNumSuccessors(); Op != e; ++Op)
00456       if (TI->getSuccessor(Op) == Header)
00457         TI->setSuccessor(Op, BEBlock);
00458   }
00459 
00460   //===--- Update all analyses which we must preserve now -----------------===//
00461 
00462   // Update Loop Information - we know that this block is now in the current
00463   // loop and all parent loops.
00464   L->addBasicBlockToLoop(BEBlock, *LI);
00465 
00466   // Update dominator information
00467   DT->splitBlock(BEBlock);
00468 
00469   return BEBlock;
00470 }
00471 
00472 /// \brief Simplify one loop and queue further loops for simplification.
00473 ///
00474 /// FIXME: Currently this accepts both lots of analyses that it uses and a raw
00475 /// Pass pointer. The Pass pointer is used by numerous utilities to update
00476 /// specific analyses. Rather than a pass it would be much cleaner and more
00477 /// explicit if they accepted the analysis directly and then updated it.
00478 static bool simplifyOneLoop(Loop *L, SmallVectorImpl<Loop *> &Worklist,
00479                             AliasAnalysis *AA, DominatorTree *DT, LoopInfo *LI,
00480                             ScalarEvolution *SE, Pass *PP,
00481                             AssumptionCache *AC) {
00482   bool Changed = false;
00483 ReprocessLoop:
00484 
00485   // Check to see that no blocks (other than the header) in this loop have
00486   // predecessors that are not in the loop.  This is not valid for natural
00487   // loops, but can occur if the blocks are unreachable.  Since they are
00488   // unreachable we can just shamelessly delete those CFG edges!
00489   for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
00490        BB != E; ++BB) {
00491     if (*BB == L->getHeader()) continue;
00492 
00493     SmallPtrSet<BasicBlock*, 4> BadPreds;
00494     for (pred_iterator PI = pred_begin(*BB),
00495          PE = pred_end(*BB); PI != PE; ++PI) {
00496       BasicBlock *P = *PI;
00497       if (!L->contains(P))
00498         BadPreds.insert(P);
00499     }
00500 
00501     // Delete each unique out-of-loop (and thus dead) predecessor.
00502     for (BasicBlock *P : BadPreds) {
00503 
00504       DEBUG(dbgs() << "LoopSimplify: Deleting edge from dead predecessor "
00505                    << P->getName() << "\n");
00506 
00507       // Inform each successor of each dead pred.
00508       for (succ_iterator SI = succ_begin(P), SE = succ_end(P); SI != SE; ++SI)
00509         (*SI)->removePredecessor(P);
00510       // Zap the dead pred's terminator and replace it with unreachable.
00511       TerminatorInst *TI = P->getTerminator();
00512        TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
00513       P->getTerminator()->eraseFromParent();
00514       new UnreachableInst(P->getContext(), P);
00515       Changed = true;
00516     }
00517   }
00518 
00519   // If there are exiting blocks with branches on undef, resolve the undef in
00520   // the direction which will exit the loop. This will help simplify loop
00521   // trip count computations.
00522   SmallVector<BasicBlock*, 8> ExitingBlocks;
00523   L->getExitingBlocks(ExitingBlocks);
00524   for (SmallVectorImpl<BasicBlock *>::iterator I = ExitingBlocks.begin(),
00525        E = ExitingBlocks.end(); I != E; ++I)
00526     if (BranchInst *BI = dyn_cast<BranchInst>((*I)->getTerminator()))
00527       if (BI->isConditional()) {
00528         if (UndefValue *Cond = dyn_cast<UndefValue>(BI->getCondition())) {
00529 
00530           DEBUG(dbgs() << "LoopSimplify: Resolving \"br i1 undef\" to exit in "
00531                        << (*I)->getName() << "\n");
00532 
00533           BI->setCondition(ConstantInt::get(Cond->getType(),
00534                                             !L->contains(BI->getSuccessor(0))));
00535 
00536           // This may make the loop analyzable, force SCEV recomputation.
00537           if (SE)
00538             SE->forgetLoop(L);
00539 
00540           Changed = true;
00541         }
00542       }
00543 
00544   // Does the loop already have a preheader?  If so, don't insert one.
00545   BasicBlock *Preheader = L->getLoopPreheader();
00546   if (!Preheader) {
00547     Preheader = InsertPreheaderForLoop(L, PP);
00548     if (Preheader) {
00549       ++NumInserted;
00550       Changed = true;
00551     }
00552   }
00553 
00554   // Next, check to make sure that all exit nodes of the loop only have
00555   // predecessors that are inside of the loop.  This check guarantees that the
00556   // loop preheader/header will dominate the exit blocks.  If the exit block has
00557   // predecessors from outside of the loop, split the edge now.
00558   SmallVector<BasicBlock*, 8> ExitBlocks;
00559   L->getExitBlocks(ExitBlocks);
00560 
00561   SmallSetVector<BasicBlock *, 8> ExitBlockSet(ExitBlocks.begin(),
00562                                                ExitBlocks.end());
00563   for (SmallSetVector<BasicBlock *, 8>::iterator I = ExitBlockSet.begin(),
00564          E = ExitBlockSet.end(); I != E; ++I) {
00565     BasicBlock *ExitBlock = *I;
00566     for (pred_iterator PI = pred_begin(ExitBlock), PE = pred_end(ExitBlock);
00567          PI != PE; ++PI)
00568       // Must be exactly this loop: no subloops, parent loops, or non-loop preds
00569       // allowed.
00570       if (!L->contains(*PI)) {
00571         if (rewriteLoopExitBlock(L, ExitBlock, AA, DT, LI, PP)) {
00572           ++NumInserted;
00573           Changed = true;
00574         }
00575         break;
00576       }
00577   }
00578 
00579   // If the header has more than two predecessors at this point (from the
00580   // preheader and from multiple backedges), we must adjust the loop.
00581   BasicBlock *LoopLatch = L->getLoopLatch();
00582   if (!LoopLatch) {
00583     // If this is really a nested loop, rip it out into a child loop.  Don't do
00584     // this for loops with a giant number of backedges, just factor them into a
00585     // common backedge instead.
00586     if (L->getNumBackEdges() < 8) {
00587       if (Loop *OuterL =
00588               separateNestedLoop(L, Preheader, AA, DT, LI, SE, PP, AC)) {
00589         ++NumNested;
00590         // Enqueue the outer loop as it should be processed next in our
00591         // depth-first nest walk.
00592         Worklist.push_back(OuterL);
00593 
00594         // This is a big restructuring change, reprocess the whole loop.
00595         Changed = true;
00596         // GCC doesn't tail recursion eliminate this.
00597         // FIXME: It isn't clear we can't rely on LLVM to TRE this.
00598         goto ReprocessLoop;
00599       }
00600     }
00601 
00602     // If we either couldn't, or didn't want to, identify nesting of the loops,
00603     // insert a new block that all backedges target, then make it jump to the
00604     // loop header.
00605     LoopLatch = insertUniqueBackedgeBlock(L, Preheader, AA, DT, LI);
00606     if (LoopLatch) {
00607       ++NumInserted;
00608       Changed = true;
00609     }
00610   }
00611 
00612   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
00613 
00614   // Scan over the PHI nodes in the loop header.  Since they now have only two
00615   // incoming values (the loop is canonicalized), we may have simplified the PHI
00616   // down to 'X = phi [X, Y]', which should be replaced with 'Y'.
00617   PHINode *PN;
00618   for (BasicBlock::iterator I = L->getHeader()->begin();
00619        (PN = dyn_cast<PHINode>(I++)); )
00620     if (Value *V = SimplifyInstruction(PN, DL, nullptr, DT, AC)) {
00621       if (AA) AA->deleteValue(PN);
00622       if (SE) SE->forgetValue(PN);
00623       PN->replaceAllUsesWith(V);
00624       PN->eraseFromParent();
00625     }
00626 
00627   // If this loop has multiple exits and the exits all go to the same
00628   // block, attempt to merge the exits. This helps several passes, such
00629   // as LoopRotation, which do not support loops with multiple exits.
00630   // SimplifyCFG also does this (and this code uses the same utility
00631   // function), however this code is loop-aware, where SimplifyCFG is
00632   // not. That gives it the advantage of being able to hoist
00633   // loop-invariant instructions out of the way to open up more
00634   // opportunities, and the disadvantage of having the responsibility
00635   // to preserve dominator information.
00636   bool UniqueExit = true;
00637   if (!ExitBlocks.empty())
00638     for (unsigned i = 1, e = ExitBlocks.size(); i != e; ++i)
00639       if (ExitBlocks[i] != ExitBlocks[0]) {
00640         UniqueExit = false;
00641         break;
00642       }
00643   if (UniqueExit) {
00644     for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
00645       BasicBlock *ExitingBlock = ExitingBlocks[i];
00646       if (!ExitingBlock->getSinglePredecessor()) continue;
00647       BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
00648       if (!BI || !BI->isConditional()) continue;
00649       CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition());
00650       if (!CI || CI->getParent() != ExitingBlock) continue;
00651 
00652       // Attempt to hoist out all instructions except for the
00653       // comparison and the branch.
00654       bool AllInvariant = true;
00655       bool AnyInvariant = false;
00656       for (BasicBlock::iterator I = ExitingBlock->begin(); &*I != BI; ) {
00657         Instruction *Inst = I++;
00658         // Skip debug info intrinsics.
00659         if (isa<DbgInfoIntrinsic>(Inst))
00660           continue;
00661         if (Inst == CI)
00662           continue;
00663         if (!L->makeLoopInvariant(Inst, AnyInvariant,
00664                                   Preheader ? Preheader->getTerminator()
00665                                             : nullptr)) {
00666           AllInvariant = false;
00667           break;
00668         }
00669       }
00670       if (AnyInvariant) {
00671         Changed = true;
00672         // The loop disposition of all SCEV expressions that depend on any
00673         // hoisted values have also changed.
00674         if (SE)
00675           SE->forgetLoopDispositions(L);
00676       }
00677       if (!AllInvariant) continue;
00678 
00679       // The block has now been cleared of all instructions except for
00680       // a comparison and a conditional branch. SimplifyCFG may be able
00681       // to fold it now.
00682       if (!FoldBranchToCommonDest(BI))
00683         continue;
00684 
00685       // Success. The block is now dead, so remove it from the loop,
00686       // update the dominator tree and delete it.
00687       DEBUG(dbgs() << "LoopSimplify: Eliminating exiting block "
00688                    << ExitingBlock->getName() << "\n");
00689 
00690       // Notify ScalarEvolution before deleting this block. Currently assume the
00691       // parent loop doesn't change (spliting edges doesn't count). If blocks,
00692       // CFG edges, or other values in the parent loop change, then we need call
00693       // to forgetLoop() for the parent instead.
00694       if (SE)
00695         SE->forgetLoop(L);
00696 
00697       assert(pred_begin(ExitingBlock) == pred_end(ExitingBlock));
00698       Changed = true;
00699       LI->removeBlock(ExitingBlock);
00700 
00701       DomTreeNode *Node = DT->getNode(ExitingBlock);
00702       const std::vector<DomTreeNodeBase<BasicBlock> *> &Children =
00703         Node->getChildren();
00704       while (!Children.empty()) {
00705         DomTreeNode *Child = Children.front();
00706         DT->changeImmediateDominator(Child, Node->getIDom());
00707       }
00708       DT->eraseNode(ExitingBlock);
00709 
00710       BI->getSuccessor(0)->removePredecessor(ExitingBlock);
00711       BI->getSuccessor(1)->removePredecessor(ExitingBlock);
00712       ExitingBlock->eraseFromParent();
00713     }
00714   }
00715 
00716   return Changed;
00717 }
00718 
00719 bool llvm::simplifyLoop(Loop *L, DominatorTree *DT, LoopInfo *LI, Pass *PP,
00720                         AliasAnalysis *AA, ScalarEvolution *SE,
00721                         AssumptionCache *AC) {
00722   bool Changed = false;
00723 
00724   // Worklist maintains our depth-first queue of loops in this nest to process.
00725   SmallVector<Loop *, 4> Worklist;
00726   Worklist.push_back(L);
00727 
00728   // Walk the worklist from front to back, pushing newly found sub loops onto
00729   // the back. This will let us process loops from back to front in depth-first
00730   // order. We can use this simple process because loops form a tree.
00731   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
00732     Loop *L2 = Worklist[Idx];
00733     Worklist.append(L2->begin(), L2->end());
00734   }
00735 
00736   while (!Worklist.empty())
00737     Changed |= simplifyOneLoop(Worklist.pop_back_val(), Worklist, AA, DT, LI,
00738                                SE, PP, AC);
00739 
00740   return Changed;
00741 }
00742 
00743 namespace {
00744   struct LoopSimplify : public FunctionPass {
00745     static char ID; // Pass identification, replacement for typeid
00746     LoopSimplify() : FunctionPass(ID) {
00747       initializeLoopSimplifyPass(*PassRegistry::getPassRegistry());
00748     }
00749 
00750     // AA - If we have an alias analysis object to update, this is it, otherwise
00751     // this is null.
00752     AliasAnalysis *AA;
00753     DominatorTree *DT;
00754     LoopInfo *LI;
00755     ScalarEvolution *SE;
00756     AssumptionCache *AC;
00757 
00758     bool runOnFunction(Function &F) override;
00759 
00760     void getAnalysisUsage(AnalysisUsage &AU) const override {
00761       AU.addRequired<AssumptionCacheTracker>();
00762 
00763       // We need loop information to identify the loops...
00764       AU.addRequired<DominatorTreeWrapperPass>();
00765       AU.addPreserved<DominatorTreeWrapperPass>();
00766 
00767       AU.addRequired<LoopInfoWrapperPass>();
00768       AU.addPreserved<LoopInfoWrapperPass>();
00769 
00770       AU.addPreserved<AliasAnalysis>();
00771       AU.addPreserved<ScalarEvolution>();
00772       AU.addPreserved<DependenceAnalysis>();
00773       AU.addPreservedID(BreakCriticalEdgesID);  // No critical edges added.
00774     }
00775 
00776     /// verifyAnalysis() - Verify LoopSimplifyForm's guarantees.
00777     void verifyAnalysis() const override;
00778   };
00779 }
00780 
00781 char LoopSimplify::ID = 0;
00782 INITIALIZE_PASS_BEGIN(LoopSimplify, "loop-simplify",
00783                 "Canonicalize natural loops", false, false)
00784 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
00785 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00786 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
00787 INITIALIZE_PASS_END(LoopSimplify, "loop-simplify",
00788                 "Canonicalize natural loops", false, false)
00789 
00790 // Publicly exposed interface to pass...
00791 char &llvm::LoopSimplifyID = LoopSimplify::ID;
00792 Pass *llvm::createLoopSimplifyPass() { return new LoopSimplify(); }
00793 
00794 /// runOnFunction - Run down all loops in the CFG (recursively, but we could do
00795 /// it in any convenient order) inserting preheaders...
00796 ///
00797 bool LoopSimplify::runOnFunction(Function &F) {
00798   bool Changed = false;
00799   AA = getAnalysisIfAvailable<AliasAnalysis>();
00800   LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
00801   DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
00802   SE = getAnalysisIfAvailable<ScalarEvolution>();
00803   AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
00804 
00805   // Simplify each loop nest in the function.
00806   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
00807     Changed |= simplifyLoop(*I, DT, LI, this, AA, SE, AC);
00808 
00809   return Changed;
00810 }
00811 
00812 // FIXME: Restore this code when we re-enable verification in verifyAnalysis
00813 // below.
00814 #if 0
00815 static void verifyLoop(Loop *L) {
00816   // Verify subloops.
00817   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
00818     verifyLoop(*I);
00819 
00820   // It used to be possible to just assert L->isLoopSimplifyForm(), however
00821   // with the introduction of indirectbr, there are now cases where it's
00822   // not possible to transform a loop as necessary. We can at least check
00823   // that there is an indirectbr near any time there's trouble.
00824 
00825   // Indirectbr can interfere with preheader and unique backedge insertion.
00826   if (!L->getLoopPreheader() || !L->getLoopLatch()) {
00827     bool HasIndBrPred = false;
00828     for (pred_iterator PI = pred_begin(L->getHeader()),
00829          PE = pred_end(L->getHeader()); PI != PE; ++PI)
00830       if (isa<IndirectBrInst>((*PI)->getTerminator())) {
00831         HasIndBrPred = true;
00832         break;
00833       }
00834     assert(HasIndBrPred &&
00835            "LoopSimplify has no excuse for missing loop header info!");
00836     (void)HasIndBrPred;
00837   }
00838 
00839   // Indirectbr can interfere with exit block canonicalization.
00840   if (!L->hasDedicatedExits()) {
00841     bool HasIndBrExiting = false;
00842     SmallVector<BasicBlock*, 8> ExitingBlocks;
00843     L->getExitingBlocks(ExitingBlocks);
00844     for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
00845       if (isa<IndirectBrInst>((ExitingBlocks[i])->getTerminator())) {
00846         HasIndBrExiting = true;
00847         break;
00848       }
00849     }
00850 
00851     assert(HasIndBrExiting &&
00852            "LoopSimplify has no excuse for missing exit block info!");
00853     (void)HasIndBrExiting;
00854   }
00855 }
00856 #endif
00857 
00858 void LoopSimplify::verifyAnalysis() const {
00859   // FIXME: This routine is being called mid-way through the loop pass manager
00860   // as loop passes destroy this analysis. That's actually fine, but we have no
00861   // way of expressing that here. Once all of the passes that destroy this are
00862   // hoisted out of the loop pass manager we can add back verification here.
00863 #if 0
00864   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
00865     verifyLoop(*I);
00866 #endif
00867 }