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