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