LLVM API Documentation

LoopUnswitch.cpp

Go to the documentation of this file.
00001 //===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass transforms loops that contain branches on loop-invariant conditions
00011 // to have multiple loops.  For example, it turns the left into the right code:
00012 //
00013 //  for (...)                  if (lic)
00014 //    A                          for (...)
00015 //    if (lic)                     A; B; C
00016 //      B                      else
00017 //    C                          for (...)
00018 //                                 A; C
00019 //
00020 // This can increase the size of the code exponentially (doubling it every time
00021 // a loop is unswitched) so we only unswitch if the resultant code will be
00022 // smaller than a threshold.
00023 //
00024 // This pass expects LICM to be run before it to hoist invariant conditions out
00025 // of the loop, to make the unswitching opportunity obvious.
00026 //
00027 //===----------------------------------------------------------------------===//
00028 
00029 #define DEBUG_TYPE "loop-unswitch"
00030 #include "llvm/Transforms/Scalar.h"
00031 #include "llvm/Constants.h"
00032 #include "llvm/Function.h"
00033 #include "llvm/Instructions.h"
00034 #include "llvm/Analysis/LoopInfo.h"
00035 #include "llvm/Transforms/Utils/Cloning.h"
00036 #include "llvm/Transforms/Utils/Local.h"
00037 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00038 #include "llvm/ADT/Statistic.h"
00039 #include "llvm/ADT/PostOrderIterator.h"
00040 #include "llvm/Support/Debug.h"
00041 #include "llvm/Support/CommandLine.h"
00042 #include <algorithm>
00043 #include <iostream>
00044 #include <set>
00045 using namespace llvm;
00046 
00047 namespace {
00048   Statistic<> NumBranches("loop-unswitch", "Number of branches unswitched");
00049   Statistic<> NumSwitches("loop-unswitch", "Number of switches unswitched");
00050   Statistic<> NumSelects ("loop-unswitch", "Number of selects unswitched");
00051   Statistic<> NumTrivial ("loop-unswitch",
00052                           "Number of unswitches that are trivial");
00053   Statistic<> NumSimplify("loop-unswitch", 
00054                           "Number of simplifications of unswitched code");
00055   cl::opt<unsigned>
00056   Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
00057             cl::init(10), cl::Hidden);
00058   
00059   class LoopUnswitch : public FunctionPass {
00060     LoopInfo *LI;  // Loop information
00061 
00062     // LoopProcessWorklist - List of loops we need to process.
00063     std::vector<Loop*> LoopProcessWorklist;
00064   public:
00065     virtual bool runOnFunction(Function &F);
00066     bool visitLoop(Loop *L);
00067 
00068     /// This transformation requires natural loop information & requires that
00069     /// loop preheaders be inserted into the CFG...
00070     ///
00071     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00072       AU.addRequiredID(LoopSimplifyID);
00073       AU.addPreservedID(LoopSimplifyID);
00074       AU.addRequired<LoopInfo>();
00075       AU.addPreserved<LoopInfo>();
00076       AU.addRequiredID(LCSSAID);
00077       AU.addPreservedID(LCSSAID);
00078     }
00079 
00080   private:
00081     /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
00082     /// remove it.
00083     void RemoveLoopFromWorklist(Loop *L) {
00084       std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
00085                                                  LoopProcessWorklist.end(), L);
00086       if (I != LoopProcessWorklist.end())
00087         LoopProcessWorklist.erase(I);
00088     }
00089       
00090     bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
00091     unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
00092     void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
00093                                   BasicBlock *ExitBlock);
00094     void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
00095     BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To);
00096     BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt);
00097 
00098     void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
00099                                               Constant *Val, bool isEqual);
00100     
00101     void SimplifyCode(std::vector<Instruction*> &Worklist);
00102     void RemoveBlockIfDead(BasicBlock *BB,
00103                            std::vector<Instruction*> &Worklist);
00104     void RemoveLoopFromHierarchy(Loop *L);
00105   };
00106   RegisterOpt<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
00107 }
00108 
00109 FunctionPass *llvm::createLoopUnswitchPass() { return new LoopUnswitch(); }
00110 
00111 bool LoopUnswitch::runOnFunction(Function &F) {
00112   bool Changed = false;
00113   LI = &getAnalysis<LoopInfo>();
00114 
00115   // Populate the worklist of loops to process in post-order.
00116   for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
00117     for (po_iterator<Loop*> LI = po_begin(*I), E = po_end(*I); LI != E; ++LI)
00118       LoopProcessWorklist.push_back(*LI);
00119 
00120   // Process the loops in worklist order, this is a post-order visitation of
00121   // the loops.  We use a worklist of loops so that loops can be removed at any
00122   // time if they are deleted (e.g. the backedge of a loop is removed).
00123   while (!LoopProcessWorklist.empty()) {
00124     Loop *L = LoopProcessWorklist.back();
00125     LoopProcessWorklist.pop_back();    
00126     Changed |= visitLoop(L);
00127   }
00128 
00129   return Changed;
00130 }
00131 
00132 /// FindLIVLoopCondition - Cond is a condition that occurs in L.  If it is
00133 /// invariant in the loop, or has an invariant piece, return the invariant.
00134 /// Otherwise, return null.
00135 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
00136   // Constants should be folded, not unswitched on!
00137   if (isa<Constant>(Cond)) return false;
00138   
00139   // TODO: Handle: br (VARIANT|INVARIANT).
00140   // TODO: Hoist simple expressions out of loops.
00141   if (L->isLoopInvariant(Cond)) return Cond;
00142   
00143   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
00144     if (BO->getOpcode() == Instruction::And ||
00145         BO->getOpcode() == Instruction::Or) {
00146       // If either the left or right side is invariant, we can unswitch on this,
00147       // which will cause the branch to go away in one loop and the condition to
00148       // simplify in the other one.
00149       if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
00150         return LHS;
00151       if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
00152         return RHS;
00153     }
00154       
00155       return 0;
00156 }
00157 
00158 bool LoopUnswitch::visitLoop(Loop *L) {
00159   assert(L->isLCSSAForm());
00160   
00161   bool Changed = false;
00162   
00163   // Loop over all of the basic blocks in the loop.  If we find an interior
00164   // block that is branching on a loop-invariant condition, we can unswitch this
00165   // loop.
00166   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
00167        I != E; ++I) {
00168     TerminatorInst *TI = (*I)->getTerminator();
00169     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
00170       // If this isn't branching on an invariant condition, we can't unswitch
00171       // it.
00172       if (BI->isConditional()) {
00173         // See if this, or some part of it, is loop invariant.  If so, we can
00174         // unswitch on it if we desire.
00175         Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
00176         if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::True, L)) {
00177           ++NumBranches;
00178           return true;
00179         }
00180       }      
00181     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
00182       Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
00183       if (LoopCond && SI->getNumCases() > 1) {
00184         // Find a value to unswitch on:
00185         // FIXME: this should chose the most expensive case!
00186         Constant *UnswitchVal = SI->getCaseValue(1);
00187         if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
00188           ++NumSwitches;
00189           return true;
00190         }
00191       }
00192     }
00193     
00194     // Scan the instructions to check for unswitchable values.
00195     for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end(); 
00196          BBI != E; ++BBI)
00197       if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
00198         Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
00199         if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantBool::True, L)) {
00200           ++NumSelects;
00201           return true;
00202         }
00203       }
00204   }
00205   
00206   assert(L->isLCSSAForm());
00207   
00208   return Changed;
00209 }
00210 
00211 /// isTrivialLoopExitBlock - Check to see if all paths from BB either:
00212 ///   1. Exit the loop with no side effects.
00213 ///   2. Branch to the latch block with no side-effects.
00214 ///
00215 /// If these conditions are true, we return true and set ExitBB to the block we
00216 /// exit through.
00217 ///
00218 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
00219                                          BasicBlock *&ExitBB,
00220                                          std::set<BasicBlock*> &Visited) {
00221   if (!Visited.insert(BB).second) {
00222     // Already visited and Ok, end of recursion.
00223     return true;
00224   } else if (!L->contains(BB)) {
00225     // Otherwise, this is a loop exit, this is fine so long as this is the
00226     // first exit.
00227     if (ExitBB != 0) return false;
00228     ExitBB = BB;
00229     return true;
00230   }
00231   
00232   // Otherwise, this is an unvisited intra-loop node.  Check all successors.
00233   for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
00234     // Check to see if the successor is a trivial loop exit.
00235     if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
00236       return false;
00237   }
00238 
00239   // Okay, everything after this looks good, check to make sure that this block
00240   // doesn't include any side effects.
00241   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
00242     if (I->mayWriteToMemory())
00243       return false;
00244   
00245   return true;
00246 }
00247 
00248 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
00249 /// leads to an exit from the specified loop, and has no side-effects in the 
00250 /// process.  If so, return the block that is exited to, otherwise return null.
00251 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
00252   std::set<BasicBlock*> Visited;
00253   Visited.insert(L->getHeader());  // Branches to header are ok.
00254   BasicBlock *ExitBB = 0;
00255   if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
00256     return ExitBB;
00257   return 0;
00258 }
00259 
00260 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
00261 /// trivial: that is, that the condition controls whether or not the loop does
00262 /// anything at all.  If this is a trivial condition, unswitching produces no
00263 /// code duplications (equivalently, it produces a simpler loop and a new empty
00264 /// loop, which gets deleted).
00265 ///
00266 /// If this is a trivial condition, return true, otherwise return false.  When
00267 /// returning true, this sets Cond and Val to the condition that controls the
00268 /// trivial condition: when Cond dynamically equals Val, the loop is known to
00269 /// exit.  Finally, this sets LoopExit to the BB that the loop exits to when
00270 /// Cond == Val.
00271 ///
00272 static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
00273                                        BasicBlock **LoopExit = 0) {
00274   BasicBlock *Header = L->getHeader();
00275   TerminatorInst *HeaderTerm = Header->getTerminator();
00276   
00277   BasicBlock *LoopExitBB = 0;
00278   if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
00279     // If the header block doesn't end with a conditional branch on Cond, we
00280     // can't handle it.
00281     if (!BI->isConditional() || BI->getCondition() != Cond)
00282       return false;
00283   
00284     // Check to see if a successor of the branch is guaranteed to go to the
00285     // latch block or exit through a one exit block without having any 
00286     // side-effects.  If so, determine the value of Cond that causes it to do
00287     // this.
00288     if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
00289       if (Val) *Val = ConstantBool::True;
00290     } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
00291       if (Val) *Val = ConstantBool::False;
00292     }
00293   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
00294     // If this isn't a switch on Cond, we can't handle it.
00295     if (SI->getCondition() != Cond) return false;
00296     
00297     // Check to see if a successor of the switch is guaranteed to go to the
00298     // latch block or exit through a one exit block without having any 
00299     // side-effects.  If so, determine the value of Cond that causes it to do
00300     // this.  Note that we can't trivially unswitch on the default case.
00301     for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
00302       if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
00303         // Okay, we found a trivial case, remember the value that is trivial.
00304         if (Val) *Val = SI->getCaseValue(i);
00305         break;
00306       }
00307   }
00308 
00309   // If we didn't find a single unique LoopExit block, or if the loop exit block
00310   // contains phi nodes, this isn't trivial.
00311   if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
00312     return false;   // Can't handle this.
00313   
00314   if (LoopExit) *LoopExit = LoopExitBB;
00315   
00316   // We already know that nothing uses any scalar values defined inside of this
00317   // loop.  As such, we just have to check to see if this loop will execute any
00318   // side-effecting instructions (e.g. stores, calls, volatile loads) in the
00319   // part of the loop that the code *would* execute.  We already checked the
00320   // tail, check the header now.
00321   for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
00322     if (I->mayWriteToMemory())
00323       return false;
00324   return true;
00325 }
00326 
00327 /// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
00328 /// we choose to unswitch the specified loop on the specified value.
00329 ///
00330 unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
00331   // If the condition is trivial, always unswitch.  There is no code growth for
00332   // this case.
00333   if (IsTrivialUnswitchCondition(L, LIC))
00334     return 0;
00335   
00336   // FIXME: This is really overly conservative.  However, more liberal 
00337   // estimations have thus far resulted in excessive unswitching, which is bad
00338   // both in compile time and in code size.  This should be replaced once
00339   // someone figures out how a good estimation.
00340   return L->getBlocks().size();
00341   
00342   unsigned Cost = 0;
00343   // FIXME: this is brain dead.  It should take into consideration code
00344   // shrinkage.
00345   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
00346        I != E; ++I) {
00347     BasicBlock *BB = *I;
00348     // Do not include empty blocks in the cost calculation.  This happen due to
00349     // loop canonicalization and will be removed.
00350     if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
00351       continue;
00352     
00353     // Count basic blocks.
00354     ++Cost;
00355   }
00356 
00357   return Cost;
00358 }
00359 
00360 /// UnswitchIfProfitable - We have found that we can unswitch L when
00361 /// LoopCond == Val to simplify the loop.  If we decide that this is profitable,
00362 /// unswitch the loop, reprocess the pieces, then return true.
00363 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
00364   // Check to see if it would be profitable to unswitch this loop.
00365   unsigned Cost = getLoopUnswitchCost(L, LoopCond);
00366   if (Cost > Threshold) {
00367     // FIXME: this should estimate growth by the amount of code shared by the
00368     // resultant unswitched loops.
00369     //
00370     DEBUG(std::cerr << "NOT unswitching loop %"
00371                     << L->getHeader()->getName() << ", cost too high: "
00372                     << L->getBlocks().size() << "\n");
00373     return false;
00374   }
00375   
00376   // If this is a trivial condition to unswitch (which results in no code
00377   // duplication), do it now.
00378   Constant *CondVal;
00379   BasicBlock *ExitBlock;
00380   if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
00381     UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
00382   } else {
00383     UnswitchNontrivialCondition(LoopCond, Val, L);
00384   }
00385  
00386   return true;
00387 }
00388 
00389 /// SplitBlock - Split the specified block at the specified instruction - every
00390 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
00391 /// to a new block.  The two blocks are joined by an unconditional branch and
00392 /// the loop info is updated.
00393 ///
00394 BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *Old, Instruction *SplitPt) {
00395   BasicBlock::iterator SplitIt = SplitPt;
00396   while (isa<PHINode>(SplitIt))
00397     ++SplitIt;
00398   BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
00399 
00400   // The new block lives in whichever loop the old one did.
00401   if (Loop *L = LI->getLoopFor(Old))
00402     L->addBasicBlockToLoop(New, *LI);
00403   
00404   return New;
00405 }
00406 
00407 
00408 BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) {
00409   TerminatorInst *LatchTerm = BB->getTerminator();
00410   unsigned SuccNum = 0;
00411   for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
00412     assert(i != e && "Didn't find edge?");
00413     if (LatchTerm->getSuccessor(i) == Succ) {
00414       SuccNum = i;
00415       break;
00416     }
00417   }
00418   
00419   // If this is a critical edge, let SplitCriticalEdge do it.
00420   if (SplitCriticalEdge(BB->getTerminator(), SuccNum, this))
00421     return LatchTerm->getSuccessor(SuccNum);
00422 
00423   // If the edge isn't critical, then BB has a single successor or Succ has a
00424   // single pred.  Split the block.
00425   BasicBlock::iterator SplitPoint;
00426   if (BasicBlock *SP = Succ->getSinglePredecessor()) {
00427     // If the successor only has a single pred, split the top of the successor
00428     // block.
00429     assert(SP == BB && "CFG broken");
00430     return SplitBlock(Succ, Succ->begin());
00431   } else {
00432     // Otherwise, if BB has a single successor, split it at the bottom of the
00433     // block.
00434     assert(BB->getTerminator()->getNumSuccessors() == 1 &&
00435            "Should have a single succ!"); 
00436     return SplitBlock(BB, BB->getTerminator());
00437   }
00438 }
00439   
00440 
00441 
00442 // RemapInstruction - Convert the instruction operands from referencing the
00443 // current values into those specified by ValueMap.
00444 //
00445 static inline void RemapInstruction(Instruction *I,
00446                                     std::map<const Value *, Value*> &ValueMap) {
00447   for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
00448     Value *Op = I->getOperand(op);
00449     std::map<const Value *, Value*>::iterator It = ValueMap.find(Op);
00450     if (It != ValueMap.end()) Op = It->second;
00451     I->setOperand(op, Op);
00452   }
00453 }
00454 
00455 /// CloneLoop - Recursively clone the specified loop and all of its children,
00456 /// mapping the blocks with the specified map.
00457 static Loop *CloneLoop(Loop *L, Loop *PL, std::map<const Value*, Value*> &VM,
00458                        LoopInfo *LI) {
00459   Loop *New = new Loop();
00460 
00461   if (PL)
00462     PL->addChildLoop(New);
00463   else
00464     LI->addTopLevelLoop(New);
00465 
00466   // Add all of the blocks in L to the new loop.
00467   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
00468        I != E; ++I)
00469     if (LI->getLoopFor(*I) == L)
00470       New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
00471 
00472   // Add all of the subloops to the new loop.
00473   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
00474     CloneLoop(*I, New, VM, LI);
00475 
00476   return New;
00477 }
00478 
00479 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
00480 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest.  Insert the
00481 /// code immediately before InsertPt.
00482 static void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
00483                                            BasicBlock *TrueDest,
00484                                            BasicBlock *FalseDest,
00485                                            Instruction *InsertPt) {
00486   // Insert a conditional branch on LIC to the two preheaders.  The original
00487   // code is the true version and the new code is the false version.
00488   Value *BranchVal = LIC;
00489   if (!isa<ConstantBool>(Val)) {
00490     BranchVal = BinaryOperator::createSetEQ(LIC, Val, "tmp", InsertPt);
00491   } else if (Val != ConstantBool::True) {
00492     // We want to enter the new loop when the condition is true.
00493     std::swap(TrueDest, FalseDest);
00494   }
00495 
00496   // Insert the new branch.
00497   new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
00498 }
00499 
00500 
00501 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
00502 /// condition in it (a cond branch from its header block to its latch block,
00503 /// where the path through the loop that doesn't execute its body has no 
00504 /// side-effects), unswitch it.  This doesn't involve any code duplication, just
00505 /// moving the conditional branch outside of the loop and updating loop info.
00506 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, 
00507                                             Constant *Val, 
00508                                             BasicBlock *ExitBlock) {
00509   DEBUG(std::cerr << "loop-unswitch: Trivial-Unswitch loop %"
00510         << L->getHeader()->getName() << " [" << L->getBlocks().size()
00511         << " blocks] in Function " << L->getHeader()->getParent()->getName()
00512         << " on cond: " << *Val << " == " << *Cond << "\n");
00513   
00514   // First step, split the preheader, so that we know that there is a safe place
00515   // to insert the conditional branch.  We will change 'OrigPH' to have a
00516   // conditional branch on Cond.
00517   BasicBlock *OrigPH = L->getLoopPreheader();
00518   BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
00519 
00520   // Now that we have a place to insert the conditional branch, create a place
00521   // to branch to: this is the exit block out of the loop that we should
00522   // short-circuit to.
00523   
00524   // Split this block now, so that the loop maintains its exit block, and so
00525   // that the jump from the preheader can execute the contents of the exit block
00526   // without actually branching to it (the exit block should be dominated by the
00527   // loop header, not the preheader).
00528   assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
00529   BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin());
00530     
00531   // Okay, now we have a position to branch from and a position to branch to, 
00532   // insert the new conditional branch.
00533   EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH, 
00534                                  OrigPH->getTerminator());
00535   OrigPH->getTerminator()->eraseFromParent();
00536 
00537   // We need to reprocess this loop, it could be unswitched again.
00538   LoopProcessWorklist.push_back(L);
00539   
00540   // Now that we know that the loop is never entered when this condition is a
00541   // particular value, rewrite the loop with this info.  We know that this will
00542   // at least eliminate the old branch.
00543   RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
00544   ++NumTrivial;
00545 }
00546 
00547 
00548 /// VersionLoop - We determined that the loop is profitable to unswitch when LIC
00549 /// equal Val.  Split it into loop versions and test the condition outside of
00550 /// either loop.  Return the loops created as Out1/Out2.
00551 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val, 
00552                                                Loop *L) {
00553   Function *F = L->getHeader()->getParent();
00554   DEBUG(std::cerr << "loop-unswitch: Unswitching loop %"
00555                   << L->getHeader()->getName() << " [" << L->getBlocks().size()
00556                   << " blocks] in Function " << F->getName()
00557                   << " when '" << *Val << "' == " << *LIC << "\n");
00558 
00559   // LoopBlocks contains all of the basic blocks of the loop, including the
00560   // preheader of the loop, the body of the loop, and the exit blocks of the 
00561   // loop, in that order.
00562   std::vector<BasicBlock*> LoopBlocks;
00563 
00564   // First step, split the preheader and exit blocks, and add these blocks to
00565   // the LoopBlocks list.
00566   BasicBlock *OrigPreheader = L->getLoopPreheader();
00567   LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
00568 
00569   // We want the loop to come after the preheader, but before the exit blocks.
00570   LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
00571 
00572   std::vector<BasicBlock*> ExitBlocks;
00573   L->getExitBlocks(ExitBlocks);
00574   std::sort(ExitBlocks.begin(), ExitBlocks.end());
00575   ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
00576                    ExitBlocks.end());
00577   
00578   // Split all of the edges from inside the loop to their exit blocks.  Update
00579   // the appropriate Phi nodes as we do so.
00580   unsigned NumBlocks = L->getBlocks().size();
00581   
00582   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
00583     BasicBlock *ExitBlock = ExitBlocks[i];
00584     std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
00585 
00586     for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
00587       assert(L->contains(Preds[j]) &&
00588              "All preds of loop exit blocks must be the same loop!");
00589       BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock);
00590       BasicBlock* StartBlock = Preds[j];
00591       BasicBlock* EndBlock;
00592       if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
00593         EndBlock = MiddleBlock;
00594         MiddleBlock = EndBlock->getSinglePredecessor();;
00595       } else {
00596         EndBlock = ExitBlock;
00597       }
00598       
00599       std::set<PHINode*> InsertedPHIs;
00600       PHINode* OldLCSSA = 0;
00601       for (BasicBlock::iterator I = EndBlock->begin();
00602            (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
00603         Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
00604         PHINode* NewLCSSA = new PHINode(OldLCSSA->getType(),
00605                                         OldLCSSA->getName() + ".us-lcssa",
00606                                         MiddleBlock->getTerminator());
00607         NewLCSSA->addIncoming(OldValue, StartBlock);
00608         OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
00609                                    NewLCSSA);
00610         InsertedPHIs.insert(NewLCSSA);
00611       }
00612 
00613       BasicBlock::iterator InsertPt = EndBlock->begin();
00614       while (dyn_cast<PHINode>(InsertPt)) ++InsertPt;
00615       for (BasicBlock::iterator I = MiddleBlock->begin();
00616          (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
00617          ++I) {
00618         PHINode *NewLCSSA = new PHINode(OldLCSSA->getType(),
00619                                         OldLCSSA->getName() + ".us-lcssa",
00620                                         InsertPt);
00621         OldLCSSA->replaceAllUsesWith(NewLCSSA);
00622         NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
00623       }
00624     }    
00625   }
00626   
00627   // The exit blocks may have been changed due to edge splitting, recompute.
00628   ExitBlocks.clear();
00629   L->getExitBlocks(ExitBlocks);
00630   std::sort(ExitBlocks.begin(), ExitBlocks.end());
00631   ExitBlocks.erase(std::unique(ExitBlocks.begin(), ExitBlocks.end()),
00632                    ExitBlocks.end());
00633   
00634   // Add exit blocks to the loop blocks.
00635   LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
00636 
00637   // Next step, clone all of the basic blocks that make up the loop (including
00638   // the loop preheader and exit blocks), keeping track of the mapping between
00639   // the instructions and blocks.
00640   std::vector<BasicBlock*> NewBlocks;
00641   NewBlocks.reserve(LoopBlocks.size());
00642   std::map<const Value*, Value*> ValueMap;
00643   for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
00644     BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
00645     NewBlocks.push_back(New);
00646     ValueMap[LoopBlocks[i]] = New;  // Keep the BB mapping.
00647   }
00648 
00649   // Splice the newly inserted blocks into the function right before the
00650   // original preheader.
00651   F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
00652                                 NewBlocks[0], F->end());
00653 
00654   // Now we create the new Loop object for the versioned loop.
00655   Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI);
00656   Loop *ParentLoop = L->getParentLoop();
00657   if (ParentLoop) {
00658     // Make sure to add the cloned preheader and exit blocks to the parent loop
00659     // as well.
00660     ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
00661   }
00662   
00663   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
00664     BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
00665     // The new exit block should be in the same loop as the old one.
00666     if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
00667       ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
00668     
00669     assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
00670            "Exit block should have been split to have one successor!");
00671     BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
00672     
00673     // If the successor of the exit block had PHI nodes, add an entry for
00674     // NewExit.
00675     PHINode *PN;
00676     for (BasicBlock::iterator I = ExitSucc->begin();
00677          (PN = dyn_cast<PHINode>(I)); ++I) {
00678       Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
00679       std::map<const Value *, Value*>::iterator It = ValueMap.find(V);
00680       if (It != ValueMap.end()) V = It->second;
00681       PN->addIncoming(V, NewExit);
00682     }
00683   }
00684 
00685   // Rewrite the code to refer to itself.
00686   for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
00687     for (BasicBlock::iterator I = NewBlocks[i]->begin(),
00688            E = NewBlocks[i]->end(); I != E; ++I)
00689       RemapInstruction(I, ValueMap);
00690   
00691   // Rewrite the original preheader to select between versions of the loop.
00692   BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
00693   assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
00694          "Preheader splitting did not work correctly!");
00695 
00696   // Emit the new branch that selects between the two versions of this loop.
00697   EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
00698   OldBR->eraseFromParent();
00699   
00700   LoopProcessWorklist.push_back(L);
00701   LoopProcessWorklist.push_back(NewLoop);
00702 
00703   // Now we rewrite the original code to know that the condition is true and the
00704   // new code to know that the condition is false.
00705   RewriteLoopBodyWithConditionConstant(L      , LIC, Val, false);
00706   
00707   // It's possible that simplifying one loop could cause the other to be
00708   // deleted.  If so, don't simplify it.
00709   if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
00710     RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
00711 }
00712 
00713 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
00714 /// specified.
00715 static void RemoveFromWorklist(Instruction *I, 
00716                                std::vector<Instruction*> &Worklist) {
00717   std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
00718                                                      Worklist.end(), I);
00719   while (WI != Worklist.end()) {
00720     unsigned Offset = WI-Worklist.begin();
00721     Worklist.erase(WI);
00722     WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
00723   }
00724 }
00725 
00726 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
00727 /// program, replacing all uses with V and update the worklist.
00728 static void ReplaceUsesOfWith(Instruction *I, Value *V, 
00729                               std::vector<Instruction*> &Worklist) {
00730   DEBUG(std::cerr << "Replace with '" << *V << "': " << *I);
00731 
00732   // Add uses to the worklist, which may be dead now.
00733   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
00734     if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
00735       Worklist.push_back(Use);
00736 
00737   // Add users to the worklist which may be simplified now.
00738   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
00739        UI != E; ++UI)
00740     Worklist.push_back(cast<Instruction>(*UI));
00741   I->replaceAllUsesWith(V);
00742   I->eraseFromParent();
00743   RemoveFromWorklist(I, Worklist);
00744   ++NumSimplify;
00745 }
00746 
00747 /// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
00748 /// information, and remove any dead successors it has.
00749 ///
00750 void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
00751                                      std::vector<Instruction*> &Worklist) {
00752   if (pred_begin(BB) != pred_end(BB)) {
00753     // This block isn't dead, since an edge to BB was just removed, see if there
00754     // are any easy simplifications we can do now.
00755     if (BasicBlock *Pred = BB->getSinglePredecessor()) {
00756       // If it has one pred, fold phi nodes in BB.
00757       while (isa<PHINode>(BB->begin()))
00758         ReplaceUsesOfWith(BB->begin(), 
00759                           cast<PHINode>(BB->begin())->getIncomingValue(0), 
00760                           Worklist);
00761       
00762       // If this is the header of a loop and the only pred is the latch, we now
00763       // have an unreachable loop.
00764       if (Loop *L = LI->getLoopFor(BB))
00765         if (L->getHeader() == BB && L->contains(Pred)) {
00766           // Remove the branch from the latch to the header block, this makes
00767           // the header dead, which will make the latch dead (because the header
00768           // dominates the latch).
00769           Pred->getTerminator()->eraseFromParent();
00770           new UnreachableInst(Pred);
00771           
00772           // The loop is now broken, remove it from LI.
00773           RemoveLoopFromHierarchy(L);
00774           
00775           // Reprocess the header, which now IS dead.
00776           RemoveBlockIfDead(BB, Worklist);
00777           return;
00778         }
00779       
00780       // If pred ends in a uncond branch, add uncond branch to worklist so that
00781       // the two blocks will get merged.
00782       if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
00783         if (BI->isUnconditional())
00784           Worklist.push_back(BI);
00785     }
00786     return;
00787   }
00788 
00789   DEBUG(std::cerr << "Nuking dead block: " << *BB);
00790   
00791   // Remove the instructions in the basic block from the worklist.
00792   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
00793     RemoveFromWorklist(I, Worklist);
00794     
00795     // Anything that uses the instructions in this basic block should have their
00796     // uses replaced with undefs.
00797     if (!I->use_empty())
00798       I->replaceAllUsesWith(UndefValue::get(I->getType()));
00799   }
00800   
00801   // If this is the edge to the header block for a loop, remove the loop and
00802   // promote all subloops.
00803   if (Loop *BBLoop = LI->getLoopFor(BB)) {
00804     if (BBLoop->getLoopLatch() == BB)
00805       RemoveLoopFromHierarchy(BBLoop);
00806   }
00807 
00808   // Remove the block from the loop info, which removes it from any loops it
00809   // was in.
00810   LI->removeBlock(BB);
00811   
00812   
00813   // Remove phi node entries in successors for this block.
00814   TerminatorInst *TI = BB->getTerminator();
00815   std::vector<BasicBlock*> Succs;
00816   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
00817     Succs.push_back(TI->getSuccessor(i));
00818     TI->getSuccessor(i)->removePredecessor(BB);
00819   }
00820   
00821   // Unique the successors, remove anything with multiple uses.
00822   std::sort(Succs.begin(), Succs.end());
00823   Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
00824   
00825   // Remove the basic block, including all of the instructions contained in it.
00826   BB->eraseFromParent();
00827   
00828   // Remove successor blocks here that are not dead, so that we know we only
00829   // have dead blocks in this list.  Nondead blocks have a way of becoming dead,
00830   // then getting removed before we revisit them, which is badness.
00831   //
00832   for (unsigned i = 0; i != Succs.size(); ++i)
00833     if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
00834       // One exception is loop headers.  If this block was the preheader for a
00835       // loop, then we DO want to visit the loop so the loop gets deleted.
00836       // We know that if the successor is a loop header, that this loop had to
00837       // be the preheader: the case where this was the latch block was handled
00838       // above and headers can only have two predecessors.
00839       if (!LI->isLoopHeader(Succs[i])) {
00840         Succs.erase(Succs.begin()+i);
00841         --i;
00842       }
00843     }
00844   
00845   for (unsigned i = 0, e = Succs.size(); i != e; ++i)
00846     RemoveBlockIfDead(Succs[i], Worklist);
00847 }
00848 
00849 /// RemoveLoopFromHierarchy - We have discovered that the specified loop has
00850 /// become unwrapped, either because the backedge was deleted, or because the
00851 /// edge into the header was removed.  If the edge into the header from the
00852 /// latch block was removed, the loop is unwrapped but subloops are still alive,
00853 /// so they just reparent loops.  If the loops are actually dead, they will be
00854 /// removed later.
00855 void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
00856   if (Loop *ParentLoop = L->getParentLoop()) { // Not a top-level loop.
00857     // Reparent all of the blocks in this loop.  Since BBLoop had a parent,
00858     // they are now all in it.
00859     for (Loop::block_iterator I = L->block_begin(), E = L->block_end(); 
00860          I != E; ++I)
00861       if (LI->getLoopFor(*I) == L)    // Don't change blocks in subloops.
00862         LI->changeLoopFor(*I, ParentLoop);
00863     
00864     // Remove the loop from its parent loop.
00865     for (Loop::iterator I = ParentLoop->begin(), E = ParentLoop->end();;
00866          ++I) {
00867       assert(I != E && "Couldn't find loop");
00868       if (*I == L) {
00869         ParentLoop->removeChildLoop(I);
00870         break;
00871       }
00872     }
00873     
00874     // Move all subloops into the parent loop.
00875     while (L->begin() != L->end())
00876       ParentLoop->addChildLoop(L->removeChildLoop(L->end()-1));
00877   } else {
00878     // Reparent all of the blocks in this loop.  Since BBLoop had no parent,
00879     // they no longer in a loop at all.
00880     
00881     for (unsigned i = 0; i != L->getBlocks().size(); ++i) {
00882       // Don't change blocks in subloops.
00883       if (LI->getLoopFor(L->getBlocks()[i]) == L) {
00884         LI->removeBlock(L->getBlocks()[i]);
00885         --i;
00886       }
00887     }
00888 
00889     // Remove the loop from the top-level LoopInfo object.
00890     for (LoopInfo::iterator I = LI->begin(), E = LI->end();; ++I) {
00891       assert(I != E && "Couldn't find loop");
00892       if (*I == L) {
00893         LI->removeLoop(I);
00894         break;
00895       }
00896     }
00897 
00898     // Move all of the subloops to the top-level.
00899     while (L->begin() != L->end())
00900       LI->addTopLevelLoop(L->removeChildLoop(L->end()-1));
00901   }
00902 
00903   delete L;
00904   RemoveLoopFromWorklist(L);
00905 }
00906 
00907 
00908 
00909 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
00910 // the value specified by Val in the specified loop, or we know it does NOT have
00911 // that value.  Rewrite any uses of LIC or of properties correlated to it.
00912 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
00913                                                         Constant *Val,
00914                                                         bool IsEqual) {
00915   assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
00916   
00917   // FIXME: Support correlated properties, like:
00918   //  for (...)
00919   //    if (li1 < li2)
00920   //      ...
00921   //    if (li1 > li2)
00922   //      ...
00923   
00924   // FOLD boolean conditions (X|LIC), (X&LIC).  Fold conditional branches,
00925   // selects, switches.
00926   std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
00927   std::vector<Instruction*> Worklist;
00928 
00929   // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
00930   // in the loop with the appropriate one directly.
00931   if (IsEqual || isa<ConstantBool>(Val)) {
00932     Value *Replacement;
00933     if (IsEqual)
00934       Replacement = Val;
00935     else
00936       Replacement = ConstantBool::get(!cast<ConstantBool>(Val)->getValue());
00937     
00938     for (unsigned i = 0, e = Users.size(); i != e; ++i)
00939       if (Instruction *U = cast<Instruction>(Users[i])) {
00940         if (!L->contains(U->getParent()))
00941           continue;
00942         U->replaceUsesOfWith(LIC, Replacement);
00943         Worklist.push_back(U);
00944       }
00945   } else {
00946     // Otherwise, we don't know the precise value of LIC, but we do know that it
00947     // is certainly NOT "Val".  As such, simplify any uses in the loop that we
00948     // can.  This case occurs when we unswitch switch statements.
00949     for (unsigned i = 0, e = Users.size(); i != e; ++i)
00950       if (Instruction *U = cast<Instruction>(Users[i])) {
00951         if (!L->contains(U->getParent()))
00952           continue;
00953 
00954         Worklist.push_back(U);
00955 
00956         // If we know that LIC is not Val, use this info to simplify code.
00957         if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
00958           for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
00959             if (SI->getCaseValue(i) == Val) {
00960               // Found a dead case value.  Don't remove PHI nodes in the 
00961               // successor if they become single-entry, those PHI nodes may
00962               // be in the Users list.
00963               
00964               // FIXME: This is a hack.  We need to keep the successor around
00965               // and hooked up so as to preserve the loop structure, because
00966               // trying to update it is complicated.  So instead we preserve the
00967               // loop structure and put the block on an dead code path.
00968               
00969               BasicBlock* Old = SI->getParent();
00970               BasicBlock* Split = SplitBlock(Old, SI);
00971               
00972               Instruction* OldTerm = Old->getTerminator();
00973               BranchInst* Branch = new BranchInst(Split,
00974                                         SI->getSuccessor(i),
00975                                         ConstantBool::True,
00976                                         OldTerm);
00977               
00978               Old->getTerminator()->eraseFromParent();
00979               
00980               
00981               PHINode *PN;
00982               for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
00983                    (PN = dyn_cast<PHINode>(II)); ++II) {
00984                 Value *InVal = PN->removeIncomingValue(Split, false);
00985                 PN->addIncoming(InVal, Old);
00986               }
00987 
00988               SI->removeCase(i);
00989               break;
00990             }
00991           }
00992         }
00993         
00994         // TODO: We could do other simplifications, for example, turning 
00995         // LIC == Val -> false.
00996       }
00997   }
00998   
00999   SimplifyCode(Worklist);
01000 }
01001 
01002 /// SimplifyCode - Okay, now that we have simplified some instructions in the 
01003 /// loop, walk over it and constant prop, dce, and fold control flow where
01004 /// possible.  Note that this is effectively a very simple loop-structure-aware
01005 /// optimizer.  During processing of this loop, L could very well be deleted, so
01006 /// it must not be used.
01007 ///
01008 /// FIXME: When the loop optimizer is more mature, separate this out to a new
01009 /// pass.
01010 ///
01011 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
01012   while (!Worklist.empty()) {
01013     Instruction *I = Worklist.back();
01014     Worklist.pop_back();
01015     
01016     // Simple constant folding.
01017     if (Constant *C = ConstantFoldInstruction(I)) {
01018       ReplaceUsesOfWith(I, C, Worklist);
01019       continue;
01020     }
01021     
01022     // Simple DCE.
01023     if (isInstructionTriviallyDead(I)) {
01024       DEBUG(std::cerr << "Remove dead instruction '" << *I);
01025       
01026       // Add uses to the worklist, which may be dead now.
01027       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
01028         if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
01029           Worklist.push_back(Use);
01030       I->eraseFromParent();
01031       RemoveFromWorklist(I, Worklist);
01032       ++NumSimplify;
01033       continue;
01034     }
01035     
01036     // Special case hacks that appear commonly in unswitched code.
01037     switch (I->getOpcode()) {
01038     case Instruction::Select:
01039       if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(0))) {
01040         ReplaceUsesOfWith(I, I->getOperand(!CB->getValue()+1), Worklist);
01041         continue;
01042       }
01043       break;
01044     case Instruction::And:
01045       if (isa<ConstantBool>(I->getOperand(0)))   // constant -> RHS
01046         cast<BinaryOperator>(I)->swapOperands();
01047       if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) {
01048         if (CB->getValue())   // X & 1 -> X
01049           ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
01050         else                  // X & 0 -> 0
01051           ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
01052         continue;
01053       }
01054       break;
01055     case Instruction::Or:
01056       if (isa<ConstantBool>(I->getOperand(0)))   // constant -> RHS
01057         cast<BinaryOperator>(I)->swapOperands();
01058       if (ConstantBool *CB = dyn_cast<ConstantBool>(I->getOperand(1))) {
01059         if (CB->getValue())   // X | 1 -> 1
01060           ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
01061         else                  // X | 0 -> X
01062           ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
01063         continue;
01064       }
01065       break;
01066     case Instruction::Br: {
01067       BranchInst *BI = cast<BranchInst>(I);
01068       if (BI->isUnconditional()) {
01069         // If BI's parent is the only pred of the successor, fold the two blocks
01070         // together.
01071         BasicBlock *Pred = BI->getParent();
01072         BasicBlock *Succ = BI->getSuccessor(0);
01073         BasicBlock *SinglePred = Succ->getSinglePredecessor();
01074         if (!SinglePred) continue;  // Nothing to do.
01075         assert(SinglePred == Pred && "CFG broken");
01076 
01077         DEBUG(std::cerr << "Merging blocks: " << Pred->getName() << " <- " 
01078                         << Succ->getName() << "\n");
01079         
01080         // Resolve any single entry PHI nodes in Succ.
01081         while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
01082           ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
01083         
01084         // Move all of the successor contents from Succ to Pred.
01085         Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
01086                                    Succ->end());
01087         BI->eraseFromParent();
01088         RemoveFromWorklist(BI, Worklist);
01089         
01090         // If Succ has any successors with PHI nodes, update them to have
01091         // entries coming from Pred instead of Succ.
01092         Succ->replaceAllUsesWith(Pred);
01093         
01094         // Remove Succ from the loop tree.
01095         LI->removeBlock(Succ);
01096         Succ->eraseFromParent();
01097         ++NumSimplify;
01098       } else if (ConstantBool *CB = dyn_cast<ConstantBool>(BI->getCondition())){
01099         // Conditional branch.  Turn it into an unconditional branch, then
01100         // remove dead blocks.
01101         break;  // FIXME: Enable.
01102 
01103         DEBUG(std::cerr << "Folded branch: " << *BI);
01104         BasicBlock *DeadSucc = BI->getSuccessor(CB->getValue());
01105         BasicBlock *LiveSucc = BI->getSuccessor(!CB->getValue());
01106         DeadSucc->removePredecessor(BI->getParent(), true);
01107         Worklist.push_back(new BranchInst(LiveSucc, BI));
01108         BI->eraseFromParent();
01109         RemoveFromWorklist(BI, Worklist);
01110         ++NumSimplify;
01111 
01112         RemoveBlockIfDead(DeadSucc, Worklist);
01113       }
01114       break;
01115     }
01116     }
01117   }
01118 }