LoopIndexSplit doesn't actually use ScalarEvolution.
[oota-llvm.git] / lib / Transforms / Scalar / LoopIndexSplit.cpp
1 //===- LoopIndexSplit.cpp - Loop Index Splitting Pass ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements Loop Index Splitting Pass. This pass handles three
11 // kinds of loops.
12 //
13 // [1] Loop is eliminated when loop body is executed only once. For example,
14 // for (i = 0; i < N; ++i) {
15 //   if ( i == X) {
16 //     ...
17 //   }
18 // }
19 //
20 // [2] Loop's iteration space is shrunk if loop body is executed for certain
21 //     range only. For example,
22 // 
23 // for (i = 0; i < N; ++i) {
24 //   if ( i > A && i < B) {
25 //     ...
26 //   }
27 // }
28 // is trnasformed to iterators from A to B, if A > 0 and B < N.
29 //
30 // [3] Loop is split if the loop body is dominated by an branch. For example,
31 //
32 // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
33 //
34 // is transformed into
35 // AEV = BSV = SV
36 // for (i = LB; i < min(UB, AEV); ++i)
37 //    A;
38 // for (i = max(LB, BSV); i < UB; ++i);
39 //    B;
40 //===----------------------------------------------------------------------===//
41
42 #define DEBUG_TYPE "loop-index-split"
43
44 #include "llvm/Transforms/Scalar.h"
45 #include "llvm/IntrinsicInst.h"
46 #include "llvm/Analysis/LoopPass.h"
47 #include "llvm/Analysis/ScalarEvolution.h"
48 #include "llvm/Analysis/Dominators.h"
49 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
50 #include "llvm/Transforms/Utils/Cloning.h"
51 #include "llvm/Support/Compiler.h"
52 #include "llvm/ADT/DepthFirstIterator.h"
53 #include "llvm/ADT/Statistic.h"
54
55 using namespace llvm;
56
57 STATISTIC(NumIndexSplit, "Number of loop index split");
58 STATISTIC(NumIndexSplitRemoved, "Number of loops eliminated by loop index split");
59 STATISTIC(NumRestrictBounds, "Number of loop iteration space restricted");
60
61 namespace {
62
63   class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
64
65   public:
66     static char ID; // Pass ID, replacement for typeid
67     LoopIndexSplit() : LoopPass(&ID) {}
68
69     // Index split Loop L. Return true if loop is split.
70     bool runOnLoop(Loop *L, LPPassManager &LPM);
71
72     void getAnalysisUsage(AnalysisUsage &AU) const {
73       AU.addPreserved<ScalarEvolution>();
74       AU.addRequiredID(LCSSAID);
75       AU.addPreservedID(LCSSAID);
76       AU.addRequired<LoopInfo>();
77       AU.addPreserved<LoopInfo>();
78       AU.addRequiredID(LoopSimplifyID);
79       AU.addPreservedID(LoopSimplifyID);
80       AU.addRequired<DominatorTree>();
81       AU.addRequired<DominanceFrontier>();
82       AU.addPreserved<DominatorTree>();
83       AU.addPreserved<DominanceFrontier>();
84     }
85
86   private:
87     /// processOneIterationLoop -- Eliminate loop if loop body is executed 
88     /// only once. For example,
89     /// for (i = 0; i < N; ++i) {
90     ///   if ( i == X) {
91     ///     ...
92     ///   }
93     /// }
94     ///
95     bool processOneIterationLoop();
96
97     // -- Routines used by updateLoopIterationSpace();
98
99     /// updateLoopIterationSpace -- Update loop's iteration space if loop 
100     /// body is executed for certain IV range only. For example,
101     /// 
102     /// for (i = 0; i < N; ++i) {
103     ///   if ( i > A && i < B) {
104     ///     ...
105     ///   }
106     /// }
107     /// is transformed to iterators from A to B, if A > 0 and B < N.
108     ///
109     bool updateLoopIterationSpace();
110
111     /// restrictLoopBound - Op dominates loop body. Op compares an IV based value
112     /// with a loop invariant value. Update loop's lower and upper bound based on
113     /// the loop invariant value.
114     bool restrictLoopBound(ICmpInst &Op);
115
116     // --- Routines used by splitLoop(). --- /
117
118     bool splitLoop();
119
120     /// removeBlocks - Remove basic block DeadBB and all blocks dominated by 
121     /// DeadBB. This routine is used to remove split condition's dead branch, 
122     /// dominated by DeadBB. LiveBB dominates split conidition's other branch.
123     void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
124     
125     /// moveExitCondition - Move exit condition EC into split condition block.
126     void moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
127                            BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
128                            PHINode *IV, Instruction *IVAdd, Loop *LP,
129                            unsigned);
130     
131     /// updatePHINodes - CFG has been changed. 
132     /// Before 
133     ///   - ExitBB's single predecessor was Latch
134     ///   - Latch's second successor was Header
135     /// Now
136     ///   - ExitBB's single predecessor was Header
137     ///   - Latch's one and only successor was Header
138     ///
139     /// Update ExitBB PHINodes' to reflect this change.
140     void updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch, 
141                         BasicBlock *Header,
142                         PHINode *IV, Instruction *IVIncrement, Loop *LP);
143
144     // --- Utility routines --- /
145
146     /// cleanBlock - A block is considered clean if all non terminal 
147     /// instructions are either PHINodes or IV based values.
148     bool cleanBlock(BasicBlock *BB);
149
150     /// IVisLT - If Op is comparing IV based value with an loop invariant and 
151     /// IV based value is less than  the loop invariant then return the loop 
152     /// invariant. Otherwise return NULL.
153     Value * IVisLT(ICmpInst &Op);
154
155     /// IVisLE - If Op is comparing IV based value with an loop invariant and 
156     /// IV based value is less than or equal to the loop invariant then 
157     /// return the loop invariant. Otherwise return NULL.
158     Value * IVisLE(ICmpInst &Op);
159
160     /// IVisGT - If Op is comparing IV based value with an loop invariant and 
161     /// IV based value is greater than  the loop invariant then return the loop 
162     /// invariant. Otherwise return NULL.
163     Value * IVisGT(ICmpInst &Op);
164
165     /// IVisGE - If Op is comparing IV based value with an loop invariant and 
166     /// IV based value is greater than or equal to the loop invariant then 
167     /// return the loop invariant. Otherwise return NULL.
168     Value * IVisGE(ICmpInst &Op);
169
170   private:
171
172     // Current Loop information.
173     Loop *L;
174     LPPassManager *LPM;
175     LoopInfo *LI;
176     DominatorTree *DT;
177     DominanceFrontier *DF;
178
179     PHINode *IndVar;
180     ICmpInst *ExitCondition;
181     ICmpInst *SplitCondition;
182     Value *IVStartValue;
183     Value *IVExitValue;
184     Instruction *IVIncrement;
185     SmallPtrSet<Value *, 4> IVBasedValues;
186   };
187 }
188
189 char LoopIndexSplit::ID = 0;
190 static RegisterPass<LoopIndexSplit>
191 X("loop-index-split", "Index Split Loops");
192
193 Pass *llvm::createLoopIndexSplitPass() {
194   return new LoopIndexSplit();
195 }
196
197 // Index split Loop L. Return true if loop is split.
198 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
199   L = IncomingLoop;
200   LPM = &LPM_Ref;
201
202   // FIXME - Nested loops make dominator info updates tricky. 
203   if (!L->getSubLoops().empty())
204     return false;
205
206   DT = &getAnalysis<DominatorTree>();
207   LI = &getAnalysis<LoopInfo>();
208   DF = &getAnalysis<DominanceFrontier>();
209
210   // Initialize loop data.
211   IndVar = L->getCanonicalInductionVariable();
212   if (!IndVar) return false;
213
214   bool P1InLoop = L->contains(IndVar->getIncomingBlock(1));
215   IVStartValue = IndVar->getIncomingValue(!P1InLoop);
216   IVIncrement = dyn_cast<Instruction>(IndVar->getIncomingValue(P1InLoop));
217   if (!IVIncrement) return false;
218   
219   IVBasedValues.clear();
220   IVBasedValues.insert(IndVar);
221   IVBasedValues.insert(IVIncrement);
222   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
223        I != E; ++I) 
224     for(BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end(); 
225         BI != BE; ++BI) {
226       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(BI)) 
227         if (BO != IVIncrement 
228             && (BO->getOpcode() == Instruction::Add
229                 || BO->getOpcode() == Instruction::Sub))
230           if (IVBasedValues.count(BO->getOperand(0))
231               && L->isLoopInvariant(BO->getOperand(1)))
232             IVBasedValues.insert(BO);
233     }
234
235   // Reject loop if loop exit condition is not suitable.
236   BasicBlock *ExitingBlock = L->getExitingBlock();
237   if (!ExitingBlock)
238     return false;
239   BranchInst *EBR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
240   if (!EBR) return false;
241   ExitCondition = dyn_cast<ICmpInst>(EBR->getCondition());
242   if (!ExitCondition) return false;
243   if (ExitingBlock != L->getLoopLatch()) return false;
244   IVExitValue = ExitCondition->getOperand(1);
245   if (!L->isLoopInvariant(IVExitValue))
246     IVExitValue = ExitCondition->getOperand(0);
247   if (!L->isLoopInvariant(IVExitValue))
248     return false;
249
250   // If start value is more then exit value where induction variable
251   // increments by 1 then we are potentially dealing with an infinite loop.
252   // Do not index split this loop.
253   if (ConstantInt *SV = dyn_cast<ConstantInt>(IVStartValue))
254     if (ConstantInt *EV = dyn_cast<ConstantInt>(IVExitValue))
255       if (SV->getSExtValue() > EV->getSExtValue())
256         return false;
257
258   if (processOneIterationLoop())
259     return true;
260
261   if (updateLoopIterationSpace())
262     return true;
263
264   if (splitLoop())
265     return true;
266
267   return false;
268 }
269
270 // --- Helper routines --- 
271 // isUsedOutsideLoop - Returns true iff V is used outside the loop L.
272 static bool isUsedOutsideLoop(Value *V, Loop *L) {
273   for(Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
274     if (!L->contains(cast<Instruction>(*UI)->getParent()))
275       return true;
276   return false;
277 }
278
279 // Return V+1
280 static Value *getPlusOne(Value *V, bool Sign, Instruction *InsertPt) {
281   ConstantInt *One = ConstantInt::get(V->getType(), 1, Sign);
282   return BinaryOperator::CreateAdd(V, One, "lsp", InsertPt);
283 }
284
285 // Return V-1
286 static Value *getMinusOne(Value *V, bool Sign, Instruction *InsertPt) {
287   ConstantInt *One = ConstantInt::get(V->getType(), 1, Sign);
288   return BinaryOperator::CreateSub(V, One, "lsp", InsertPt);
289 }
290
291 // Return min(V1, V1)
292 static Value *getMin(Value *V1, Value *V2, bool Sign, Instruction *InsertPt) {
293  
294   Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
295                           V1, V2, "lsp", InsertPt);
296   return SelectInst::Create(C, V1, V2, "lsp", InsertPt);
297 }
298
299 // Return max(V1, V2)
300 static Value *getMax(Value *V1, Value *V2, bool Sign, Instruction *InsertPt) {
301  
302   Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
303                           V1, V2, "lsp", InsertPt);
304   return SelectInst::Create(C, V2, V1, "lsp", InsertPt);
305 }
306
307 /// processOneIterationLoop -- Eliminate loop if loop body is executed 
308 /// only once. For example,
309 /// for (i = 0; i < N; ++i) {
310 ///   if ( i == X) {
311 ///     ...
312 ///   }
313 /// }
314 ///
315 bool LoopIndexSplit::processOneIterationLoop() {
316   SplitCondition = NULL;
317   BasicBlock *Latch = L->getLoopLatch();
318   BasicBlock *Header = L->getHeader();
319   BranchInst *BR = dyn_cast<BranchInst>(Header->getTerminator());
320   if (!BR) return false;
321   if (!isa<BranchInst>(Latch->getTerminator())) return false;
322   if (BR->isUnconditional()) return false;
323   SplitCondition = dyn_cast<ICmpInst>(BR->getCondition());
324   if (!SplitCondition) return false;
325   if (SplitCondition == ExitCondition) return false;
326   if (SplitCondition->getPredicate() != ICmpInst::ICMP_EQ) return false;
327   if (BR->getOperand(1) != Latch) return false;
328   if (!IVBasedValues.count(SplitCondition->getOperand(0))
329       && !IVBasedValues.count(SplitCondition->getOperand(1)))
330     return false;
331
332   // If IV is used outside the loop then this loop traversal is required.
333   // FIXME: Calculate and use last IV value. 
334   if (isUsedOutsideLoop(IVIncrement, L))
335     return false;
336
337   // If BR operands are not IV or not loop invariants then skip this loop.
338   Value *OPV = SplitCondition->getOperand(0);
339   Value *SplitValue = SplitCondition->getOperand(1);
340   if (!L->isLoopInvariant(SplitValue)) {
341     Value *T = SplitValue;
342     SplitValue = OPV;
343     OPV = T;
344   }
345   if (!L->isLoopInvariant(SplitValue))
346     return false;
347   Instruction *OPI = dyn_cast<Instruction>(OPV);
348   if (!OPI) return false;
349   if (OPI->getParent() != Header || isUsedOutsideLoop(OPI, L))
350     return false;
351   
352   if (!cleanBlock(Header))
353     return false;
354
355   if (!cleanBlock(Latch))
356     return false;
357     
358   // If the merge point for BR is not loop latch then skip this loop.
359   if (BR->getSuccessor(0) != Latch) {
360     DominanceFrontier::iterator DF0 = DF->find(BR->getSuccessor(0));
361     assert (DF0 != DF->end() && "Unable to find dominance frontier");
362     if (!DF0->second.count(Latch))
363       return false;
364   }
365   
366   if (BR->getSuccessor(1) != Latch) {
367     DominanceFrontier::iterator DF1 = DF->find(BR->getSuccessor(1));
368     assert (DF1 != DF->end() && "Unable to find dominance frontier");
369     if (!DF1->second.count(Latch))
370       return false;
371   }
372     
373   // Now, Current loop L contains compare instruction
374   // that compares induction variable, IndVar, against loop invariant. And
375   // entire (i.e. meaningful) loop body is dominated by this compare
376   // instruction. In such case eliminate 
377   // loop structure surrounding this loop body. For example,
378   //     for (int i = start; i < end; ++i) {
379   //         if ( i == somevalue) {
380   //           loop_body
381   //         }
382   //     }
383   // can be transformed into
384   //     if (somevalue >= start && somevalue < end) {
385   //        i = somevalue;
386   //        loop_body
387   //     }
388
389   // Replace index variable with split value in loop body. Loop body is executed
390   // only when index variable is equal to split value.
391   IndVar->replaceAllUsesWith(SplitValue);
392
393   // Replace split condition in header.
394   // Transform 
395   //      SplitCondition : icmp eq i32 IndVar, SplitValue
396   // into
397   //      c1 = icmp uge i32 SplitValue, StartValue
398   //      c2 = icmp ult i32 SplitValue, ExitValue
399   //      and i32 c1, c2 
400   Instruction *C1 = new ICmpInst(ExitCondition->isSignedPredicate() ? 
401                                  ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
402                                  SplitValue, IVStartValue, "lisplit", BR);
403
404   CmpInst::Predicate C2P  = ExitCondition->getPredicate();
405   BranchInst *LatchBR = cast<BranchInst>(Latch->getTerminator());
406   if (LatchBR->getOperand(0) != Header)
407     C2P = CmpInst::getInversePredicate(C2P);
408   Instruction *C2 = new ICmpInst(C2P, SplitValue, IVExitValue, "lisplit", BR);
409   Instruction *NSplitCond = BinaryOperator::CreateAnd(C1, C2, "lisplit", BR);
410
411   SplitCondition->replaceAllUsesWith(NSplitCond);
412   SplitCondition->eraseFromParent();
413
414   // Remove Latch to Header edge.
415   BasicBlock *LatchSucc = NULL;
416   Header->removePredecessor(Latch);
417   for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
418        SI != E; ++SI) {
419     if (Header != *SI)
420       LatchSucc = *SI;
421   }
422   LatchBR->setUnconditionalDest(LatchSucc);
423
424   // Remove IVIncrement
425   IVIncrement->replaceAllUsesWith(UndefValue::get(IVIncrement->getType()));
426   IVIncrement->eraseFromParent();
427   
428   LPM->deleteLoopFromQueue(L);
429
430   // Update Dominator Info.
431   // Only CFG change done is to remove Latch to Header edge. This
432   // does not change dominator tree because Latch did not dominate
433   // Header.
434   if (DF) {
435     DominanceFrontier::iterator HeaderDF = DF->find(Header);
436     if (HeaderDF != DF->end()) 
437       DF->removeFromFrontier(HeaderDF, Header);
438
439     DominanceFrontier::iterator LatchDF = DF->find(Latch);
440     if (LatchDF != DF->end()) 
441       DF->removeFromFrontier(LatchDF, Header);
442   }
443
444   ++NumIndexSplitRemoved;
445   return true;
446 }
447
448 /// restrictLoopBound - Op dominates loop body. Op compares an IV based value 
449 /// with a loop invariant value. Update loop's lower and upper bound based on 
450 /// the loop invariant value.
451 bool LoopIndexSplit::restrictLoopBound(ICmpInst &Op) {
452   bool Sign = Op.isSignedPredicate();
453   Instruction *PHTerm = L->getLoopPreheader()->getTerminator();
454
455   if (IVisGT(*ExitCondition) || IVisGE(*ExitCondition)) {
456     BranchInst *EBR = 
457       cast<BranchInst>(ExitCondition->getParent()->getTerminator());
458     ExitCondition->setPredicate(ExitCondition->getInversePredicate());
459     BasicBlock *T = EBR->getSuccessor(0);
460     EBR->setSuccessor(0, EBR->getSuccessor(1));
461     EBR->setSuccessor(1, T);
462   }
463
464   // New upper and lower bounds.
465   Value *NLB = NULL;
466   Value *NUB = NULL;
467   if (Value *V = IVisLT(Op)) {
468     // Restrict upper bound.
469     if (IVisLE(*ExitCondition)) 
470       V = getMinusOne(V, Sign, PHTerm);
471     NUB = getMin(V, IVExitValue, Sign, PHTerm);
472   } else if (Value *V = IVisLE(Op)) {
473     // Restrict upper bound.
474     if (IVisLT(*ExitCondition)) 
475       V = getPlusOne(V, Sign, PHTerm);
476     NUB = getMin(V, IVExitValue, Sign, PHTerm);
477   } else if (Value *V = IVisGT(Op)) {
478     // Restrict lower bound.
479     V = getPlusOne(V, Sign, PHTerm);
480     NLB = getMax(V, IVStartValue, Sign, PHTerm);
481   } else if (Value *V = IVisGE(Op))
482     // Restrict lower bound.
483     NLB = getMax(V, IVStartValue, Sign, PHTerm);
484
485   if (!NLB && !NUB) 
486     return false;
487
488   if (NLB) {
489     unsigned i = IndVar->getBasicBlockIndex(L->getLoopPreheader());
490     IndVar->setIncomingValue(i, NLB);
491   }
492
493   if (NUB) {
494     unsigned i = (ExitCondition->getOperand(0) != IVExitValue);
495     ExitCondition->setOperand(i, NUB);
496   }
497   return true;
498 }
499
500 /// updateLoopIterationSpace -- Update loop's iteration space if loop 
501 /// body is executed for certain IV range only. For example,
502 /// 
503 /// for (i = 0; i < N; ++i) {
504 ///   if ( i > A && i < B) {
505 ///     ...
506 ///   }
507 /// }
508 /// is transformed to iterators from A to B, if A > 0 and B < N.
509 ///
510 bool LoopIndexSplit::updateLoopIterationSpace() {
511   SplitCondition = NULL;
512   if (ExitCondition->getPredicate() == ICmpInst::ICMP_NE
513       || ExitCondition->getPredicate() == ICmpInst::ICMP_EQ)
514     return false;
515   BasicBlock *Latch = L->getLoopLatch();
516   BasicBlock *Header = L->getHeader();
517   BranchInst *BR = dyn_cast<BranchInst>(Header->getTerminator());
518   if (!BR) return false;
519   if (!isa<BranchInst>(Latch->getTerminator())) return false;
520   if (BR->isUnconditional()) return false;
521   BinaryOperator *AND = dyn_cast<BinaryOperator>(BR->getCondition());
522   if (!AND) return false;
523   if (AND->getOpcode() != Instruction::And) return false;
524   ICmpInst *Op0 = dyn_cast<ICmpInst>(AND->getOperand(0));
525   ICmpInst *Op1 = dyn_cast<ICmpInst>(AND->getOperand(1));
526   if (!Op0 || !Op1)
527     return false;
528   IVBasedValues.insert(AND);
529   IVBasedValues.insert(Op0);
530   IVBasedValues.insert(Op1);
531   if (!cleanBlock(Header)) return false;
532   BasicBlock *ExitingBlock = ExitCondition->getParent();
533   if (!cleanBlock(ExitingBlock)) return false;
534
535   // Verify that loop exiting block has only two predecessor, where one pred
536   // is split condition block. The other predecessor will become exiting block's
537   // dominator after CFG is updated. TODO : Handle CFG's where exiting block has
538   // more then two predecessors. This requires extra work in updating dominator
539   // information.
540   BasicBlock *ExitingBBPred = NULL;
541   for (pred_iterator PI = pred_begin(ExitingBlock), PE = pred_end(ExitingBlock);
542        PI != PE; ++PI) {
543     BasicBlock *BB = *PI;
544     if (Header == BB)
545       continue;
546     if (ExitingBBPred)
547       return false;
548     else
549       ExitingBBPred = BB;
550   }
551
552   if (!restrictLoopBound(*Op0))
553     return false;
554
555   if (!restrictLoopBound(*Op1))
556     return false;
557
558   // Update CFG.
559   if (BR->getSuccessor(0) == ExitingBlock)
560     BR->setUnconditionalDest(BR->getSuccessor(1));
561   else
562     BR->setUnconditionalDest(BR->getSuccessor(0));
563
564   AND->eraseFromParent();
565   if (Op0->use_empty())
566     Op0->eraseFromParent();
567   if (Op1->use_empty())
568     Op1->eraseFromParent();
569
570   // Update domiantor info. Now, ExitingBlock has only one predecessor, 
571   // ExitingBBPred, and it is ExitingBlock's immediate domiantor.
572   DT->changeImmediateDominator(ExitingBlock, ExitingBBPred);
573
574   BasicBlock *ExitBlock = ExitingBlock->getTerminator()->getSuccessor(1);
575   if (L->contains(ExitBlock))
576     ExitBlock = ExitingBlock->getTerminator()->getSuccessor(0);
577
578   // If ExitingBlock is a member of the loop basic blocks' DF list then
579   // replace ExitingBlock with header and exit block in the DF list
580   DominanceFrontier::iterator ExitingBlockDF = DF->find(ExitingBlock);
581   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
582        I != E; ++I) {
583     BasicBlock *BB = *I;
584     if (BB == Header || BB == ExitingBlock)
585       continue;
586     DominanceFrontier::iterator BBDF = DF->find(BB);
587     DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
588     DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
589     while (DomSetI != DomSetE) {
590       DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
591       ++DomSetI;
592       BasicBlock *DFBB = *CurrentItr;
593       if (DFBB == ExitingBlock) {
594         BBDF->second.erase(DFBB);
595         for (DominanceFrontier::DomSetType::iterator 
596                EBI = ExitingBlockDF->second.begin(),
597                EBE = ExitingBlockDF->second.end(); EBI != EBE; ++EBI) 
598           BBDF->second.insert(*EBI);
599       }
600     }
601   }
602   NumRestrictBounds++;
603   return true;
604 }
605
606 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
607 /// This routine is used to remove split condition's dead branch, dominated by
608 /// DeadBB. LiveBB dominates split conidition's other branch.
609 void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP, 
610                                   BasicBlock *LiveBB) {
611
612   // First update DeadBB's dominance frontier. 
613   SmallVector<BasicBlock *, 8> FrontierBBs;
614   DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
615   if (DeadBBDF != DF->end()) {
616     SmallVector<BasicBlock *, 8> PredBlocks;
617     
618     DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
619     for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
620            DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) 
621       {
622       BasicBlock *FrontierBB = *DeadBBSetI;
623       FrontierBBs.push_back(FrontierBB);
624
625       // Rremove any PHI incoming edge from blocks dominated by DeadBB.
626       PredBlocks.clear();
627       for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
628           PI != PE; ++PI) {
629         BasicBlock *P = *PI;
630         if (P == DeadBB || DT->dominates(DeadBB, P))
631           PredBlocks.push_back(P);
632       }
633
634       for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
635           FBI != FBE; ++FBI) {
636         if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
637           for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
638                 PE = PredBlocks.end(); PI != PE; ++PI) {
639             BasicBlock *P = *PI;
640             PN->removeIncomingValue(P);
641           }
642         }
643         else
644           break;
645       }      
646     }
647   }
648   
649   // Now remove DeadBB and all nodes dominated by DeadBB in df order.
650   SmallVector<BasicBlock *, 32> WorkList;
651   DomTreeNode *DN = DT->getNode(DeadBB);
652   for (df_iterator<DomTreeNode*> DI = df_begin(DN),
653          E = df_end(DN); DI != E; ++DI) {
654     BasicBlock *BB = DI->getBlock();
655     WorkList.push_back(BB);
656     BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
657   }
658
659   while (!WorkList.empty()) {
660     BasicBlock *BB = WorkList.back(); WorkList.pop_back();
661     for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end(); 
662         BBI != BBE; ) {
663       Instruction *I = BBI;
664       ++BBI;
665       I->replaceAllUsesWith(UndefValue::get(I->getType()));
666       I->eraseFromParent();
667     }
668     LPM->deleteSimpleAnalysisValue(BB, LP);
669     DT->eraseNode(BB);
670     DF->removeBlock(BB);
671     LI->removeBlock(BB);
672     BB->eraseFromParent();
673   }
674
675   // Update Frontier BBs' dominator info.
676   while (!FrontierBBs.empty()) {
677     BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
678     BasicBlock *NewDominator = FBB->getSinglePredecessor();
679     if (!NewDominator) {
680       pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
681       NewDominator = *PI;
682       ++PI;
683       if (NewDominator != LiveBB) {
684         for(; PI != PE; ++PI) {
685           BasicBlock *P = *PI;
686           if (P == LiveBB) {
687             NewDominator = LiveBB;
688             break;
689           }
690           NewDominator = DT->findNearestCommonDominator(NewDominator, P);
691         }
692       }
693     }
694     assert (NewDominator && "Unable to fix dominator info.");
695     DT->changeImmediateDominator(FBB, NewDominator);
696     DF->changeImmediateDominator(FBB, NewDominator, DT);
697   }
698
699 }
700
701 // moveExitCondition - Move exit condition EC into split condition block CondBB.
702 void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
703                                        BasicBlock *ExitBB, ICmpInst *EC, 
704                                        ICmpInst *SC, PHINode *IV, 
705                                        Instruction *IVAdd, Loop *LP,
706                                        unsigned ExitValueNum) {
707
708   BasicBlock *ExitingBB = EC->getParent();
709   Instruction *CurrentBR = CondBB->getTerminator();
710
711   // Move exit condition into split condition block.
712   EC->moveBefore(CurrentBR);
713   EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
714
715   // Move exiting block's branch into split condition block. Update its branch
716   // destination.
717   BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
718   ExitingBR->moveBefore(CurrentBR);
719   BasicBlock *OrigDestBB = NULL;
720   if (ExitingBR->getSuccessor(0) == ExitBB) {
721     OrigDestBB = ExitingBR->getSuccessor(1);
722     ExitingBR->setSuccessor(1, ActiveBB);
723   }
724   else {
725     OrigDestBB = ExitingBR->getSuccessor(0);
726     ExitingBR->setSuccessor(0, ActiveBB);
727   }
728     
729   // Remove split condition and current split condition branch.
730   SC->eraseFromParent();
731   CurrentBR->eraseFromParent();
732
733   // Connect exiting block to original destination.
734   BranchInst::Create(OrigDestBB, ExitingBB);
735
736   // Update PHINodes
737   updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd, LP);
738
739   // Fix dominator info.
740   // ExitBB is now dominated by CondBB
741   DT->changeImmediateDominator(ExitBB, CondBB);
742   DF->changeImmediateDominator(ExitBB, CondBB, DT);
743   
744   // Basicblocks dominated by ActiveBB may have ExitingBB or
745   // a basic block outside the loop in their DF list. If so,
746   // replace it with CondBB.
747   DomTreeNode *Node = DT->getNode(ActiveBB);
748   for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
749        DI != DE; ++DI) {
750     BasicBlock *BB = DI->getBlock();
751     DominanceFrontier::iterator BBDF = DF->find(BB);
752     DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
753     DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
754     while (DomSetI != DomSetE) {
755       DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
756       ++DomSetI;
757       BasicBlock *DFBB = *CurrentItr;
758       if (DFBB == ExitingBB || !L->contains(DFBB)) {
759         BBDF->second.erase(DFBB);
760         BBDF->second.insert(CondBB);
761       }
762     }
763   }
764 }
765
766 /// updatePHINodes - CFG has been changed. 
767 /// Before 
768 ///   - ExitBB's single predecessor was Latch
769 ///   - Latch's second successor was Header
770 /// Now
771 ///   - ExitBB's single predecessor is Header
772 ///   - Latch's one and only successor is Header
773 ///
774 /// Update ExitBB PHINodes' to reflect this change.
775 void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch, 
776                                     BasicBlock *Header,
777                                     PHINode *IV, Instruction *IVIncrement,
778                                     Loop *LP) {
779
780   for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end(); 
781        BI != BE; ) {
782     PHINode *PN = dyn_cast<PHINode>(BI);
783     ++BI;
784     if (!PN)
785       break;
786
787     Value *V = PN->getIncomingValueForBlock(Latch);
788     if (PHINode *PHV = dyn_cast<PHINode>(V)) {
789       // PHV is in Latch. PHV has one use is in ExitBB PHINode. And one use
790       // in Header which is new incoming value for PN.
791       Value *NewV = NULL;
792       for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end(); 
793            UI != E; ++UI) 
794         if (PHINode *U = dyn_cast<PHINode>(*UI)) 
795           if (LP->contains(U->getParent())) {
796             NewV = U;
797             break;
798           }
799
800       // Add incoming value from header only if PN has any use inside the loop.
801       if (NewV)
802         PN->addIncoming(NewV, Header);
803
804     } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
805       // If this instruction is IVIncrement then IV is new incoming value 
806       // from header otherwise this instruction must be incoming value from 
807       // header because loop is in LCSSA form.
808       if (PHI == IVIncrement)
809         PN->addIncoming(IV, Header);
810       else
811         PN->addIncoming(V, Header);
812     } else
813       // Otherwise this is an incoming value from header because loop is in 
814       // LCSSA form.
815       PN->addIncoming(V, Header);
816     
817     // Remove incoming value from Latch.
818     PN->removeIncomingValue(Latch);
819   }
820 }
821
822 bool LoopIndexSplit::splitLoop() {
823   SplitCondition = NULL;
824   if (ExitCondition->getPredicate() == ICmpInst::ICMP_NE
825       || ExitCondition->getPredicate() == ICmpInst::ICMP_EQ)
826     return false;
827   BasicBlock *Header = L->getHeader();
828   BasicBlock *Latch = L->getLoopLatch();
829   BranchInst *SBR = NULL; // Split Condition Branch
830   BranchInst *EBR = cast<BranchInst>(ExitCondition->getParent()->getTerminator());
831   // If Exiting block includes loop variant instructions then this
832   // loop may not be split safely.
833   BasicBlock *ExitingBlock = ExitCondition->getParent();
834   if (!cleanBlock(ExitingBlock)) return false;
835
836   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
837        I != E; ++I) {
838     BranchInst *BR = dyn_cast<BranchInst>((*I)->getTerminator());
839     if (!BR || BR->isUnconditional()) continue;
840     ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
841     if (!CI || CI == ExitCondition 
842         || CI->getPredicate() == ICmpInst::ICMP_NE
843         || CI->getPredicate() == ICmpInst::ICMP_EQ)
844       continue;
845
846     // Unable to handle triangle loops at the moment.
847     // In triangle loop, split condition is in header and one of the
848     // the split destination is loop latch. If split condition is EQ
849     // then such loops are already handle in processOneIterationLoop().
850     if (Header == (*I)
851         && (Latch == BR->getSuccessor(0) || Latch == BR->getSuccessor(1)))
852       continue;
853
854     // If the block does not dominate the latch then this is not a diamond.
855     // Such loop may not benefit from index split.
856     if (!DT->dominates((*I), Latch))
857       continue;
858
859     // If split condition branches heads do not have single predecessor, 
860     // SplitCondBlock, then is not possible to remove inactive branch.
861     if (!BR->getSuccessor(0)->getSinglePredecessor() 
862         || !BR->getSuccessor(1)->getSinglePredecessor())
863       return false;
864
865     // If the merge point for BR is not loop latch then skip this condition.
866     if (BR->getSuccessor(0) != Latch) {
867       DominanceFrontier::iterator DF0 = DF->find(BR->getSuccessor(0));
868       assert (DF0 != DF->end() && "Unable to find dominance frontier");
869       if (!DF0->second.count(Latch))
870         continue;
871     }
872     
873     if (BR->getSuccessor(1) != Latch) {
874       DominanceFrontier::iterator DF1 = DF->find(BR->getSuccessor(1));
875       assert (DF1 != DF->end() && "Unable to find dominance frontier");
876       if (!DF1->second.count(Latch))
877         continue;
878     }
879     SplitCondition = CI;
880     SBR = BR;
881     break;
882   }
883    
884   if (!SplitCondition)
885     return false;
886
887   // If the predicate sign does not match then skip.
888   if (ExitCondition->isSignedPredicate() != SplitCondition->isSignedPredicate())
889     return false;
890
891   unsigned EVOpNum = (ExitCondition->getOperand(1) == IVExitValue);
892   unsigned SVOpNum = IVBasedValues.count(SplitCondition->getOperand(0));
893   Value *SplitValue = SplitCondition->getOperand(SVOpNum);
894   if (!L->isLoopInvariant(SplitValue))
895     return false;
896   if (!IVBasedValues.count(SplitCondition->getOperand(!SVOpNum)))
897     return false;
898
899   // Normalize loop conditions so that it is easier to calculate new loop
900   // bounds.
901   if (IVisGT(*ExitCondition) || IVisGE(*ExitCondition)) {
902     ExitCondition->setPredicate(ExitCondition->getInversePredicate());
903     BasicBlock *T = EBR->getSuccessor(0);
904     EBR->setSuccessor(0, EBR->getSuccessor(1));
905     EBR->setSuccessor(1, T);
906   }
907
908   if (IVisGT(*SplitCondition) || IVisGE(*SplitCondition)) {
909     SplitCondition->setPredicate(SplitCondition->getInversePredicate());
910     BasicBlock *T = SBR->getSuccessor(0);
911     SBR->setSuccessor(0, SBR->getSuccessor(1));
912     SBR->setSuccessor(1, T);
913   }
914
915   //[*] Calculate new loop bounds.
916   Value *AEV = SplitValue;
917   Value *BSV = SplitValue;
918   bool Sign = SplitCondition->isSignedPredicate();
919   Instruction *PHTerm = L->getLoopPreheader()->getTerminator();
920
921   if (IVisLT(*ExitCondition)) {
922     if (IVisLT(*SplitCondition)) {
923       /* Do nothing */
924     }
925     else if (IVisLE(*SplitCondition)) {
926       AEV = getPlusOne(SplitValue, Sign, PHTerm);
927       BSV = getPlusOne(SplitValue, Sign, PHTerm);
928     } else {
929       assert (0 && "Unexpected split condition!");
930     }
931   }
932   else if (IVisLE(*ExitCondition)) {
933     if (IVisLT(*SplitCondition)) {
934       AEV = getMinusOne(SplitValue, Sign, PHTerm);
935     }
936     else if (IVisLE(*SplitCondition)) {
937       BSV = getPlusOne(SplitValue, Sign, PHTerm);
938     } else {
939       assert (0 && "Unexpected split condition!");
940     }
941   } else {
942     assert (0 && "Unexpected exit condition!");
943   }
944   AEV = getMin(AEV, IVExitValue, Sign, PHTerm);
945   BSV = getMax(BSV, IVStartValue, Sign, PHTerm);
946
947   // [*] Clone Loop
948   DenseMap<const Value *, Value *> ValueMap;
949   Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
950   Loop *ALoop = L;
951
952   // [*] ALoop's exiting edge enters BLoop's header.
953   //    ALoop's original exit block becomes BLoop's exit block.
954   PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
955   BasicBlock *A_ExitingBlock = ExitCondition->getParent();
956   BranchInst *A_ExitInsn =
957     dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
958   assert (A_ExitInsn && "Unable to find suitable loop exit branch");
959   BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
960   BasicBlock *B_Header = BLoop->getHeader();
961   if (ALoop->contains(B_ExitBlock)) {
962     B_ExitBlock = A_ExitInsn->getSuccessor(0);
963     A_ExitInsn->setSuccessor(0, B_Header);
964   } else
965     A_ExitInsn->setSuccessor(1, B_Header);
966
967   // [*] Update ALoop's exit value using new exit value.
968   ExitCondition->setOperand(EVOpNum, AEV);
969
970   // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
971   //     original loop's preheader. Add incoming PHINode values from
972   //     ALoop's exiting block. Update BLoop header's domiantor info.
973
974   // Collect inverse map of Header PHINodes.
975   DenseMap<Value *, Value *> InverseMap;
976   for (BasicBlock::iterator BI = ALoop->getHeader()->begin(), 
977          BE = ALoop->getHeader()->end(); BI != BE; ++BI) {
978     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
979       PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
980       InverseMap[PNClone] = PN;
981     } else
982       break;
983   }
984
985   BasicBlock *A_Preheader = ALoop->getLoopPreheader();
986   for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
987        BI != BE; ++BI) {
988     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
989       // Remove incoming value from original preheader.
990       PN->removeIncomingValue(A_Preheader);
991
992       // Add incoming value from A_ExitingBlock.
993       if (PN == B_IndVar)
994         PN->addIncoming(BSV, A_ExitingBlock);
995       else { 
996         PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
997         Value *V2 = NULL;
998         // If loop header is also loop exiting block then
999         // OrigPN is incoming value for B loop header.
1000         if (A_ExitingBlock == ALoop->getHeader())
1001           V2 = OrigPN;
1002         else
1003           V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1004         PN->addIncoming(V2, A_ExitingBlock);
1005       }
1006     } else
1007       break;
1008   }
1009
1010   DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1011   DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
1012   
1013   // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1014   //     block. Remove incoming PHINode values from ALoop's exiting block.
1015   //     Add new incoming values from BLoop's incoming exiting value.
1016   //     Update BLoop exit block's dominator info..
1017   BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1018   for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
1019        BI != BE; ++BI) {
1020     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1021       PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)], 
1022                                                             B_ExitingBlock);
1023       PN->removeIncomingValue(A_ExitingBlock);
1024     } else
1025       break;
1026   }
1027
1028   DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1029   DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
1030
1031  //[*] Split ALoop's exit edge. This creates a new block which
1032   //    serves two purposes. First one is to hold PHINode defnitions
1033   //    to ensure that ALoop's LCSSA form. Second use it to act
1034   //    as a preheader for BLoop.
1035   BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
1036
1037   //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1038   //    in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1039   for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1040       BI != BE; ++BI) {
1041     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1042       Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
1043       PHINode *newPHI = PHINode::Create(PN->getType(), PN->getName());
1044       newPHI->addIncoming(V1, A_ExitingBlock);
1045       A_ExitBlock->getInstList().push_front(newPHI);
1046       PN->removeIncomingValue(A_ExitBlock);
1047       PN->addIncoming(newPHI, A_ExitBlock);
1048     } else
1049       break;
1050   }
1051
1052   //[*] Eliminate split condition's inactive branch from ALoop.
1053   BasicBlock *A_SplitCondBlock = SplitCondition->getParent();
1054   BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
1055   BasicBlock *A_InactiveBranch = NULL;
1056   BasicBlock *A_ActiveBranch = NULL;
1057   A_ActiveBranch = A_BR->getSuccessor(0);
1058   A_InactiveBranch = A_BR->getSuccessor(1);
1059   A_BR->setUnconditionalDest(A_ActiveBranch);
1060   removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1061
1062   //[*] Eliminate split condition's inactive branch in from BLoop.
1063   BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1064   BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
1065   BasicBlock *B_InactiveBranch = NULL;
1066   BasicBlock *B_ActiveBranch = NULL;
1067   B_ActiveBranch = B_BR->getSuccessor(1);
1068   B_InactiveBranch = B_BR->getSuccessor(0);
1069   B_BR->setUnconditionalDest(B_ActiveBranch);
1070   removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1071
1072   BasicBlock *A_Header = ALoop->getHeader();
1073   if (A_ExitingBlock == A_Header)
1074     return true;
1075
1076   //[*] Move exit condition into split condition block to avoid
1077   //    executing dead loop iteration.
1078   ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1079   Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IVIncrement]);
1080   ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SplitCondition]);
1081
1082   moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
1083                     cast<ICmpInst>(SplitCondition), IndVar, IVIncrement, 
1084                     ALoop, EVOpNum);
1085
1086   moveExitCondition(B_SplitCondBlock, B_ActiveBranch, 
1087                     B_ExitBlock, B_ExitCondition,
1088                     B_SplitCondition, B_IndVar, B_IndVarIncrement, 
1089                     BLoop, EVOpNum);
1090
1091   NumIndexSplit++;
1092   return true;
1093 }
1094
1095 /// cleanBlock - A block is considered clean if all non terminal instructions 
1096 /// are either, PHINodes, IV based.
1097 bool LoopIndexSplit::cleanBlock(BasicBlock *BB) {
1098   Instruction *Terminator = BB->getTerminator();
1099   for(BasicBlock::iterator BI = BB->begin(), BE = BB->end(); 
1100       BI != BE; ++BI) {
1101     Instruction *I = BI;
1102
1103     if (isa<PHINode>(I) || I == Terminator || I == ExitCondition
1104         || I == SplitCondition || IVBasedValues.count(I) 
1105         || isa<DbgInfoIntrinsic>(I))
1106       continue;
1107
1108     if (I->mayWriteToMemory())
1109       return false;
1110
1111     // I is used only inside this block then it is OK.
1112     bool usedOutsideBB = false;
1113     for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); 
1114          UI != UE; ++UI) {
1115       Instruction *U = cast<Instruction>(UI);
1116       if (U->getParent() != BB)
1117         usedOutsideBB = true;
1118     }
1119     if (!usedOutsideBB)
1120       continue;
1121
1122     // Otherwise we have a instruction that may not allow loop spliting.
1123     return false;
1124   }
1125   return true;
1126 }
1127
1128 /// IVisLT - If Op is comparing IV based value with an loop invariant and 
1129 /// IV based value is less than  the loop invariant then return the loop 
1130 /// invariant. Otherwise return NULL.
1131 Value * LoopIndexSplit::IVisLT(ICmpInst &Op) {
1132   ICmpInst::Predicate P = Op.getPredicate();
1133   if ((P == ICmpInst::ICMP_SLT || P == ICmpInst::ICMP_ULT) 
1134       && IVBasedValues.count(Op.getOperand(0)) 
1135       && L->isLoopInvariant(Op.getOperand(1)))
1136     return Op.getOperand(1);
1137
1138   if ((P == ICmpInst::ICMP_SGT || P == ICmpInst::ICMP_UGT) 
1139       && IVBasedValues.count(Op.getOperand(1)) 
1140       && L->isLoopInvariant(Op.getOperand(0)))
1141     return Op.getOperand(0);
1142
1143   return NULL;
1144 }
1145
1146 /// IVisLE - If Op is comparing IV based value with an loop invariant and 
1147 /// IV based value is less than or equal to the loop invariant then 
1148 /// return the loop invariant. Otherwise return NULL.
1149 Value * LoopIndexSplit::IVisLE(ICmpInst &Op) {
1150   ICmpInst::Predicate P = Op.getPredicate();
1151   if ((P == ICmpInst::ICMP_SLE || P == ICmpInst::ICMP_ULE)
1152       && IVBasedValues.count(Op.getOperand(0)) 
1153       && L->isLoopInvariant(Op.getOperand(1)))
1154     return Op.getOperand(1);
1155
1156   if ((P == ICmpInst::ICMP_SGE || P == ICmpInst::ICMP_UGE) 
1157       && IVBasedValues.count(Op.getOperand(1)) 
1158       && L->isLoopInvariant(Op.getOperand(0)))
1159     return Op.getOperand(0);
1160
1161   return NULL;
1162 }
1163
1164 /// IVisGT - If Op is comparing IV based value with an loop invariant and 
1165 /// IV based value is greater than  the loop invariant then return the loop 
1166 /// invariant. Otherwise return NULL.
1167 Value * LoopIndexSplit::IVisGT(ICmpInst &Op) {
1168   ICmpInst::Predicate P = Op.getPredicate();
1169   if ((P == ICmpInst::ICMP_SGT || P == ICmpInst::ICMP_UGT) 
1170       && IVBasedValues.count(Op.getOperand(0)) 
1171       && L->isLoopInvariant(Op.getOperand(1)))
1172     return Op.getOperand(1);
1173
1174   if ((P == ICmpInst::ICMP_SLT || P == ICmpInst::ICMP_ULT) 
1175       && IVBasedValues.count(Op.getOperand(1)) 
1176       && L->isLoopInvariant(Op.getOperand(0)))
1177     return Op.getOperand(0);
1178
1179   return NULL;
1180 }
1181
1182 /// IVisGE - If Op is comparing IV based value with an loop invariant and 
1183 /// IV based value is greater than or equal to the loop invariant then 
1184 /// return the loop invariant. Otherwise return NULL.
1185 Value * LoopIndexSplit::IVisGE(ICmpInst &Op) {
1186   ICmpInst::Predicate P = Op.getPredicate();
1187   if ((P == ICmpInst::ICMP_SGE || P == ICmpInst::ICMP_UGE)
1188       && IVBasedValues.count(Op.getOperand(0)) 
1189       && L->isLoopInvariant(Op.getOperand(1)))
1190     return Op.getOperand(1);
1191
1192   if ((P == ICmpInst::ICMP_SLE || P == ICmpInst::ICMP_ULE) 
1193       && IVBasedValues.count(Op.getOperand(1)) 
1194       && L->isLoopInvariant(Op.getOperand(0)))
1195     return Op.getOperand(0);
1196
1197   return NULL;
1198 }
1199