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