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