Before deleting a basic block, give other loop passes a chance cleanup analysis value...
[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   // If the merge point for BR is not loop latch then skip this loop.
536   if (BR->getSuccessor(0) != Latch) {
537     DominanceFrontier::iterator DF0 = DF->find(BR->getSuccessor(0));
538     assert (DF0 != DF->end() && "Unable to find dominance frontier");
539     if (!DF0->second.count(Latch))
540       return false;
541   }
542   
543   if (BR->getSuccessor(1) != Latch) {
544     DominanceFrontier::iterator DF1 = DF->find(BR->getSuccessor(1));
545     assert (DF1 != DF->end() && "Unable to find dominance frontier");
546     if (!DF1->second.count(Latch))
547       return false;
548   }
549     
550   // Verify that loop exiting block has only two predecessor, where one pred
551   // is split condition block. The other predecessor will become exiting block's
552   // dominator after CFG is updated. TODO : Handle CFG's where exiting block has
553   // more then two predecessors. This requires extra work in updating dominator
554   // information.
555   BasicBlock *ExitingBBPred = NULL;
556   for (pred_iterator PI = pred_begin(ExitingBlock), PE = pred_end(ExitingBlock);
557        PI != PE; ++PI) {
558     BasicBlock *BB = *PI;
559     if (Header == BB)
560       continue;
561     if (ExitingBBPred)
562       return false;
563     else
564       ExitingBBPred = BB;
565   }
566
567   if (!restrictLoopBound(*Op0))
568     return false;
569
570   if (!restrictLoopBound(*Op1))
571     return false;
572
573   // Update CFG.
574   if (BR->getSuccessor(0) == ExitingBlock)
575     BR->setUnconditionalDest(BR->getSuccessor(1));
576   else
577     BR->setUnconditionalDest(BR->getSuccessor(0));
578
579   AND->eraseFromParent();
580   if (Op0->use_empty())
581     Op0->eraseFromParent();
582   if (Op1->use_empty())
583     Op1->eraseFromParent();
584
585   // Update domiantor info. Now, ExitingBlock has only one predecessor, 
586   // ExitingBBPred, and it is ExitingBlock's immediate domiantor.
587   DT->changeImmediateDominator(ExitingBlock, ExitingBBPred);
588
589   BasicBlock *ExitBlock = ExitingBlock->getTerminator()->getSuccessor(1);
590   if (L->contains(ExitBlock))
591     ExitBlock = ExitingBlock->getTerminator()->getSuccessor(0);
592
593   // If ExitingBlock is a member of the loop basic blocks' DF list then
594   // replace ExitingBlock with header and exit block in the DF list
595   DominanceFrontier::iterator ExitingBlockDF = DF->find(ExitingBlock);
596   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
597        I != E; ++I) {
598     BasicBlock *BB = *I;
599     if (BB == Header || BB == ExitingBlock)
600       continue;
601     DominanceFrontier::iterator BBDF = DF->find(BB);
602     DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
603     DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
604     while (DomSetI != DomSetE) {
605       DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
606       ++DomSetI;
607       BasicBlock *DFBB = *CurrentItr;
608       if (DFBB == ExitingBlock) {
609         BBDF->second.erase(DFBB);
610         for (DominanceFrontier::DomSetType::iterator 
611                EBI = ExitingBlockDF->second.begin(),
612                EBE = ExitingBlockDF->second.end(); EBI != EBE; ++EBI) 
613           BBDF->second.insert(*EBI);
614       }
615     }
616   }
617   NumRestrictBounds++;
618   return true;
619 }
620
621 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
622 /// This routine is used to remove split condition's dead branch, dominated by
623 /// DeadBB. LiveBB dominates split conidition's other branch.
624 void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP, 
625                                   BasicBlock *LiveBB) {
626
627   // First update DeadBB's dominance frontier. 
628   SmallVector<BasicBlock *, 8> FrontierBBs;
629   DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
630   if (DeadBBDF != DF->end()) {
631     SmallVector<BasicBlock *, 8> PredBlocks;
632     
633     DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
634     for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
635            DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) 
636       {
637       BasicBlock *FrontierBB = *DeadBBSetI;
638       FrontierBBs.push_back(FrontierBB);
639
640       // Rremove any PHI incoming edge from blocks dominated by DeadBB.
641       PredBlocks.clear();
642       for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
643           PI != PE; ++PI) {
644         BasicBlock *P = *PI;
645         if (P == DeadBB || DT->dominates(DeadBB, P))
646           PredBlocks.push_back(P);
647       }
648
649       for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
650           FBI != FBE; ++FBI) {
651         if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
652           for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
653                 PE = PredBlocks.end(); PI != PE; ++PI) {
654             BasicBlock *P = *PI;
655             PN->removeIncomingValue(P);
656           }
657         }
658         else
659           break;
660       }      
661     }
662   }
663   
664   // Now remove DeadBB and all nodes dominated by DeadBB in df order.
665   SmallVector<BasicBlock *, 32> WorkList;
666   DomTreeNode *DN = DT->getNode(DeadBB);
667   for (df_iterator<DomTreeNode*> DI = df_begin(DN),
668          E = df_end(DN); DI != E; ++DI) {
669     BasicBlock *BB = DI->getBlock();
670     WorkList.push_back(BB);
671     BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
672   }
673
674   while (!WorkList.empty()) {
675     BasicBlock *BB = WorkList.back(); WorkList.pop_back();
676     LPM->deleteSimpleAnalysisValue(BB, LP);
677     for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end(); 
678         BBI != BBE; ) {
679       Instruction *I = BBI;
680       ++BBI;
681       I->replaceAllUsesWith(UndefValue::get(I->getType()));
682       I->eraseFromParent();
683     }
684     DT->eraseNode(BB);
685     DF->removeBlock(BB);
686     LI->removeBlock(BB);
687     BB->eraseFromParent();
688   }
689
690   // Update Frontier BBs' dominator info.
691   while (!FrontierBBs.empty()) {
692     BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
693     BasicBlock *NewDominator = FBB->getSinglePredecessor();
694     if (!NewDominator) {
695       pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
696       NewDominator = *PI;
697       ++PI;
698       if (NewDominator != LiveBB) {
699         for(; PI != PE; ++PI) {
700           BasicBlock *P = *PI;
701           if (P == LiveBB) {
702             NewDominator = LiveBB;
703             break;
704           }
705           NewDominator = DT->findNearestCommonDominator(NewDominator, P);
706         }
707       }
708     }
709     assert (NewDominator && "Unable to fix dominator info.");
710     DT->changeImmediateDominator(FBB, NewDominator);
711     DF->changeImmediateDominator(FBB, NewDominator, DT);
712   }
713
714 }
715
716 // moveExitCondition - Move exit condition EC into split condition block CondBB.
717 void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
718                                        BasicBlock *ExitBB, ICmpInst *EC, 
719                                        ICmpInst *SC, PHINode *IV, 
720                                        Instruction *IVAdd, Loop *LP,
721                                        unsigned ExitValueNum) {
722
723   BasicBlock *ExitingBB = EC->getParent();
724   Instruction *CurrentBR = CondBB->getTerminator();
725
726   // Move exit condition into split condition block.
727   EC->moveBefore(CurrentBR);
728   EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
729
730   // Move exiting block's branch into split condition block. Update its branch
731   // destination.
732   BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
733   ExitingBR->moveBefore(CurrentBR);
734   BasicBlock *OrigDestBB = NULL;
735   if (ExitingBR->getSuccessor(0) == ExitBB) {
736     OrigDestBB = ExitingBR->getSuccessor(1);
737     ExitingBR->setSuccessor(1, ActiveBB);
738   }
739   else {
740     OrigDestBB = ExitingBR->getSuccessor(0);
741     ExitingBR->setSuccessor(0, ActiveBB);
742   }
743     
744   // Remove split condition and current split condition branch.
745   SC->eraseFromParent();
746   CurrentBR->eraseFromParent();
747
748   // Connect exiting block to original destination.
749   BranchInst::Create(OrigDestBB, ExitingBB);
750
751   // Update PHINodes
752   updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd, LP);
753
754   // Fix dominator info.
755   // ExitBB is now dominated by CondBB
756   DT->changeImmediateDominator(ExitBB, CondBB);
757   DF->changeImmediateDominator(ExitBB, CondBB, DT);
758   
759   // Basicblocks dominated by ActiveBB may have ExitingBB or
760   // a basic block outside the loop in their DF list. If so,
761   // replace it with CondBB.
762   DomTreeNode *Node = DT->getNode(ActiveBB);
763   for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
764        DI != DE; ++DI) {
765     BasicBlock *BB = DI->getBlock();
766     DominanceFrontier::iterator BBDF = DF->find(BB);
767     DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
768     DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
769     while (DomSetI != DomSetE) {
770       DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
771       ++DomSetI;
772       BasicBlock *DFBB = *CurrentItr;
773       if (DFBB == ExitingBB || !L->contains(DFBB)) {
774         BBDF->second.erase(DFBB);
775         BBDF->second.insert(CondBB);
776       }
777     }
778   }
779 }
780
781 /// updatePHINodes - CFG has been changed. 
782 /// Before 
783 ///   - ExitBB's single predecessor was Latch
784 ///   - Latch's second successor was Header
785 /// Now
786 ///   - ExitBB's single predecessor is Header
787 ///   - Latch's one and only successor is Header
788 ///
789 /// Update ExitBB PHINodes' to reflect this change.
790 void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch, 
791                                     BasicBlock *Header,
792                                     PHINode *IV, Instruction *IVIncrement,
793                                     Loop *LP) {
794
795   for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end(); 
796        BI != BE; ) {
797     PHINode *PN = dyn_cast<PHINode>(BI);
798     ++BI;
799     if (!PN)
800       break;
801
802     Value *V = PN->getIncomingValueForBlock(Latch);
803     if (PHINode *PHV = dyn_cast<PHINode>(V)) {
804       // PHV is in Latch. PHV has one use is in ExitBB PHINode. And one use
805       // in Header which is new incoming value for PN.
806       Value *NewV = NULL;
807       for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end(); 
808            UI != E; ++UI) 
809         if (PHINode *U = dyn_cast<PHINode>(*UI)) 
810           if (LP->contains(U->getParent())) {
811             NewV = U;
812             break;
813           }
814
815       // Add incoming value from header only if PN has any use inside the loop.
816       if (NewV)
817         PN->addIncoming(NewV, Header);
818
819     } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
820       // If this instruction is IVIncrement then IV is new incoming value 
821       // from header otherwise this instruction must be incoming value from 
822       // header because loop is in LCSSA form.
823       if (PHI == IVIncrement)
824         PN->addIncoming(IV, Header);
825       else
826         PN->addIncoming(V, Header);
827     } else
828       // Otherwise this is an incoming value from header because loop is in 
829       // LCSSA form.
830       PN->addIncoming(V, Header);
831     
832     // Remove incoming value from Latch.
833     PN->removeIncomingValue(Latch);
834   }
835 }
836
837 bool LoopIndexSplit::splitLoop() {
838   SplitCondition = NULL;
839   if (ExitCondition->getPredicate() == ICmpInst::ICMP_NE
840       || ExitCondition->getPredicate() == ICmpInst::ICMP_EQ)
841     return false;
842   BasicBlock *Header = L->getHeader();
843   BasicBlock *Latch = L->getLoopLatch();
844   BranchInst *SBR = NULL; // Split Condition Branch
845   BranchInst *EBR = cast<BranchInst>(ExitCondition->getParent()->getTerminator());
846   // If Exiting block includes loop variant instructions then this
847   // loop may not be split safely.
848   BasicBlock *ExitingBlock = ExitCondition->getParent();
849   if (!cleanBlock(ExitingBlock)) return false;
850
851   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
852        I != E; ++I) {
853     BranchInst *BR = dyn_cast<BranchInst>((*I)->getTerminator());
854     if (!BR || BR->isUnconditional()) continue;
855     ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
856     if (!CI || CI == ExitCondition 
857         || CI->getPredicate() == ICmpInst::ICMP_NE
858         || CI->getPredicate() == ICmpInst::ICMP_EQ)
859       continue;
860
861     // Unable to handle triangle loops at the moment.
862     // In triangle loop, split condition is in header and one of the
863     // the split destination is loop latch. If split condition is EQ
864     // then such loops are already handle in processOneIterationLoop().
865     if (Header == (*I)
866         && (Latch == BR->getSuccessor(0) || Latch == BR->getSuccessor(1)))
867       continue;
868
869     // If the block does not dominate the latch then this is not a diamond.
870     // Such loop may not benefit from index split.
871     if (!DT->dominates((*I), Latch))
872       continue;
873
874     // If split condition branches heads do not have single predecessor, 
875     // SplitCondBlock, then is not possible to remove inactive branch.
876     if (!BR->getSuccessor(0)->getSinglePredecessor() 
877         || !BR->getSuccessor(1)->getSinglePredecessor())
878       return false;
879
880     // If the merge point for BR is not loop latch then skip this condition.
881     if (BR->getSuccessor(0) != Latch) {
882       DominanceFrontier::iterator DF0 = DF->find(BR->getSuccessor(0));
883       assert (DF0 != DF->end() && "Unable to find dominance frontier");
884       if (!DF0->second.count(Latch))
885         continue;
886     }
887     
888     if (BR->getSuccessor(1) != Latch) {
889       DominanceFrontier::iterator DF1 = DF->find(BR->getSuccessor(1));
890       assert (DF1 != DF->end() && "Unable to find dominance frontier");
891       if (!DF1->second.count(Latch))
892         continue;
893     }
894     SplitCondition = CI;
895     SBR = BR;
896     break;
897   }
898    
899   if (!SplitCondition)
900     return false;
901
902   // If the predicate sign does not match then skip.
903   if (ExitCondition->isSignedPredicate() != SplitCondition->isSignedPredicate())
904     return false;
905
906   unsigned EVOpNum = (ExitCondition->getOperand(1) == IVExitValue);
907   unsigned SVOpNum = IVBasedValues.count(SplitCondition->getOperand(0));
908   Value *SplitValue = SplitCondition->getOperand(SVOpNum);
909   if (!L->isLoopInvariant(SplitValue))
910     return false;
911   if (!IVBasedValues.count(SplitCondition->getOperand(!SVOpNum)))
912     return false;
913
914   // Normalize loop conditions so that it is easier to calculate new loop
915   // bounds.
916   if (IVisGT(*ExitCondition) || IVisGE(*ExitCondition)) {
917     ExitCondition->setPredicate(ExitCondition->getInversePredicate());
918     BasicBlock *T = EBR->getSuccessor(0);
919     EBR->setSuccessor(0, EBR->getSuccessor(1));
920     EBR->setSuccessor(1, T);
921   }
922
923   if (IVisGT(*SplitCondition) || IVisGE(*SplitCondition)) {
924     SplitCondition->setPredicate(SplitCondition->getInversePredicate());
925     BasicBlock *T = SBR->getSuccessor(0);
926     SBR->setSuccessor(0, SBR->getSuccessor(1));
927     SBR->setSuccessor(1, T);
928   }
929
930   //[*] Calculate new loop bounds.
931   Value *AEV = SplitValue;
932   Value *BSV = SplitValue;
933   bool Sign = SplitCondition->isSignedPredicate();
934   Instruction *PHTerm = L->getLoopPreheader()->getTerminator();
935
936   if (IVisLT(*ExitCondition)) {
937     if (IVisLT(*SplitCondition)) {
938       /* Do nothing */
939     }
940     else if (IVisLE(*SplitCondition)) {
941       AEV = getPlusOne(SplitValue, Sign, PHTerm);
942       BSV = getPlusOne(SplitValue, Sign, PHTerm);
943     } else {
944       assert (0 && "Unexpected split condition!");
945     }
946   }
947   else if (IVisLE(*ExitCondition)) {
948     if (IVisLT(*SplitCondition)) {
949       AEV = getMinusOne(SplitValue, Sign, PHTerm);
950     }
951     else if (IVisLE(*SplitCondition)) {
952       BSV = getPlusOne(SplitValue, Sign, PHTerm);
953     } else {
954       assert (0 && "Unexpected split condition!");
955     }
956   } else {
957     assert (0 && "Unexpected exit condition!");
958   }
959   AEV = getMin(AEV, IVExitValue, Sign, PHTerm);
960   BSV = getMax(BSV, IVStartValue, Sign, PHTerm);
961
962   // [*] Clone Loop
963   DenseMap<const Value *, Value *> ValueMap;
964   Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
965   Loop *ALoop = L;
966
967   // [*] ALoop's exiting edge enters BLoop's header.
968   //    ALoop's original exit block becomes BLoop's exit block.
969   PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
970   BasicBlock *A_ExitingBlock = ExitCondition->getParent();
971   BranchInst *A_ExitInsn =
972     dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
973   assert (A_ExitInsn && "Unable to find suitable loop exit branch");
974   BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
975   BasicBlock *B_Header = BLoop->getHeader();
976   if (ALoop->contains(B_ExitBlock)) {
977     B_ExitBlock = A_ExitInsn->getSuccessor(0);
978     A_ExitInsn->setSuccessor(0, B_Header);
979   } else
980     A_ExitInsn->setSuccessor(1, B_Header);
981
982   // [*] Update ALoop's exit value using new exit value.
983   ExitCondition->setOperand(EVOpNum, AEV);
984
985   // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
986   //     original loop's preheader. Add incoming PHINode values from
987   //     ALoop's exiting block. Update BLoop header's domiantor info.
988
989   // Collect inverse map of Header PHINodes.
990   DenseMap<Value *, Value *> InverseMap;
991   for (BasicBlock::iterator BI = ALoop->getHeader()->begin(), 
992          BE = ALoop->getHeader()->end(); BI != BE; ++BI) {
993     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
994       PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
995       InverseMap[PNClone] = PN;
996     } else
997       break;
998   }
999
1000   BasicBlock *A_Preheader = ALoop->getLoopPreheader();
1001   for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1002        BI != BE; ++BI) {
1003     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1004       // Remove incoming value from original preheader.
1005       PN->removeIncomingValue(A_Preheader);
1006
1007       // Add incoming value from A_ExitingBlock.
1008       if (PN == B_IndVar)
1009         PN->addIncoming(BSV, A_ExitingBlock);
1010       else { 
1011         PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
1012         Value *V2 = NULL;
1013         // If loop header is also loop exiting block then
1014         // OrigPN is incoming value for B loop header.
1015         if (A_ExitingBlock == ALoop->getHeader())
1016           V2 = OrigPN;
1017         else
1018           V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1019         PN->addIncoming(V2, A_ExitingBlock);
1020       }
1021     } else
1022       break;
1023   }
1024
1025   DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1026   DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
1027   
1028   // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1029   //     block. Remove incoming PHINode values from ALoop's exiting block.
1030   //     Add new incoming values from BLoop's incoming exiting value.
1031   //     Update BLoop exit block's dominator info..
1032   BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1033   for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
1034        BI != BE; ++BI) {
1035     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1036       PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)], 
1037                                                             B_ExitingBlock);
1038       PN->removeIncomingValue(A_ExitingBlock);
1039     } else
1040       break;
1041   }
1042
1043   DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1044   DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
1045
1046  //[*] Split ALoop's exit edge. This creates a new block which
1047   //    serves two purposes. First one is to hold PHINode defnitions
1048   //    to ensure that ALoop's LCSSA form. Second use it to act
1049   //    as a preheader for BLoop.
1050   BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
1051
1052   //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1053   //    in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1054   for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1055       BI != BE; ++BI) {
1056     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1057       Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
1058       PHINode *newPHI = PHINode::Create(PN->getType(), PN->getName());
1059       newPHI->addIncoming(V1, A_ExitingBlock);
1060       A_ExitBlock->getInstList().push_front(newPHI);
1061       PN->removeIncomingValue(A_ExitBlock);
1062       PN->addIncoming(newPHI, A_ExitBlock);
1063     } else
1064       break;
1065   }
1066
1067   //[*] Eliminate split condition's inactive branch from ALoop.
1068   BasicBlock *A_SplitCondBlock = SplitCondition->getParent();
1069   BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
1070   BasicBlock *A_InactiveBranch = NULL;
1071   BasicBlock *A_ActiveBranch = NULL;
1072   A_ActiveBranch = A_BR->getSuccessor(0);
1073   A_InactiveBranch = A_BR->getSuccessor(1);
1074   A_BR->setUnconditionalDest(A_ActiveBranch);
1075   removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1076
1077   //[*] Eliminate split condition's inactive branch in from BLoop.
1078   BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1079   BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
1080   BasicBlock *B_InactiveBranch = NULL;
1081   BasicBlock *B_ActiveBranch = NULL;
1082   B_ActiveBranch = B_BR->getSuccessor(1);
1083   B_InactiveBranch = B_BR->getSuccessor(0);
1084   B_BR->setUnconditionalDest(B_ActiveBranch);
1085   removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1086
1087   BasicBlock *A_Header = ALoop->getHeader();
1088   if (A_ExitingBlock == A_Header)
1089     return true;
1090
1091   //[*] Move exit condition into split condition block to avoid
1092   //    executing dead loop iteration.
1093   ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1094   Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IVIncrement]);
1095   ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SplitCondition]);
1096
1097   moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
1098                     cast<ICmpInst>(SplitCondition), IndVar, IVIncrement, 
1099                     ALoop, EVOpNum);
1100
1101   moveExitCondition(B_SplitCondBlock, B_ActiveBranch, 
1102                     B_ExitBlock, B_ExitCondition,
1103                     B_SplitCondition, B_IndVar, B_IndVarIncrement, 
1104                     BLoop, EVOpNum);
1105
1106   NumIndexSplit++;
1107   return true;
1108 }
1109
1110 /// cleanBlock - A block is considered clean if all non terminal instructions 
1111 /// are either, PHINodes, IV based.
1112 bool LoopIndexSplit::cleanBlock(BasicBlock *BB) {
1113   Instruction *Terminator = BB->getTerminator();
1114   for(BasicBlock::iterator BI = BB->begin(), BE = BB->end(); 
1115       BI != BE; ++BI) {
1116     Instruction *I = BI;
1117
1118     if (isa<PHINode>(I) || I == Terminator || I == ExitCondition
1119         || I == SplitCondition || IVBasedValues.count(I) 
1120         || isa<DbgInfoIntrinsic>(I))
1121       continue;
1122
1123     if (I->mayWriteToMemory())
1124       return false;
1125
1126     // I is used only inside this block then it is OK.
1127     bool usedOutsideBB = false;
1128     for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); 
1129          UI != UE; ++UI) {
1130       Instruction *U = cast<Instruction>(UI);
1131       if (U->getParent() != BB)
1132         usedOutsideBB = true;
1133     }
1134     if (!usedOutsideBB)
1135       continue;
1136
1137     // Otherwise we have a instruction that may not allow loop spliting.
1138     return false;
1139   }
1140   return true;
1141 }
1142
1143 /// IVisLT - If Op is comparing IV based value with an loop invariant and 
1144 /// IV based value is less than  the loop invariant then return the loop 
1145 /// invariant. Otherwise return NULL.
1146 Value * LoopIndexSplit::IVisLT(ICmpInst &Op) {
1147   ICmpInst::Predicate P = Op.getPredicate();
1148   if ((P == ICmpInst::ICMP_SLT || P == ICmpInst::ICMP_ULT) 
1149       && IVBasedValues.count(Op.getOperand(0)) 
1150       && L->isLoopInvariant(Op.getOperand(1)))
1151     return Op.getOperand(1);
1152
1153   if ((P == ICmpInst::ICMP_SGT || P == ICmpInst::ICMP_UGT) 
1154       && IVBasedValues.count(Op.getOperand(1)) 
1155       && L->isLoopInvariant(Op.getOperand(0)))
1156     return Op.getOperand(0);
1157
1158   return NULL;
1159 }
1160
1161 /// IVisLE - If Op is comparing IV based value with an loop invariant and 
1162 /// IV based value is less than or equal to the loop invariant then 
1163 /// return the loop invariant. Otherwise return NULL.
1164 Value * LoopIndexSplit::IVisLE(ICmpInst &Op) {
1165   ICmpInst::Predicate P = Op.getPredicate();
1166   if ((P == ICmpInst::ICMP_SLE || P == ICmpInst::ICMP_ULE)
1167       && IVBasedValues.count(Op.getOperand(0)) 
1168       && L->isLoopInvariant(Op.getOperand(1)))
1169     return Op.getOperand(1);
1170
1171   if ((P == ICmpInst::ICMP_SGE || P == ICmpInst::ICMP_UGE) 
1172       && IVBasedValues.count(Op.getOperand(1)) 
1173       && L->isLoopInvariant(Op.getOperand(0)))
1174     return Op.getOperand(0);
1175
1176   return NULL;
1177 }
1178
1179 /// IVisGT - If Op is comparing IV based value with an loop invariant and 
1180 /// IV based value is greater than  the loop invariant then return the loop 
1181 /// invariant. Otherwise return NULL.
1182 Value * LoopIndexSplit::IVisGT(ICmpInst &Op) {
1183   ICmpInst::Predicate P = Op.getPredicate();
1184   if ((P == ICmpInst::ICMP_SGT || P == ICmpInst::ICMP_UGT) 
1185       && IVBasedValues.count(Op.getOperand(0)) 
1186       && L->isLoopInvariant(Op.getOperand(1)))
1187     return Op.getOperand(1);
1188
1189   if ((P == ICmpInst::ICMP_SLT || P == ICmpInst::ICMP_ULT) 
1190       && IVBasedValues.count(Op.getOperand(1)) 
1191       && L->isLoopInvariant(Op.getOperand(0)))
1192     return Op.getOperand(0);
1193
1194   return NULL;
1195 }
1196
1197 /// IVisGE - If Op is comparing IV based value with an loop invariant and 
1198 /// IV based value is greater than or equal to the loop invariant then 
1199 /// return the loop invariant. Otherwise return NULL.
1200 Value * LoopIndexSplit::IVisGE(ICmpInst &Op) {
1201   ICmpInst::Predicate P = Op.getPredicate();
1202   if ((P == ICmpInst::ICMP_SGE || P == ICmpInst::ICMP_UGE)
1203       && IVBasedValues.count(Op.getOperand(0)) 
1204       && L->isLoopInvariant(Op.getOperand(1)))
1205     return Op.getOperand(1);
1206
1207   if ((P == ICmpInst::ICMP_SLE || P == ICmpInst::ICMP_ULE) 
1208       && IVBasedValues.count(Op.getOperand(1)) 
1209       && L->isLoopInvariant(Op.getOperand(0)))
1210     return Op.getOperand(0);
1211
1212   return NULL;
1213 }
1214