If a condition is not inside a loop then the condition is suitable
[oota-llvm.git] / lib / Transforms / Scalar / LoopUnswitch.cpp
1 //===-- LoopUnswitch.cpp - Hoist loop-invariant conditionals in loop ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass transforms loops that contain branches on loop-invariant conditions
11 // to have multiple loops.  For example, it turns the left into the right code:
12 //
13 //  for (...)                  if (lic)
14 //    A                          for (...)
15 //    if (lic)                     A; B; C
16 //      B                      else
17 //    C                          for (...)
18 //                                 A; C
19 //
20 // This can increase the size of the code exponentially (doubling it every time
21 // a loop is unswitched) so we only unswitch if the resultant code will be
22 // smaller than a threshold.
23 //
24 // This pass expects LICM to be run before it to hoist invariant conditions out
25 // of the loop, to make the unswitching opportunity obvious.
26 //
27 //===----------------------------------------------------------------------===//
28
29 #define DEBUG_TYPE "loop-unswitch"
30 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/Constants.h"
32 #include "llvm/DerivedTypes.h"
33 #include "llvm/Function.h"
34 #include "llvm/Instructions.h"
35 #include "llvm/Analysis/ConstantFolding.h"
36 #include "llvm/Analysis/LoopInfo.h"
37 #include "llvm/Analysis/LoopPass.h"
38 #include "llvm/Transforms/Utils/Cloning.h"
39 #include "llvm/Transforms/Utils/Local.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include "llvm/ADT/Statistic.h"
42 #include "llvm/ADT/SmallPtrSet.h"
43 #include "llvm/ADT/PostOrderIterator.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/Debug.h"
47 #include <algorithm>
48 #include <set>
49 using namespace llvm;
50
51 STATISTIC(NumBranches, "Number of branches unswitched");
52 STATISTIC(NumSwitches, "Number of switches unswitched");
53 STATISTIC(NumSelects , "Number of selects unswitched");
54 STATISTIC(NumTrivial , "Number of unswitches that are trivial");
55 STATISTIC(NumSimplify, "Number of simplifications of unswitched code");
56
57 namespace {
58   cl::opt<unsigned>
59   Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"),
60             cl::init(10), cl::Hidden);
61   
62   class VISIBILITY_HIDDEN LoopUnswitch : public LoopPass {
63     LoopInfo *LI;  // Loop information
64     LPPassManager *LPM;
65
66     // LoopProcessWorklist - Used to check if second loop needs processing
67     // after RewriteLoopBodyWithConditionConstant rewrites first loop.
68     std::vector<Loop*> LoopProcessWorklist;
69     SmallPtrSet<Value *,8> UnswitchedVals;
70     
71     bool OptimizeForSize;
72   public:
73     static char ID; // Pass ID, replacement for typeid
74     LoopUnswitch(bool Os = false) : 
75       LoopPass((intptr_t)&ID), OptimizeForSize(Os) {}
76
77     bool runOnLoop(Loop *L, LPPassManager &LPM);
78
79     /// This transformation requires natural loop information & requires that
80     /// loop preheaders be inserted into the CFG...
81     ///
82     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
83       AU.addRequiredID(LoopSimplifyID);
84       AU.addPreservedID(LoopSimplifyID);
85       AU.addRequired<LoopInfo>();
86       AU.addPreserved<LoopInfo>();
87       AU.addRequiredID(LCSSAID);
88       AU.addPreservedID(LCSSAID);
89     }
90
91   private:
92     /// RemoveLoopFromWorklist - If the specified loop is on the loop worklist,
93     /// remove it.
94     void RemoveLoopFromWorklist(Loop *L) {
95       std::vector<Loop*>::iterator I = std::find(LoopProcessWorklist.begin(),
96                                                  LoopProcessWorklist.end(), L);
97       if (I != LoopProcessWorklist.end())
98         LoopProcessWorklist.erase(I);
99     }
100       
101     bool UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L);
102     unsigned getLoopUnswitchCost(Loop *L, Value *LIC);
103     void UnswitchTrivialCondition(Loop *L, Value *Cond, Constant *Val,
104                                   BasicBlock *ExitBlock);
105     void UnswitchNontrivialCondition(Value *LIC, Constant *OnVal, Loop *L);
106     BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To);
107     BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt);
108
109     void RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
110                                               Constant *Val, bool isEqual);
111     
112     void SimplifyCode(std::vector<Instruction*> &Worklist);
113     void RemoveBlockIfDead(BasicBlock *BB,
114                            std::vector<Instruction*> &Worklist);
115     void RemoveLoopFromHierarchy(Loop *L);
116   };
117   char LoopUnswitch::ID = 0;
118   RegisterPass<LoopUnswitch> X("loop-unswitch", "Unswitch loops");
119 }
120
121 LoopPass *llvm::createLoopUnswitchPass(bool Os) { 
122   return new LoopUnswitch(Os); 
123 }
124
125 /// FindLIVLoopCondition - Cond is a condition that occurs in L.  If it is
126 /// invariant in the loop, or has an invariant piece, return the invariant.
127 /// Otherwise, return null.
128 static Value *FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed) {
129   // Constants should be folded, not unswitched on!
130   if (isa<Constant>(Cond)) return false;
131
132   // If cond is not in loop then it is not suitable.
133   if (Instruction *I = dyn_cast<Instruction>(Cond))
134     if (!L->contains(I->getParent()))
135       return 0;
136   if (isa<Argument>(Cond))
137     return 0;
138   
139   // TODO: Handle: br (VARIANT|INVARIANT).
140   // TODO: Hoist simple expressions out of loops.
141   if (L->isLoopInvariant(Cond)) return Cond;
142   
143   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Cond))
144     if (BO->getOpcode() == Instruction::And ||
145         BO->getOpcode() == Instruction::Or) {
146       // If either the left or right side is invariant, we can unswitch on this,
147       // which will cause the branch to go away in one loop and the condition to
148       // simplify in the other one.
149       if (Value *LHS = FindLIVLoopCondition(BO->getOperand(0), L, Changed))
150         return LHS;
151       if (Value *RHS = FindLIVLoopCondition(BO->getOperand(1), L, Changed))
152         return RHS;
153     }
154       
155       return 0;
156 }
157
158 bool LoopUnswitch::runOnLoop(Loop *L, LPPassManager &LPM_Ref) {
159   assert(L->isLCSSAForm());
160   LI = &getAnalysis<LoopInfo>();
161   LPM = &LPM_Ref;
162   bool Changed = false;
163   
164   // Loop over all of the basic blocks in the loop.  If we find an interior
165   // block that is branching on a loop-invariant condition, we can unswitch this
166   // loop.
167   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
168        I != E; ++I) {
169     TerminatorInst *TI = (*I)->getTerminator();
170     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
171       // If this isn't branching on an invariant condition, we can't unswitch
172       // it.
173       if (BI->isConditional()) {
174         // See if this, or some part of it, is loop invariant.  If so, we can
175         // unswitch on it if we desire.
176         Value *LoopCond = FindLIVLoopCondition(BI->getCondition(), L, Changed);
177         if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
178                                              L)) {
179           ++NumBranches;
180           return true;
181         }
182       }      
183     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
184       Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
185       if (LoopCond && SI->getNumCases() > 1) {
186         // Find a value to unswitch on:
187         // FIXME: this should chose the most expensive case!
188         Constant *UnswitchVal = SI->getCaseValue(1);
189         // Do not process same value again and again.
190         if (!UnswitchedVals.insert(UnswitchVal))
191           continue;
192
193         if (UnswitchIfProfitable(LoopCond, UnswitchVal, L)) {
194           ++NumSwitches;
195           return true;
196         }
197       }
198     }
199     
200     // Scan the instructions to check for unswitchable values.
201     for (BasicBlock::iterator BBI = (*I)->begin(), E = (*I)->end(); 
202          BBI != E; ++BBI)
203       if (SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
204         Value *LoopCond = FindLIVLoopCondition(SI->getCondition(), L, Changed);
205         if (LoopCond && UnswitchIfProfitable(LoopCond, ConstantInt::getTrue(),
206                                              L)) {
207           ++NumSelects;
208           return true;
209         }
210       }
211   }
212   
213   assert(L->isLCSSAForm());
214   
215   return Changed;
216 }
217
218 /// isTrivialLoopExitBlock - Check to see if all paths from BB either:
219 ///   1. Exit the loop with no side effects.
220 ///   2. Branch to the latch block with no side-effects.
221 ///
222 /// If these conditions are true, we return true and set ExitBB to the block we
223 /// exit through.
224 ///
225 static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB,
226                                          BasicBlock *&ExitBB,
227                                          std::set<BasicBlock*> &Visited) {
228   if (!Visited.insert(BB).second) {
229     // Already visited and Ok, end of recursion.
230     return true;
231   } else if (!L->contains(BB)) {
232     // Otherwise, this is a loop exit, this is fine so long as this is the
233     // first exit.
234     if (ExitBB != 0) return false;
235     ExitBB = BB;
236     return true;
237   }
238   
239   // Otherwise, this is an unvisited intra-loop node.  Check all successors.
240   for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI) {
241     // Check to see if the successor is a trivial loop exit.
242     if (!isTrivialLoopExitBlockHelper(L, *SI, ExitBB, Visited))
243       return false;
244   }
245
246   // Okay, everything after this looks good, check to make sure that this block
247   // doesn't include any side effects.
248   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
249     if (I->mayWriteToMemory())
250       return false;
251   
252   return true;
253 }
254
255 /// isTrivialLoopExitBlock - Return true if the specified block unconditionally
256 /// leads to an exit from the specified loop, and has no side-effects in the 
257 /// process.  If so, return the block that is exited to, otherwise return null.
258 static BasicBlock *isTrivialLoopExitBlock(Loop *L, BasicBlock *BB) {
259   std::set<BasicBlock*> Visited;
260   Visited.insert(L->getHeader());  // Branches to header are ok.
261   BasicBlock *ExitBB = 0;
262   if (isTrivialLoopExitBlockHelper(L, BB, ExitBB, Visited))
263     return ExitBB;
264   return 0;
265 }
266
267 /// IsTrivialUnswitchCondition - Check to see if this unswitch condition is
268 /// trivial: that is, that the condition controls whether or not the loop does
269 /// anything at all.  If this is a trivial condition, unswitching produces no
270 /// code duplications (equivalently, it produces a simpler loop and a new empty
271 /// loop, which gets deleted).
272 ///
273 /// If this is a trivial condition, return true, otherwise return false.  When
274 /// returning true, this sets Cond and Val to the condition that controls the
275 /// trivial condition: when Cond dynamically equals Val, the loop is known to
276 /// exit.  Finally, this sets LoopExit to the BB that the loop exits to when
277 /// Cond == Val.
278 ///
279 static bool IsTrivialUnswitchCondition(Loop *L, Value *Cond, Constant **Val = 0,
280                                        BasicBlock **LoopExit = 0) {
281   BasicBlock *Header = L->getHeader();
282   TerminatorInst *HeaderTerm = Header->getTerminator();
283   
284   BasicBlock *LoopExitBB = 0;
285   if (BranchInst *BI = dyn_cast<BranchInst>(HeaderTerm)) {
286     // If the header block doesn't end with a conditional branch on Cond, we
287     // can't handle it.
288     if (!BI->isConditional() || BI->getCondition() != Cond)
289       return false;
290   
291     // Check to see if a successor of the branch is guaranteed to go to the
292     // latch block or exit through a one exit block without having any 
293     // side-effects.  If so, determine the value of Cond that causes it to do
294     // this.
295     if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(0)))) {
296       if (Val) *Val = ConstantInt::getTrue();
297     } else if ((LoopExitBB = isTrivialLoopExitBlock(L, BI->getSuccessor(1)))) {
298       if (Val) *Val = ConstantInt::getFalse();
299     }
300   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(HeaderTerm)) {
301     // If this isn't a switch on Cond, we can't handle it.
302     if (SI->getCondition() != Cond) return false;
303     
304     // Check to see if a successor of the switch is guaranteed to go to the
305     // latch block or exit through a one exit block without having any 
306     // side-effects.  If so, determine the value of Cond that causes it to do
307     // this.  Note that we can't trivially unswitch on the default case.
308     for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
309       if ((LoopExitBB = isTrivialLoopExitBlock(L, SI->getSuccessor(i)))) {
310         // Okay, we found a trivial case, remember the value that is trivial.
311         if (Val) *Val = SI->getCaseValue(i);
312         break;
313       }
314   }
315
316   // If we didn't find a single unique LoopExit block, or if the loop exit block
317   // contains phi nodes, this isn't trivial.
318   if (!LoopExitBB || isa<PHINode>(LoopExitBB->begin()))
319     return false;   // Can't handle this.
320   
321   if (LoopExit) *LoopExit = LoopExitBB;
322   
323   // We already know that nothing uses any scalar values defined inside of this
324   // loop.  As such, we just have to check to see if this loop will execute any
325   // side-effecting instructions (e.g. stores, calls, volatile loads) in the
326   // part of the loop that the code *would* execute.  We already checked the
327   // tail, check the header now.
328   for (BasicBlock::iterator I = Header->begin(), E = Header->end(); I != E; ++I)
329     if (I->mayWriteToMemory())
330       return false;
331   return true;
332 }
333
334 /// getLoopUnswitchCost - Return the cost (code size growth) that will happen if
335 /// we choose to unswitch the specified loop on the specified value.
336 ///
337 unsigned LoopUnswitch::getLoopUnswitchCost(Loop *L, Value *LIC) {
338   // If the condition is trivial, always unswitch.  There is no code growth for
339   // this case.
340   if (IsTrivialUnswitchCondition(L, LIC))
341     return 0;
342   
343   // FIXME: This is really overly conservative.  However, more liberal 
344   // estimations have thus far resulted in excessive unswitching, which is bad
345   // both in compile time and in code size.  This should be replaced once
346   // someone figures out how a good estimation.
347   return L->getBlocks().size();
348   
349   unsigned Cost = 0;
350   // FIXME: this is brain dead.  It should take into consideration code
351   // shrinkage.
352   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
353        I != E; ++I) {
354     BasicBlock *BB = *I;
355     // Do not include empty blocks in the cost calculation.  This happen due to
356     // loop canonicalization and will be removed.
357     if (BB->begin() == BasicBlock::iterator(BB->getTerminator()))
358       continue;
359     
360     // Count basic blocks.
361     ++Cost;
362   }
363
364   return Cost;
365 }
366
367 /// UnswitchIfProfitable - We have found that we can unswitch L when
368 /// LoopCond == Val to simplify the loop.  If we decide that this is profitable,
369 /// unswitch the loop, reprocess the pieces, then return true.
370 bool LoopUnswitch::UnswitchIfProfitable(Value *LoopCond, Constant *Val,Loop *L){
371   // Check to see if it would be profitable to unswitch this loop.
372   unsigned Cost = getLoopUnswitchCost(L, LoopCond);
373
374   // Do not do non-trivial unswitch while optimizing for size.
375   if (Cost && OptimizeForSize)
376     return false;
377
378   if (Cost > Threshold) {
379     // FIXME: this should estimate growth by the amount of code shared by the
380     // resultant unswitched loops.
381     //
382     DOUT << "NOT unswitching loop %"
383          << L->getHeader()->getName() << ", cost too high: "
384          << L->getBlocks().size() << "\n";
385     return false;
386   }
387   
388   // If this is a trivial condition to unswitch (which results in no code
389   // duplication), do it now.
390   Constant *CondVal;
391   BasicBlock *ExitBlock;
392   if (IsTrivialUnswitchCondition(L, LoopCond, &CondVal, &ExitBlock)) {
393     UnswitchTrivialCondition(L, LoopCond, CondVal, ExitBlock);
394   } else {
395     UnswitchNontrivialCondition(LoopCond, Val, L);
396   }
397  
398   return true;
399 }
400
401 /// SplitBlock - Split the specified block at the specified instruction - every
402 /// thing before SplitPt stays in Old and everything starting with SplitPt moves
403 /// to a new block.  The two blocks are joined by an unconditional branch and
404 /// the loop info is updated.
405 ///
406 BasicBlock *LoopUnswitch::SplitBlock(BasicBlock *Old, Instruction *SplitPt) {
407   BasicBlock::iterator SplitIt = SplitPt;
408   while (isa<PHINode>(SplitIt))
409     ++SplitIt;
410   BasicBlock *New = Old->splitBasicBlock(SplitIt, Old->getName()+".split");
411
412   // The new block lives in whichever loop the old one did.
413   if (Loop *L = LI->getLoopFor(Old))
414     L->addBasicBlockToLoop(New, *LI);
415
416   return New;
417 }
418
419
420 BasicBlock *LoopUnswitch::SplitEdge(BasicBlock *BB, BasicBlock *Succ) {
421   TerminatorInst *LatchTerm = BB->getTerminator();
422   unsigned SuccNum = 0;
423   for (unsigned i = 0, e = LatchTerm->getNumSuccessors(); ; ++i) {
424     assert(i != e && "Didn't find edge?");
425     if (LatchTerm->getSuccessor(i) == Succ) {
426       SuccNum = i;
427       break;
428     }
429   }
430   
431   // If this is a critical edge, let SplitCriticalEdge do it.
432   Loop *OrigDestBBL = LI->getLoopFor(BB->getTerminator()->getSuccessor(SuccNum));
433   if (SplitCriticalEdge(BB->getTerminator(), SuccNum)) {
434     BasicBlock *NewBB = LatchTerm->getSuccessor(SuccNum);
435
436     Loop *BBL = LI->getLoopFor(BB);
437     if (!BBL || !OrigDestBBL)
438       return NewBB;
439
440     // If edge is inside a loop then NewBB is part of same loop.
441     if (BBL == OrigDestBBL)
442       BBL->addBasicBlockToLoop(NewBB, *LI);
443     // If edge is entering loop then NewBB is part of outer loop.
444     else if (BBL->contains(OrigDestBBL->getHeader()))
445       BBL->addBasicBlockToLoop(NewBB, *LI);
446     // If edge is from an inner loop to outer loop then NewBB is part
447     // of outer loop.
448     else if (OrigDestBBL->contains(BBL->getHeader()))
449       OrigDestBBL->addBasicBlockToLoop(NewBB, *LI);
450     // Else edge is connecting two loops and NewBB is part of their parent loop
451     else if (Loop *PL = OrigDestBBL->getParentLoop())
452       PL->addBasicBlockToLoop(NewBB, *LI);
453
454     return NewBB;
455   }
456
457   // If the edge isn't critical, then BB has a single successor or Succ has a
458   // single pred.  Split the block.
459   BasicBlock::iterator SplitPoint;
460   if (BasicBlock *SP = Succ->getSinglePredecessor()) {
461     // If the successor only has a single pred, split the top of the successor
462     // block.
463     assert(SP == BB && "CFG broken");
464     return SplitBlock(Succ, Succ->begin());
465   } else {
466     // Otherwise, if BB has a single successor, split it at the bottom of the
467     // block.
468     assert(BB->getTerminator()->getNumSuccessors() == 1 &&
469            "Should have a single succ!"); 
470     return SplitBlock(BB, BB->getTerminator());
471   }
472 }
473   
474
475
476 // RemapInstruction - Convert the instruction operands from referencing the
477 // current values into those specified by ValueMap.
478 //
479 static inline void RemapInstruction(Instruction *I,
480                                     DenseMap<const Value *, Value*> &ValueMap) {
481   for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
482     Value *Op = I->getOperand(op);
483     DenseMap<const Value *, Value*>::iterator It = ValueMap.find(Op);
484     if (It != ValueMap.end()) Op = It->second;
485     I->setOperand(op, Op);
486   }
487 }
488
489 /// CloneLoop - Recursively clone the specified loop and all of its children,
490 /// mapping the blocks with the specified map.
491 static Loop *CloneLoop(Loop *L, Loop *PL, DenseMap<const Value*, Value*> &VM,
492                        LoopInfo *LI, LPPassManager *LPM) {
493   Loop *New = new Loop();
494
495   LPM->insertLoop(New, PL);
496
497   // Add all of the blocks in L to the new loop.
498   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
499        I != E; ++I)
500     if (LI->getLoopFor(*I) == L)
501       New->addBasicBlockToLoop(cast<BasicBlock>(VM[*I]), *LI);
502
503   // Add all of the subloops to the new loop.
504   for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
505     CloneLoop(*I, New, VM, LI, LPM);
506
507   return New;
508 }
509
510 /// EmitPreheaderBranchOnCondition - Emit a conditional branch on two values
511 /// if LIC == Val, branch to TrueDst, otherwise branch to FalseDest.  Insert the
512 /// code immediately before InsertPt.
513 static void EmitPreheaderBranchOnCondition(Value *LIC, Constant *Val,
514                                            BasicBlock *TrueDest,
515                                            BasicBlock *FalseDest,
516                                            Instruction *InsertPt) {
517   // Insert a conditional branch on LIC to the two preheaders.  The original
518   // code is the true version and the new code is the false version.
519   Value *BranchVal = LIC;
520   if (!isa<ConstantInt>(Val) || Val->getType() != Type::Int1Ty)
521     BranchVal = new ICmpInst(ICmpInst::ICMP_EQ, LIC, Val, "tmp", InsertPt);
522   else if (Val != ConstantInt::getTrue())
523     // We want to enter the new loop when the condition is true.
524     std::swap(TrueDest, FalseDest);
525
526   // Insert the new branch.
527   new BranchInst(TrueDest, FalseDest, BranchVal, InsertPt);
528 }
529
530
531 /// UnswitchTrivialCondition - Given a loop that has a trivial unswitchable
532 /// condition in it (a cond branch from its header block to its latch block,
533 /// where the path through the loop that doesn't execute its body has no 
534 /// side-effects), unswitch it.  This doesn't involve any code duplication, just
535 /// moving the conditional branch outside of the loop and updating loop info.
536 void LoopUnswitch::UnswitchTrivialCondition(Loop *L, Value *Cond, 
537                                             Constant *Val, 
538                                             BasicBlock *ExitBlock) {
539   DOUT << "loop-unswitch: Trivial-Unswitch loop %"
540        << L->getHeader()->getName() << " [" << L->getBlocks().size()
541        << " blocks] in Function " << L->getHeader()->getParent()->getName()
542        << " on cond: " << *Val << " == " << *Cond << "\n";
543   
544   // First step, split the preheader, so that we know that there is a safe place
545   // to insert the conditional branch.  We will change 'OrigPH' to have a
546   // conditional branch on Cond.
547   BasicBlock *OrigPH = L->getLoopPreheader();
548   BasicBlock *NewPH = SplitEdge(OrigPH, L->getHeader());
549
550   // Now that we have a place to insert the conditional branch, create a place
551   // to branch to: this is the exit block out of the loop that we should
552   // short-circuit to.
553   
554   // Split this block now, so that the loop maintains its exit block, and so
555   // that the jump from the preheader can execute the contents of the exit block
556   // without actually branching to it (the exit block should be dominated by the
557   // loop header, not the preheader).
558   assert(!L->contains(ExitBlock) && "Exit block is in the loop?");
559   BasicBlock *NewExit = SplitBlock(ExitBlock, ExitBlock->begin());
560     
561   // Okay, now we have a position to branch from and a position to branch to, 
562   // insert the new conditional branch.
563   EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH, 
564                                  OrigPH->getTerminator());
565   OrigPH->getTerminator()->eraseFromParent();
566
567   // We need to reprocess this loop, it could be unswitched again.
568   LPM->redoLoop(L);
569   
570   // Now that we know that the loop is never entered when this condition is a
571   // particular value, rewrite the loop with this info.  We know that this will
572   // at least eliminate the old branch.
573   RewriteLoopBodyWithConditionConstant(L, Cond, Val, false);
574   ++NumTrivial;
575 }
576
577
578 /// VersionLoop - We determined that the loop is profitable to unswitch when LIC
579 /// equal Val.  Split it into loop versions and test the condition outside of
580 /// either loop.  Return the loops created as Out1/Out2.
581 void LoopUnswitch::UnswitchNontrivialCondition(Value *LIC, Constant *Val, 
582                                                Loop *L) {
583   Function *F = L->getHeader()->getParent();
584   DOUT << "loop-unswitch: Unswitching loop %"
585        << L->getHeader()->getName() << " [" << L->getBlocks().size()
586        << " blocks] in Function " << F->getName()
587        << " when '" << *Val << "' == " << *LIC << "\n";
588
589   // LoopBlocks contains all of the basic blocks of the loop, including the
590   // preheader of the loop, the body of the loop, and the exit blocks of the 
591   // loop, in that order.
592   std::vector<BasicBlock*> LoopBlocks;
593
594   // First step, split the preheader and exit blocks, and add these blocks to
595   // the LoopBlocks list.
596   BasicBlock *OrigPreheader = L->getLoopPreheader();
597   LoopBlocks.push_back(SplitEdge(OrigPreheader, L->getHeader()));
598
599   // We want the loop to come after the preheader, but before the exit blocks.
600   LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
601
602   std::vector<BasicBlock*> ExitBlocks;
603   L->getUniqueExitBlocks(ExitBlocks);
604
605   // Split all of the edges from inside the loop to their exit blocks.  Update
606   // the appropriate Phi nodes as we do so.
607   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
608     BasicBlock *ExitBlock = ExitBlocks[i];
609     std::vector<BasicBlock*> Preds(pred_begin(ExitBlock), pred_end(ExitBlock));
610
611     for (unsigned j = 0, e = Preds.size(); j != e; ++j) {
612       BasicBlock* MiddleBlock = SplitEdge(Preds[j], ExitBlock);
613       BasicBlock* StartBlock = Preds[j];
614       BasicBlock* EndBlock;
615       if (MiddleBlock->getSinglePredecessor() == ExitBlock) {
616         EndBlock = MiddleBlock;
617         MiddleBlock = EndBlock->getSinglePredecessor();;
618       } else {
619         EndBlock = ExitBlock;
620       }
621       
622       std::set<PHINode*> InsertedPHIs;
623       PHINode* OldLCSSA = 0;
624       for (BasicBlock::iterator I = EndBlock->begin();
625            (OldLCSSA = dyn_cast<PHINode>(I)); ++I) {
626         Value* OldValue = OldLCSSA->getIncomingValueForBlock(MiddleBlock);
627         PHINode* NewLCSSA = new PHINode(OldLCSSA->getType(),
628                                         OldLCSSA->getName() + ".us-lcssa",
629                                         MiddleBlock->getTerminator());
630         NewLCSSA->addIncoming(OldValue, StartBlock);
631         OldLCSSA->setIncomingValue(OldLCSSA->getBasicBlockIndex(MiddleBlock),
632                                    NewLCSSA);
633         InsertedPHIs.insert(NewLCSSA);
634       }
635
636       BasicBlock::iterator InsertPt = EndBlock->begin();
637       while (dyn_cast<PHINode>(InsertPt)) ++InsertPt;
638       for (BasicBlock::iterator I = MiddleBlock->begin();
639          (OldLCSSA = dyn_cast<PHINode>(I)) && InsertedPHIs.count(OldLCSSA) == 0;
640          ++I) {
641         PHINode *NewLCSSA = new PHINode(OldLCSSA->getType(),
642                                         OldLCSSA->getName() + ".us-lcssa",
643                                         InsertPt);
644         OldLCSSA->replaceAllUsesWith(NewLCSSA);
645         NewLCSSA->addIncoming(OldLCSSA, MiddleBlock);
646       }
647     }    
648   }
649   
650   // The exit blocks may have been changed due to edge splitting, recompute.
651   ExitBlocks.clear();
652   L->getUniqueExitBlocks(ExitBlocks);
653
654   // Add exit blocks to the loop blocks.
655   LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.begin(), ExitBlocks.end());
656
657   // Next step, clone all of the basic blocks that make up the loop (including
658   // the loop preheader and exit blocks), keeping track of the mapping between
659   // the instructions and blocks.
660   std::vector<BasicBlock*> NewBlocks;
661   NewBlocks.reserve(LoopBlocks.size());
662   DenseMap<const Value*, Value*> ValueMap;
663   for (unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
664     BasicBlock *New = CloneBasicBlock(LoopBlocks[i], ValueMap, ".us", F);
665     NewBlocks.push_back(New);
666     ValueMap[LoopBlocks[i]] = New;  // Keep the BB mapping.
667   }
668
669   // Splice the newly inserted blocks into the function right before the
670   // original preheader.
671   F->getBasicBlockList().splice(LoopBlocks[0], F->getBasicBlockList(),
672                                 NewBlocks[0], F->end());
673
674   // Now we create the new Loop object for the versioned loop.
675   Loop *NewLoop = CloneLoop(L, L->getParentLoop(), ValueMap, LI, LPM);
676   Loop *ParentLoop = L->getParentLoop();
677   if (ParentLoop) {
678     // Make sure to add the cloned preheader and exit blocks to the parent loop
679     // as well.
680     ParentLoop->addBasicBlockToLoop(NewBlocks[0], *LI);
681   }
682   
683   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
684     BasicBlock *NewExit = cast<BasicBlock>(ValueMap[ExitBlocks[i]]);
685     // The new exit block should be in the same loop as the old one.
686     if (Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
687       ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
688     
689     assert(NewExit->getTerminator()->getNumSuccessors() == 1 &&
690            "Exit block should have been split to have one successor!");
691     BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
692     
693     // If the successor of the exit block had PHI nodes, add an entry for
694     // NewExit.
695     PHINode *PN;
696     for (BasicBlock::iterator I = ExitSucc->begin();
697          (PN = dyn_cast<PHINode>(I)); ++I) {
698       Value *V = PN->getIncomingValueForBlock(ExitBlocks[i]);
699       DenseMap<const Value *, Value*>::iterator It = ValueMap.find(V);
700       if (It != ValueMap.end()) V = It->second;
701       PN->addIncoming(V, NewExit);
702     }
703   }
704
705   // Rewrite the code to refer to itself.
706   for (unsigned i = 0, e = NewBlocks.size(); i != e; ++i)
707     for (BasicBlock::iterator I = NewBlocks[i]->begin(),
708            E = NewBlocks[i]->end(); I != E; ++I)
709       RemapInstruction(I, ValueMap);
710   
711   // Rewrite the original preheader to select between versions of the loop.
712   BranchInst *OldBR = cast<BranchInst>(OrigPreheader->getTerminator());
713   assert(OldBR->isUnconditional() && OldBR->getSuccessor(0) == LoopBlocks[0] &&
714          "Preheader splitting did not work correctly!");
715
716   // Emit the new branch that selects between the two versions of this loop.
717   EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR);
718   OldBR->eraseFromParent();
719   
720   LoopProcessWorklist.push_back(NewLoop);
721   LPM->redoLoop(L);
722
723   // Now we rewrite the original code to know that the condition is true and the
724   // new code to know that the condition is false.
725   RewriteLoopBodyWithConditionConstant(L      , LIC, Val, false);
726   
727   // It's possible that simplifying one loop could cause the other to be
728   // deleted.  If so, don't simplify it.
729   if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop)
730     RewriteLoopBodyWithConditionConstant(NewLoop, LIC, Val, true);
731 }
732
733 /// RemoveFromWorklist - Remove all instances of I from the worklist vector
734 /// specified.
735 static void RemoveFromWorklist(Instruction *I, 
736                                std::vector<Instruction*> &Worklist) {
737   std::vector<Instruction*>::iterator WI = std::find(Worklist.begin(),
738                                                      Worklist.end(), I);
739   while (WI != Worklist.end()) {
740     unsigned Offset = WI-Worklist.begin();
741     Worklist.erase(WI);
742     WI = std::find(Worklist.begin()+Offset, Worklist.end(), I);
743   }
744 }
745
746 /// ReplaceUsesOfWith - When we find that I really equals V, remove I from the
747 /// program, replacing all uses with V and update the worklist.
748 static void ReplaceUsesOfWith(Instruction *I, Value *V, 
749                               std::vector<Instruction*> &Worklist) {
750   DOUT << "Replace with '" << *V << "': " << *I;
751
752   // Add uses to the worklist, which may be dead now.
753   for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
754     if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
755       Worklist.push_back(Use);
756
757   // Add users to the worklist which may be simplified now.
758   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
759        UI != E; ++UI)
760     Worklist.push_back(cast<Instruction>(*UI));
761   I->replaceAllUsesWith(V);
762   I->eraseFromParent();
763   RemoveFromWorklist(I, Worklist);
764   ++NumSimplify;
765 }
766
767 /// RemoveBlockIfDead - If the specified block is dead, remove it, update loop
768 /// information, and remove any dead successors it has.
769 ///
770 void LoopUnswitch::RemoveBlockIfDead(BasicBlock *BB,
771                                      std::vector<Instruction*> &Worklist) {
772   if (pred_begin(BB) != pred_end(BB)) {
773     // This block isn't dead, since an edge to BB was just removed, see if there
774     // are any easy simplifications we can do now.
775     if (BasicBlock *Pred = BB->getSinglePredecessor()) {
776       // If it has one pred, fold phi nodes in BB.
777       while (isa<PHINode>(BB->begin()))
778         ReplaceUsesOfWith(BB->begin(), 
779                           cast<PHINode>(BB->begin())->getIncomingValue(0), 
780                           Worklist);
781       
782       // If this is the header of a loop and the only pred is the latch, we now
783       // have an unreachable loop.
784       if (Loop *L = LI->getLoopFor(BB))
785         if (L->getHeader() == BB && L->contains(Pred)) {
786           // Remove the branch from the latch to the header block, this makes
787           // the header dead, which will make the latch dead (because the header
788           // dominates the latch).
789           Pred->getTerminator()->eraseFromParent();
790           new UnreachableInst(Pred);
791           
792           // The loop is now broken, remove it from LI.
793           RemoveLoopFromHierarchy(L);
794           
795           // Reprocess the header, which now IS dead.
796           RemoveBlockIfDead(BB, Worklist);
797           return;
798         }
799       
800       // If pred ends in a uncond branch, add uncond branch to worklist so that
801       // the two blocks will get merged.
802       if (BranchInst *BI = dyn_cast<BranchInst>(Pred->getTerminator()))
803         if (BI->isUnconditional())
804           Worklist.push_back(BI);
805     }
806     return;
807   }
808
809   DOUT << "Nuking dead block: " << *BB;
810   
811   // Remove the instructions in the basic block from the worklist.
812   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
813     RemoveFromWorklist(I, Worklist);
814     
815     // Anything that uses the instructions in this basic block should have their
816     // uses replaced with undefs.
817     if (!I->use_empty())
818       I->replaceAllUsesWith(UndefValue::get(I->getType()));
819   }
820   
821   // If this is the edge to the header block for a loop, remove the loop and
822   // promote all subloops.
823   if (Loop *BBLoop = LI->getLoopFor(BB)) {
824     if (BBLoop->getLoopLatch() == BB)
825       RemoveLoopFromHierarchy(BBLoop);
826   }
827
828   // Remove the block from the loop info, which removes it from any loops it
829   // was in.
830   LI->removeBlock(BB);
831   
832   
833   // Remove phi node entries in successors for this block.
834   TerminatorInst *TI = BB->getTerminator();
835   std::vector<BasicBlock*> Succs;
836   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
837     Succs.push_back(TI->getSuccessor(i));
838     TI->getSuccessor(i)->removePredecessor(BB);
839   }
840   
841   // Unique the successors, remove anything with multiple uses.
842   std::sort(Succs.begin(), Succs.end());
843   Succs.erase(std::unique(Succs.begin(), Succs.end()), Succs.end());
844   
845   // Remove the basic block, including all of the instructions contained in it.
846   BB->eraseFromParent();
847   
848   // Remove successor blocks here that are not dead, so that we know we only
849   // have dead blocks in this list.  Nondead blocks have a way of becoming dead,
850   // then getting removed before we revisit them, which is badness.
851   //
852   for (unsigned i = 0; i != Succs.size(); ++i)
853     if (pred_begin(Succs[i]) != pred_end(Succs[i])) {
854       // One exception is loop headers.  If this block was the preheader for a
855       // loop, then we DO want to visit the loop so the loop gets deleted.
856       // We know that if the successor is a loop header, that this loop had to
857       // be the preheader: the case where this was the latch block was handled
858       // above and headers can only have two predecessors.
859       if (!LI->isLoopHeader(Succs[i])) {
860         Succs.erase(Succs.begin()+i);
861         --i;
862       }
863     }
864   
865   for (unsigned i = 0, e = Succs.size(); i != e; ++i)
866     RemoveBlockIfDead(Succs[i], Worklist);
867 }
868
869 /// RemoveLoopFromHierarchy - We have discovered that the specified loop has
870 /// become unwrapped, either because the backedge was deleted, or because the
871 /// edge into the header was removed.  If the edge into the header from the
872 /// latch block was removed, the loop is unwrapped but subloops are still alive,
873 /// so they just reparent loops.  If the loops are actually dead, they will be
874 /// removed later.
875 void LoopUnswitch::RemoveLoopFromHierarchy(Loop *L) {
876   LPM->deleteLoopFromQueue(L);
877   RemoveLoopFromWorklist(L);
878 }
879
880
881
882 // RewriteLoopBodyWithConditionConstant - We know either that the value LIC has
883 // the value specified by Val in the specified loop, or we know it does NOT have
884 // that value.  Rewrite any uses of LIC or of properties correlated to it.
885 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(Loop *L, Value *LIC,
886                                                         Constant *Val,
887                                                         bool IsEqual) {
888   assert(!isa<Constant>(LIC) && "Why are we unswitching on a constant?");
889   
890   // FIXME: Support correlated properties, like:
891   //  for (...)
892   //    if (li1 < li2)
893   //      ...
894   //    if (li1 > li2)
895   //      ...
896   
897   // FOLD boolean conditions (X|LIC), (X&LIC).  Fold conditional branches,
898   // selects, switches.
899   std::vector<User*> Users(LIC->use_begin(), LIC->use_end());
900   std::vector<Instruction*> Worklist;
901
902   // If we know that LIC == Val, or that LIC == NotVal, just replace uses of LIC
903   // in the loop with the appropriate one directly.
904   if (IsEqual || (isa<ConstantInt>(Val) && Val->getType() == Type::Int1Ty)) {
905     Value *Replacement;
906     if (IsEqual)
907       Replacement = Val;
908     else
909       Replacement = ConstantInt::get(Type::Int1Ty, 
910                                      !cast<ConstantInt>(Val)->getZExtValue());
911     
912     for (unsigned i = 0, e = Users.size(); i != e; ++i)
913       if (Instruction *U = cast<Instruction>(Users[i])) {
914         if (!L->contains(U->getParent()))
915           continue;
916         U->replaceUsesOfWith(LIC, Replacement);
917         Worklist.push_back(U);
918       }
919   } else {
920     // Otherwise, we don't know the precise value of LIC, but we do know that it
921     // is certainly NOT "Val".  As such, simplify any uses in the loop that we
922     // can.  This case occurs when we unswitch switch statements.
923     for (unsigned i = 0, e = Users.size(); i != e; ++i)
924       if (Instruction *U = cast<Instruction>(Users[i])) {
925         if (!L->contains(U->getParent()))
926           continue;
927
928         Worklist.push_back(U);
929
930         // If we know that LIC is not Val, use this info to simplify code.
931         if (SwitchInst *SI = dyn_cast<SwitchInst>(U)) {
932           for (unsigned i = 1, e = SI->getNumCases(); i != e; ++i) {
933             if (SI->getCaseValue(i) == Val) {
934               // Found a dead case value.  Don't remove PHI nodes in the 
935               // successor if they become single-entry, those PHI nodes may
936               // be in the Users list.
937               
938               // FIXME: This is a hack.  We need to keep the successor around
939               // and hooked up so as to preserve the loop structure, because
940               // trying to update it is complicated.  So instead we preserve the
941               // loop structure and put the block on an dead code path.
942               
943               BasicBlock* Old = SI->getParent();
944               BasicBlock* Split = SplitBlock(Old, SI);
945               
946               Instruction* OldTerm = Old->getTerminator();
947               new BranchInst(Split, SI->getSuccessor(i),
948                              ConstantInt::getTrue(), OldTerm);
949               
950               Old->getTerminator()->eraseFromParent();
951               
952               
953               PHINode *PN;
954               for (BasicBlock::iterator II = SI->getSuccessor(i)->begin();
955                    (PN = dyn_cast<PHINode>(II)); ++II) {
956                 Value *InVal = PN->removeIncomingValue(Split, false);
957                 PN->addIncoming(InVal, Old);
958               }
959
960               SI->removeCase(i);
961               break;
962             }
963           }
964         }
965         
966         // TODO: We could do other simplifications, for example, turning 
967         // LIC == Val -> false.
968       }
969   }
970   
971   SimplifyCode(Worklist);
972 }
973
974 /// SimplifyCode - Okay, now that we have simplified some instructions in the 
975 /// loop, walk over it and constant prop, dce, and fold control flow where
976 /// possible.  Note that this is effectively a very simple loop-structure-aware
977 /// optimizer.  During processing of this loop, L could very well be deleted, so
978 /// it must not be used.
979 ///
980 /// FIXME: When the loop optimizer is more mature, separate this out to a new
981 /// pass.
982 ///
983 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist) {
984   while (!Worklist.empty()) {
985     Instruction *I = Worklist.back();
986     Worklist.pop_back();
987     
988     // Simple constant folding.
989     if (Constant *C = ConstantFoldInstruction(I)) {
990       ReplaceUsesOfWith(I, C, Worklist);
991       continue;
992     }
993     
994     // Simple DCE.
995     if (isInstructionTriviallyDead(I)) {
996       DOUT << "Remove dead instruction '" << *I;
997       
998       // Add uses to the worklist, which may be dead now.
999       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1000         if (Instruction *Use = dyn_cast<Instruction>(I->getOperand(i)))
1001           Worklist.push_back(Use);
1002       I->eraseFromParent();
1003       RemoveFromWorklist(I, Worklist);
1004       ++NumSimplify;
1005       continue;
1006     }
1007     
1008     // Special case hacks that appear commonly in unswitched code.
1009     switch (I->getOpcode()) {
1010     case Instruction::Select:
1011       if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(0))) {
1012         ReplaceUsesOfWith(I, I->getOperand(!CB->getZExtValue()+1), Worklist);
1013         continue;
1014       }
1015       break;
1016     case Instruction::And:
1017       if (isa<ConstantInt>(I->getOperand(0)) && 
1018           I->getOperand(0)->getType() == Type::Int1Ty)   // constant -> RHS
1019         cast<BinaryOperator>(I)->swapOperands();
1020       if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1))) 
1021         if (CB->getType() == Type::Int1Ty) {
1022           if (CB->isOne())      // X & 1 -> X
1023             ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1024           else                  // X & 0 -> 0
1025             ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1026           continue;
1027         }
1028       break;
1029     case Instruction::Or:
1030       if (isa<ConstantInt>(I->getOperand(0)) &&
1031           I->getOperand(0)->getType() == Type::Int1Ty)   // constant -> RHS
1032         cast<BinaryOperator>(I)->swapOperands();
1033       if (ConstantInt *CB = dyn_cast<ConstantInt>(I->getOperand(1)))
1034         if (CB->getType() == Type::Int1Ty) {
1035           if (CB->isOne())   // X | 1 -> 1
1036             ReplaceUsesOfWith(I, I->getOperand(1), Worklist);
1037           else                  // X | 0 -> X
1038             ReplaceUsesOfWith(I, I->getOperand(0), Worklist);
1039           continue;
1040         }
1041       break;
1042     case Instruction::Br: {
1043       BranchInst *BI = cast<BranchInst>(I);
1044       if (BI->isUnconditional()) {
1045         // If BI's parent is the only pred of the successor, fold the two blocks
1046         // together.
1047         BasicBlock *Pred = BI->getParent();
1048         BasicBlock *Succ = BI->getSuccessor(0);
1049         BasicBlock *SinglePred = Succ->getSinglePredecessor();
1050         if (!SinglePred) continue;  // Nothing to do.
1051         assert(SinglePred == Pred && "CFG broken");
1052
1053         DOUT << "Merging blocks: " << Pred->getName() << " <- " 
1054              << Succ->getName() << "\n";
1055         
1056         // Resolve any single entry PHI nodes in Succ.
1057         while (PHINode *PN = dyn_cast<PHINode>(Succ->begin()))
1058           ReplaceUsesOfWith(PN, PN->getIncomingValue(0), Worklist);
1059         
1060         // Move all of the successor contents from Succ to Pred.
1061         Pred->getInstList().splice(BI, Succ->getInstList(), Succ->begin(),
1062                                    Succ->end());
1063         BI->eraseFromParent();
1064         RemoveFromWorklist(BI, Worklist);
1065         
1066         // If Succ has any successors with PHI nodes, update them to have
1067         // entries coming from Pred instead of Succ.
1068         Succ->replaceAllUsesWith(Pred);
1069         
1070         // Remove Succ from the loop tree.
1071         LI->removeBlock(Succ);
1072         Succ->eraseFromParent();
1073         ++NumSimplify;
1074       } else if (ConstantInt *CB = dyn_cast<ConstantInt>(BI->getCondition())){
1075         // Conditional branch.  Turn it into an unconditional branch, then
1076         // remove dead blocks.
1077         break;  // FIXME: Enable.
1078
1079         DOUT << "Folded branch: " << *BI;
1080         BasicBlock *DeadSucc = BI->getSuccessor(CB->getZExtValue());
1081         BasicBlock *LiveSucc = BI->getSuccessor(!CB->getZExtValue());
1082         DeadSucc->removePredecessor(BI->getParent(), true);
1083         Worklist.push_back(new BranchInst(LiveSucc, BI));
1084         BI->eraseFromParent();
1085         RemoveFromWorklist(BI, Worklist);
1086         ++NumSimplify;
1087
1088         RemoveBlockIfDead(DeadSucc, Worklist);
1089       }
1090       break;
1091     }
1092     }
1093   }
1094 }