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