LLVM API Documentation

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