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