Reorder methods alphabetically. No functionality change.
[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.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "loop-index-split"
15
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Analysis/LoopPass.h"
18 #include "llvm/Analysis/ScalarEvolutionExpander.h"
19 #include "llvm/Analysis/Dominators.h"
20 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
21 #include "llvm/Transforms/Utils/Cloning.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/ADT/DepthFirstIterator.h"
24 #include "llvm/ADT/Statistic.h"
25
26 using namespace llvm;
27
28 STATISTIC(NumIndexSplit, "Number of loops index split");
29
30 namespace {
31
32   class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
33
34   public:
35     static char ID; // Pass ID, replacement for typeid
36     LoopIndexSplit() : LoopPass((intptr_t)&ID) {}
37
38     // Index split Loop L. Return true if loop is split.
39     bool runOnLoop(Loop *L, LPPassManager &LPM);
40
41     void getAnalysisUsage(AnalysisUsage &AU) const {
42       AU.addRequired<ScalarEvolution>();
43       AU.addPreserved<ScalarEvolution>();
44       AU.addRequiredID(LCSSAID);
45       AU.addPreservedID(LCSSAID);
46       AU.addRequired<LoopInfo>();
47       AU.addPreserved<LoopInfo>();
48       AU.addRequiredID(LoopSimplifyID);
49       AU.addPreservedID(LoopSimplifyID);
50       AU.addRequired<DominatorTree>();
51       AU.addRequired<DominanceFrontier>();
52       AU.addPreserved<DominatorTree>();
53       AU.addPreserved<DominanceFrontier>();
54     }
55
56   private:
57
58     class SplitInfo {
59     public:
60       SplitInfo() : SplitValue(NULL), SplitCondition(NULL), 
61                     UseTrueBranchFirst(true), A_ExitValue(NULL), 
62                     B_StartValue(NULL) {}
63
64       // Induction variable's range is split at this value.
65       Value *SplitValue;
66       
67       // This instruction compares IndVar against SplitValue.
68       Instruction *SplitCondition;
69
70       // True if after loop index split, first loop will execute split condition's
71       // true branch.
72       bool UseTrueBranchFirst;
73
74       // Exit value for first loop after loop split.
75       Value *A_ExitValue;
76
77       // Start value for second loop after loop split.
78       Value *B_StartValue;
79
80       // Clear split info.
81       void clear() {
82         SplitValue = NULL;
83         SplitCondition = NULL;
84         UseTrueBranchFirst = true;
85         A_ExitValue = NULL;
86         B_StartValue = NULL;
87       }
88
89     };
90     
91   private:
92
93     // safeIcmpInst - CI is considered safe instruction if one of the operand
94     // is SCEVAddRecExpr based on induction variable and other operand is
95     // loop invariant. If CI is safe then populate SplitInfo object SD appropriately
96     // and return true;
97     bool safeICmpInst(ICmpInst *CI, SplitInfo &SD);
98
99     /// Find condition inside a loop that is suitable candidate for index split.
100     void findSplitCondition();
101
102     /// Find loop's exit condition.
103     void findLoopConditionals();
104
105     /// Return induction variable associated with value V.
106     void findIndVar(Value *V, Loop *L);
107
108     /// processOneIterationLoop - Current loop L contains compare instruction
109     /// that compares induction variable, IndVar, agains loop invariant. If
110     /// entire (i.e. meaningful) loop body is dominated by this compare
111     /// instruction then loop body is executed only for one iteration. In
112     /// such case eliminate loop structure surrounding this loop body. For
113     bool processOneIterationLoop(SplitInfo &SD);
114
115     void updateLoopBounds(ICmpInst *CI);
116     /// updateLoopIterationSpace - Current loop body is covered by an AND
117     /// instruction whose operands compares induction variables with loop
118     /// invariants. If possible, hoist this check outside the loop by
119     /// updating appropriate start and end values for induction variable.
120     bool updateLoopIterationSpace(SplitInfo &SD);
121
122     /// If loop header includes loop variant instruction operands then
123     /// this loop may not be eliminated.
124     bool safeHeader(SplitInfo &SD,  BasicBlock *BB);
125
126     /// If Exiting block includes loop variant instructions then this
127     /// loop may not be eliminated.
128     bool safeExitingBlock(SplitInfo &SD, BasicBlock *BB);
129
130     /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
131     /// This routine is used to remove split condition's dead branch, dominated by
132     /// DeadBB. LiveBB dominates split conidition's other branch.
133     void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
134
135     /// safeSplitCondition - Return true if it is possible to
136     /// split loop using given split condition.
137     bool safeSplitCondition(SplitInfo &SD);
138
139     /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
140     /// based on split value. 
141     void calculateLoopBounds(SplitInfo &SD);
142
143     /// updatePHINodes - CFG has been changed. 
144     /// Before 
145     ///   - ExitBB's single predecessor was Latch
146     ///   - Latch's second successor was Header
147     /// Now
148     ///   - ExitBB's single predecessor was Header
149     ///   - Latch's one and only successor was Header
150     ///
151     /// Update ExitBB PHINodes' to reflect this change.
152     void updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch, 
153                         BasicBlock *Header,
154                         PHINode *IV, Instruction *IVIncrement, Loop *LP);
155
156     /// moveExitCondition - Move exit condition EC into split condition block CondBB.
157     void moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
158                            BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
159                            PHINode *IV, Instruction *IVAdd, Loop *LP);
160
161     /// splitLoop - Split current loop L in two loops using split information
162     /// SD. Update dominator information. Maintain LCSSA form.
163     bool splitLoop(SplitInfo &SD);
164
165     void initialize() {
166       IndVar = NULL; 
167       IndVarIncrement = NULL;
168       ExitCondition = NULL;
169       StartValue = NULL;
170       ExitValueNum = 0;
171       SplitData.clear();
172     }
173
174   private:
175
176     // Current Loop.
177     Loop *L;
178     LPPassManager *LPM;
179     LoopInfo *LI;
180     ScalarEvolution *SE;
181     DominatorTree *DT;
182     DominanceFrontier *DF;
183     SmallVector<SplitInfo, 4> SplitData;
184
185     // Induction variable whose range is being split by this transformation.
186     PHINode *IndVar;
187     Instruction *IndVarIncrement;
188       
189     // Loop exit condition.
190     ICmpInst *ExitCondition;
191
192     // Induction variable's initial value.
193     Value *StartValue;
194
195     // Induction variable's final loop exit value operand number in exit condition..
196     unsigned ExitValueNum;
197   };
198 }
199
200 char LoopIndexSplit::ID = 0;
201 static RegisterPass<LoopIndexSplit>
202 X("loop-index-split", "Index Split Loops");
203
204 LoopPass *llvm::createLoopIndexSplitPass() {
205   return new LoopIndexSplit();
206 }
207
208 // Index split Loop L. Return true if loop is split.
209 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
210   bool Changed = false;
211   L = IncomingLoop;
212   LPM = &LPM_Ref;
213
214   // FIXME - Nested loops make dominator info updates tricky. 
215   if (!L->getSubLoops().empty())
216     return false;
217
218   SE = &getAnalysis<ScalarEvolution>();
219   DT = &getAnalysis<DominatorTree>();
220   LI = &getAnalysis<LoopInfo>();
221   DF = &getAnalysis<DominanceFrontier>();
222
223   initialize();
224
225   findLoopConditionals();
226
227   if (!ExitCondition)
228     return false;
229
230   findSplitCondition();
231
232   if (SplitData.empty())
233     return false;
234
235   // First see if it is possible to eliminate loop itself or not.
236   for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin();
237        SI != SplitData.end();) {
238     SplitInfo &SD = *SI;
239     ICmpInst *CI = dyn_cast<ICmpInst>(SD.SplitCondition);
240     if (SD.SplitCondition->getOpcode() == Instruction::And) {
241       Changed = updateLoopIterationSpace(SD);
242       if (Changed) {
243         ++NumIndexSplit;
244         // If is loop is eliminated then nothing else to do here.
245         return Changed;
246       } else {
247         SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
248         SI = SplitData.erase(Delete_SI);
249       }
250     }
251     else if (CI && CI->getPredicate() == ICmpInst::ICMP_EQ) {
252       Changed = processOneIterationLoop(SD);
253       if (Changed) {
254         ++NumIndexSplit;
255         // If is loop is eliminated then nothing else to do here.
256         return Changed;
257       } else {
258         SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
259         SI = SplitData.erase(Delete_SI);
260       }
261     } else
262       ++SI;
263   }
264
265   if (SplitData.empty())
266     return false;
267
268   // Split most profitiable condition.
269   // FIXME : Implement cost analysis.
270   unsigned MostProfitableSDIndex = 0;
271   Changed = splitLoop(SplitData[MostProfitableSDIndex]);
272
273   if (Changed)
274     ++NumIndexSplit;
275   
276   return Changed;
277 }
278
279 /// Return true if V is a induction variable or induction variable's
280 /// increment for loop L.
281 void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
282   
283   Instruction *I = dyn_cast<Instruction>(V);
284   if (!I)
285     return;
286
287   // Check if I is a phi node from loop header or not.
288   if (PHINode *PN = dyn_cast<PHINode>(V)) {
289     if (PN->getParent() == L->getHeader()) {
290       IndVar = PN;
291       return;
292     }
293   }
294  
295   // Check if I is a add instruction whose one operand is
296   // phi node from loop header and second operand is constant.
297   if (I->getOpcode() != Instruction::Add)
298     return;
299   
300   Value *Op0 = I->getOperand(0);
301   Value *Op1 = I->getOperand(1);
302   
303   if (PHINode *PN = dyn_cast<PHINode>(Op0)) 
304     if (PN->getParent() == L->getHeader()) 
305       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) 
306         if (CI->isOne()) {
307           IndVar = PN;
308           IndVarIncrement = I;
309           return;
310         }
311
312   if (PHINode *PN = dyn_cast<PHINode>(Op1)) 
313     if (PN->getParent() == L->getHeader()) 
314       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0)) 
315         if (CI->isOne()) {
316           IndVar = PN;
317           IndVarIncrement = I;
318           return;
319         }
320   
321   return;
322 }
323
324 // Find loop's exit condition and associated induction variable.
325 void LoopIndexSplit::findLoopConditionals() {
326
327   BasicBlock *ExitingBlock = NULL;
328
329   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
330        I != E; ++I) {
331     BasicBlock *BB = *I;
332     if (!L->isLoopExit(BB))
333       continue;
334     if (ExitingBlock)
335       return;
336     ExitingBlock = BB;
337   }
338
339   if (!ExitingBlock)
340     return;
341
342   // If exiting block is neither loop header nor loop latch then this loop is
343   // not suitable. 
344   if (ExitingBlock != L->getHeader() && ExitingBlock != L->getLoopLatch())
345     return;
346
347   // If exit block's terminator is conditional branch inst then we have found
348   // exit condition.
349   BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
350   if (!BR || BR->isUnconditional())
351     return;
352   
353   ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
354   if (!CI)
355     return;
356
357   // FIXME 
358   if (CI->getPredicate() == ICmpInst::ICMP_EQ
359       || CI->getPredicate() == ICmpInst::ICMP_NE)
360     return;
361
362   ExitCondition = CI;
363
364   // Exit condition's one operand is loop invariant exit value and second 
365   // operand is SCEVAddRecExpr based on induction variable.
366   Value *V0 = CI->getOperand(0);
367   Value *V1 = CI->getOperand(1);
368   
369   SCEVHandle SH0 = SE->getSCEV(V0);
370   SCEVHandle SH1 = SE->getSCEV(V1);
371   
372   if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
373     ExitValueNum = 0;
374     findIndVar(V1, L);
375   }
376   else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
377     ExitValueNum =  1;
378     findIndVar(V0, L);
379   }
380
381   if (!IndVar) 
382     ExitCondition = NULL;
383   else if (IndVar) {
384     BasicBlock *Preheader = L->getLoopPreheader();
385     StartValue = IndVar->getIncomingValueForBlock(Preheader);
386   }
387
388   // If start value is more then exit value where induction variable
389   // increments by 1 then we are potentially dealing with an infinite loop.
390   // Do not index split this loop.
391   if (ExitCondition) {
392     ConstantInt *SV = dyn_cast<ConstantInt>(StartValue);
393     ConstantInt *EV = 
394       dyn_cast<ConstantInt>(ExitCondition->getOperand(ExitValueNum));
395     if (SV && EV && SV->getSExtValue() > EV->getSExtValue())
396       ExitCondition = NULL;
397     else if (EV && EV->isZero())
398       ExitCondition = NULL;
399   }
400 }
401
402 /// Find condition inside a loop that is suitable candidate for index split.
403 void LoopIndexSplit::findSplitCondition() {
404
405   SplitInfo SD;
406   // Check all basic block's terminators.
407   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
408        I != E; ++I) {
409     SD.clear();
410     BasicBlock *BB = *I;
411
412     // If this basic block does not terminate in a conditional branch
413     // then terminator is not a suitable split condition.
414     BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
415     if (!BR)
416       continue;
417     
418     if (BR->isUnconditional())
419       continue;
420
421     if (Instruction *AndI = dyn_cast<Instruction>(BR->getCondition())) {
422       if (AndI->getOpcode() == Instruction::And) {
423         ICmpInst *Op0 = dyn_cast<ICmpInst>(AndI->getOperand(0));
424         ICmpInst *Op1 = dyn_cast<ICmpInst>(AndI->getOperand(1));
425
426         if (!Op0 || !Op1)
427           continue;
428
429         if (!safeICmpInst(Op0, SD))
430           continue;
431         SD.clear();
432         if (!safeICmpInst(Op1, SD))
433           continue;
434         SD.clear();
435         SD.SplitCondition = AndI;
436         SplitData.push_back(SD);
437         continue;
438       }
439     }
440     ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
441     if (!CI || CI == ExitCondition)
442       continue;
443
444     if (CI->getPredicate() == ICmpInst::ICMP_NE)
445       continue;
446
447     // If split condition predicate is GT or GE then first execute
448     // false branch of split condition.
449     if (CI->getPredicate() == ICmpInst::ICMP_UGT
450         || CI->getPredicate() == ICmpInst::ICMP_SGT
451         || CI->getPredicate() == ICmpInst::ICMP_UGE
452         || CI->getPredicate() == ICmpInst::ICMP_SGE)
453       SD.UseTrueBranchFirst = false;
454
455     // If one operand is loop invariant and second operand is SCEVAddRecExpr
456     // based on induction variable then CI is a candidate split condition.
457     if (safeICmpInst(CI, SD))
458       SplitData.push_back(SD);
459   }
460 }
461
462 // safeIcmpInst - CI is considered safe instruction if one of the operand
463 // is SCEVAddRecExpr based on induction variable and other operand is
464 // loop invariant. If CI is safe then populate SplitInfo object SD appropriately
465 // and return true;
466 bool LoopIndexSplit::safeICmpInst(ICmpInst *CI, SplitInfo &SD) {
467
468   Value *V0 = CI->getOperand(0);
469   Value *V1 = CI->getOperand(1);
470   
471   SCEVHandle SH0 = SE->getSCEV(V0);
472   SCEVHandle SH1 = SE->getSCEV(V1);
473   
474   if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
475     SD.SplitValue = V0;
476     SD.SplitCondition = CI;
477     if (PHINode *PN = dyn_cast<PHINode>(V1)) {
478       if (PN == IndVar)
479         return true;
480     }
481     else  if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
482       if (IndVarIncrement && IndVarIncrement == Insn)
483         return true;
484     }
485   }
486   else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
487     SD.SplitValue =  V1;
488     SD.SplitCondition = CI;
489     if (PHINode *PN = dyn_cast<PHINode>(V0)) {
490       if (PN == IndVar)
491         return true;
492     }
493     else  if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
494       if (IndVarIncrement && IndVarIncrement == Insn)
495         return true;
496     }
497   }
498
499   return false;
500 }
501
502 /// processOneIterationLoop - Current loop L contains compare instruction
503 /// that compares induction variable, IndVar, against loop invariant. If
504 /// entire (i.e. meaningful) loop body is dominated by this compare
505 /// instruction then loop body is executed only once. In such case eliminate 
506 /// loop structure surrounding this loop body. For example,
507 ///     for (int i = start; i < end; ++i) {
508 ///         if ( i == somevalue) {
509 ///           loop_body
510 ///         }
511 ///     }
512 /// can be transformed into
513 ///     if (somevalue >= start && somevalue < end) {
514 ///        i = somevalue;
515 ///        loop_body
516 ///     }
517 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
518
519   BasicBlock *Header = L->getHeader();
520
521   // First of all, check if SplitCondition dominates entire loop body
522   // or not.
523   
524   // If SplitCondition is not in loop header then this loop is not suitable
525   // for this transformation.
526   if (SD.SplitCondition->getParent() != Header)
527     return false;
528   
529   // If loop header includes loop variant instruction operands then
530   // this loop may not be eliminated.
531   if (!safeHeader(SD, Header)) 
532     return false;
533
534   // If Exiting block includes loop variant instructions then this
535   // loop may not be eliminated.
536   if (!safeExitingBlock(SD, ExitCondition->getParent())) 
537     return false;
538
539   // Filter loops where split condition's false branch is not empty.
540   if (ExitCondition->getParent() != Header->getTerminator()->getSuccessor(1))
541     return false;
542
543   // If split condition is not safe then do not process this loop.
544   // For example,
545   // for(int i = 0; i < N; i++) {
546   //    if ( i == XYZ) {
547   //      A;
548   //    else
549   //      B;
550   //    }
551   //   C;
552   //   D;
553   // }
554   if (!safeSplitCondition(SD))
555     return false;
556
557   BasicBlock *Latch = L->getLoopLatch();
558   BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
559   if (!BR)
560     return false;
561
562   // Update CFG.
563
564   // Replace index variable with split value in loop body. Loop body is executed
565   // only when index variable is equal to split value.
566   IndVar->replaceAllUsesWith(SD.SplitValue);
567
568   // Remove Latch to Header edge.
569   BasicBlock *LatchSucc = NULL;
570   Header->removePredecessor(Latch);
571   for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
572        SI != E; ++SI) {
573     if (Header != *SI)
574       LatchSucc = *SI;
575   }
576   BR->setUnconditionalDest(LatchSucc);
577
578   Instruction *Terminator = Header->getTerminator();
579   Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
580
581   // Replace split condition in header.
582   // Transform 
583   //      SplitCondition : icmp eq i32 IndVar, SplitValue
584   // into
585   //      c1 = icmp uge i32 SplitValue, StartValue
586   //      c2 = icmp ult i32 SplitValue, ExitValue
587   //      and i32 c1, c2 
588   bool SignedPredicate = ExitCondition->isSignedPredicate();
589   Instruction *C1 = new ICmpInst(SignedPredicate ? 
590                                  ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
591                                  SD.SplitValue, StartValue, "lisplit", 
592                                  Terminator);
593   Instruction *C2 = new ICmpInst(SignedPredicate ? 
594                                  ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
595                                  SD.SplitValue, ExitValue, "lisplit", 
596                                  Terminator);
597   Instruction *NSplitCond = BinaryOperator::CreateAnd(C1, C2, "lisplit", 
598                                                       Terminator);
599   SD.SplitCondition->replaceAllUsesWith(NSplitCond);
600   SD.SplitCondition->eraseFromParent();
601
602   // Now, clear latch block. Remove instructions that are responsible
603   // to increment induction variable. 
604   Instruction *LTerminator = Latch->getTerminator();
605   for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
606        LB != LE; ) {
607     Instruction *I = LB;
608     ++LB;
609     if (isa<PHINode>(I) || I == LTerminator)
610       continue;
611
612     if (I == IndVarIncrement) {
613       // Replace induction variable increment if it is not used outside 
614       // the loop.
615       bool UsedOutsideLoop = false;
616       for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); 
617            UI != E; ++UI) {
618         if (Instruction *Use = dyn_cast<Instruction>(UI)) 
619           if (!L->contains(Use->getParent())) {
620             UsedOutsideLoop = true;
621             break;
622           }
623       }
624       if (!UsedOutsideLoop) {
625         I->replaceAllUsesWith(ExitValue);
626         I->eraseFromParent();
627       }
628     }
629     else {
630       I->replaceAllUsesWith(UndefValue::get(I->getType()));
631       I->eraseFromParent();
632     }
633   }
634
635   LPM->deleteLoopFromQueue(L);
636
637   // Update Dominator Info.
638   // Only CFG change done is to remove Latch to Header edge. This
639   // does not change dominator tree because Latch did not dominate
640   // Header.
641   if (DF) {
642     DominanceFrontier::iterator HeaderDF = DF->find(Header);
643     if (HeaderDF != DF->end()) 
644       DF->removeFromFrontier(HeaderDF, Header);
645
646     DominanceFrontier::iterator LatchDF = DF->find(Latch);
647     if (LatchDF != DF->end()) 
648       DF->removeFromFrontier(LatchDF, Header);
649   }
650   return true;
651 }
652
653 // If loop header includes loop variant instruction operands then
654 // this loop can not be eliminated. This is used by processOneIterationLoop().
655 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
656
657   Instruction *Terminator = Header->getTerminator();
658   for(BasicBlock::iterator BI = Header->begin(), BE = Header->end(); 
659       BI != BE; ++BI) {
660     Instruction *I = BI;
661
662     // PHI Nodes are OK.
663     if (isa<PHINode>(I))
664       continue;
665
666     // SplitCondition itself is OK.
667     if (I == SD.SplitCondition)
668       continue;
669
670     // Induction variable is OK.
671     if (I == IndVar)
672       continue;
673
674     // Induction variable increment is OK.
675     if (I == IndVarIncrement)
676       continue;
677
678     // Terminator is also harmless.
679     if (I == Terminator)
680       continue;
681
682     // Otherwise we have a instruction that may not be safe.
683     return false;
684   }
685   
686   return true;
687 }
688
689 // If Exiting block includes loop variant instructions then this
690 // loop may not be eliminated. This is used by processOneIterationLoop().
691 bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD, 
692                                        BasicBlock *ExitingBlock) {
693
694   for (BasicBlock::iterator BI = ExitingBlock->begin(), 
695          BE = ExitingBlock->end(); BI != BE; ++BI) {
696     Instruction *I = BI;
697
698     // PHI Nodes are OK.
699     if (isa<PHINode>(I))
700       continue;
701
702     // Induction variable increment is OK.
703     if (IndVarIncrement && IndVarIncrement == I)
704       continue;
705
706     // Check if I is induction variable increment instruction.
707     if (I->getOpcode() == Instruction::Add) {
708
709       Value *Op0 = I->getOperand(0);
710       Value *Op1 = I->getOperand(1);
711       PHINode *PN = NULL;
712       ConstantInt *CI = NULL;
713
714       if ((PN = dyn_cast<PHINode>(Op0))) {
715         if ((CI = dyn_cast<ConstantInt>(Op1)))
716           if (CI->isOne()) {
717             if (!IndVarIncrement && PN == IndVar)
718               IndVarIncrement = I;
719             // else this is another loop induction variable
720             continue;
721           }
722       } else 
723         if ((PN = dyn_cast<PHINode>(Op1))) {
724           if ((CI = dyn_cast<ConstantInt>(Op0)))
725             if (CI->isOne()) {
726               if (!IndVarIncrement && PN == IndVar)
727                 IndVarIncrement = I;
728               // else this is another loop induction variable
729               continue;
730             }
731       }
732     } 
733
734     // I is an Exit condition if next instruction is block terminator.
735     // Exit condition is OK if it compares loop invariant exit value,
736     // which is checked below.
737     else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
738       if (EC == ExitCondition)
739         continue;
740     }
741
742     if (I == ExitingBlock->getTerminator())
743       continue;
744
745     // Otherwise we have instruction that may not be safe.
746     return false;
747   }
748
749   // We could not find any reason to consider ExitingBlock unsafe.
750   return true;
751 }
752
753 void LoopIndexSplit::updateLoopBounds(ICmpInst *CI) {
754
755   Value *V0 = CI->getOperand(0);
756   Value *V1 = CI->getOperand(1);
757   Value *NV = NULL;
758
759   SCEVHandle SH0 = SE->getSCEV(V0);
760   
761   if (SH0->isLoopInvariant(L))
762     NV = V0;
763   else
764     NV = V1;
765
766   if (ExitCondition->getPredicate() == ICmpInst::ICMP_SGT
767       || ExitCondition->getPredicate() == ICmpInst::ICMP_UGT
768       || ExitCondition->getPredicate() == ICmpInst::ICMP_SGE
769       || ExitCondition->getPredicate() == ICmpInst::ICMP_UGE)  {
770     ExitCondition->swapOperands();
771     if (ExitValueNum)
772       ExitValueNum = 0;
773     else
774       ExitValueNum = 1;
775   }
776
777   Value *NUB = NULL;
778   Value *NLB = NULL;
779   Value *UB = ExitCondition->getOperand(ExitValueNum);
780   const Type *Ty = NV->getType();
781   bool Sign = ExitCondition->isSignedPredicate();
782   BasicBlock *Preheader = L->getLoopPreheader();
783   Instruction *PHTerminator = Preheader->getTerminator();
784
785   assert (NV && "Unexpected value");
786
787   switch (CI->getPredicate()) {
788   case ICmpInst::ICMP_ULE:
789   case ICmpInst::ICMP_SLE:
790     // for (i = LB; i < UB; ++i)
791     //   if (i <= NV && ...)
792     //      LOOP_BODY
793     // 
794     // is transformed into
795     // NUB = min (NV+1, UB)
796     // for (i = LB; i < NUB ; ++i)
797     //   LOOP_BODY
798     //
799     if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLT
800         || ExitCondition->getPredicate() == ICmpInst::ICMP_ULT) {
801       Value *A = BinaryOperator::CreateAdd(NV, ConstantInt::get(Ty, 1, Sign),
802                                            "lsplit.add", PHTerminator);
803       Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
804                               A, UB,"lsplit,c", PHTerminator);
805       NUB = SelectInst::Create(C, A, UB, "lsplit.nub", PHTerminator);
806     }
807     
808     // for (i = LB; i <= UB; ++i)
809     //   if (i <= NV && ...)
810     //      LOOP_BODY
811     // 
812     // is transformed into
813     // NUB = min (NV, UB)
814     // for (i = LB; i <= NUB ; ++i)
815     //   LOOP_BODY
816     //
817     else if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLE
818              || ExitCondition->getPredicate() == ICmpInst::ICMP_ULE) {
819       Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
820                               NV, UB, "lsplit.c", PHTerminator);
821       NUB = SelectInst::Create(C, NV, UB, "lsplit.nub", PHTerminator);
822     }
823     break;
824   case ICmpInst::ICMP_ULT:
825   case ICmpInst::ICMP_SLT:
826     // for (i = LB; i < UB; ++i)
827     //   if (i < NV && ...)
828     //      LOOP_BODY
829     // 
830     // is transformed into
831     // NUB = min (NV, UB)
832     // for (i = LB; i < NUB ; ++i)
833     //   LOOP_BODY
834     //
835     if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLT
836         || ExitCondition->getPredicate() == ICmpInst::ICMP_ULT) {
837       Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
838                               NV, UB, "lsplit.c", PHTerminator);
839       NUB = SelectInst::Create(C, NV, UB, "lsplit.nub", PHTerminator);
840     }
841
842     // for (i = LB; i <= UB; ++i)
843     //   if (i < NV && ...)
844     //      LOOP_BODY
845     // 
846     // is transformed into
847     // NUB = min (NV -1 , UB)
848     // for (i = LB; i <= NUB ; ++i)
849     //   LOOP_BODY
850     //
851     else if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLE
852              || ExitCondition->getPredicate() == ICmpInst::ICMP_ULE) {
853       Value *S = BinaryOperator::CreateSub(NV, ConstantInt::get(Ty, 1, Sign),
854                                            "lsplit.add", PHTerminator);
855       Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
856                               S, UB, "lsplit.c", PHTerminator);
857       NUB = SelectInst::Create(C, S, UB, "lsplit.nub", PHTerminator);
858     }
859     break;
860   case ICmpInst::ICMP_UGE:
861   case ICmpInst::ICMP_SGE:
862     // for (i = LB; i (< or <=) UB; ++i)
863     //   if (i >= NV && ...)
864     //      LOOP_BODY
865     // 
866     // is transformed into
867     // NLB = max (NV, LB)
868     // for (i = NLB; i (< or <=) UB ; ++i)
869     //   LOOP_BODY
870     //
871     {
872       Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
873                               NV, StartValue, "lsplit.c", PHTerminator);
874       NLB = SelectInst::Create(C, StartValue, NV, "lsplit.nlb", PHTerminator);
875     }
876     break;
877   case ICmpInst::ICMP_UGT:
878   case ICmpInst::ICMP_SGT:
879     // for (i = LB; i (< or <=) UB; ++i)
880     //   if (i > NV && ...)
881     //      LOOP_BODY
882     // 
883     // is transformed into
884     // NLB = max (NV+1, LB)
885     // for (i = NLB; i (< or <=) UB ; ++i)
886     //   LOOP_BODY
887     //
888     {
889       Value *A = BinaryOperator::CreateAdd(NV, ConstantInt::get(Ty, 1, Sign),
890                                            "lsplit.add", PHTerminator);
891       Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
892                               A, StartValue, "lsplit.c", PHTerminator);
893       NLB = SelectInst::Create(C, StartValue, A, "lsplit.nlb", PHTerminator);
894     }
895     break;
896   default:
897     assert ( 0 && "Unexpected split condition predicate");
898   }
899
900   if (NLB) {
901     unsigned i = IndVar->getBasicBlockIndex(Preheader);
902     IndVar->setIncomingValue(i, NLB);
903   }
904
905   if (NUB) {
906     ExitCondition->setOperand(ExitValueNum, NUB);
907   }
908 }
909 /// updateLoopIterationSpace - Current loop body is covered by an AND
910 /// instruction whose operands compares induction variables with loop
911 /// invariants. If possible, hoist this check outside the loop by
912 /// updating appropriate start and end values for induction variable.
913 bool LoopIndexSplit::updateLoopIterationSpace(SplitInfo &SD) {
914   BasicBlock *Header = L->getHeader();
915   BasicBlock *ExitingBlock = ExitCondition->getParent();
916   BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
917
918   ICmpInst *Op0 = cast<ICmpInst>(SD.SplitCondition->getOperand(0));
919   ICmpInst *Op1 = cast<ICmpInst>(SD.SplitCondition->getOperand(1));
920
921   if (Op0->getPredicate() == ICmpInst::ICMP_EQ 
922       || Op0->getPredicate() == ICmpInst::ICMP_NE
923       || Op0->getPredicate() == ICmpInst::ICMP_EQ 
924       || Op0->getPredicate() == ICmpInst::ICMP_NE)
925     return false;
926
927   // Check if SplitCondition dominates entire loop body
928   // or not.
929   
930   // If SplitCondition is not in loop header then this loop is not suitable
931   // for this transformation.
932   if (SD.SplitCondition->getParent() != Header)
933     return false;
934   
935   // If loop header includes loop variant instruction operands then
936   // this loop may not be eliminated.
937   Instruction *Terminator = Header->getTerminator();
938   for(BasicBlock::iterator BI = Header->begin(), BE = Header->end(); 
939       BI != BE; ++BI) {
940     Instruction *I = BI;
941
942     // PHI Nodes are OK.
943     if (isa<PHINode>(I))
944       continue;
945
946     // SplitCondition itself is OK.
947     if (I == SD.SplitCondition)
948       continue;
949     if (I == Op0 || I == Op1)
950       continue;
951
952     // Induction variable is OK.
953     if (I == IndVar)
954       continue;
955
956     // Induction variable increment is OK.
957     if (I == IndVarIncrement)
958       continue;
959
960     // Terminator is also harmless.
961     if (I == Terminator)
962       continue;
963
964     // Otherwise we have a instruction that may not be safe.
965     return false;
966   }
967
968   // If Exiting block includes loop variant instructions then this
969   // loop may not be eliminated.
970   if (!safeExitingBlock(SD, ExitCondition->getParent())) 
971     return false;
972   
973   // Verify that loop exiting block has only two predecessor, where one predecessor
974   // is split condition block. The other predecessor will become exiting block's
975   // dominator after CFG is updated. TODO : Handle CFG's where exiting block has
976   // more then two predecessors. This requires extra work in updating dominator
977   // information.
978   BasicBlock *ExitingBBPred = NULL;
979   for (pred_iterator PI = pred_begin(ExitingBlock), PE = pred_end(ExitingBlock);
980        PI != PE; ++PI) {
981     BasicBlock *BB = *PI;
982     if (SplitCondBlock == BB) 
983       continue;
984     if (ExitingBBPred)
985       return false;
986     else
987       ExitingBBPred = BB;
988   }
989   
990   // Update loop bounds to absorb Op0 check.
991   updateLoopBounds(Op0);
992   // Update loop bounds to absorb Op1 check.
993   updateLoopBounds(Op1);
994
995   // Update CFG
996
997   // Unconditionally connect split block to its remaining successor. 
998   BranchInst *SplitTerminator = 
999     cast<BranchInst>(SplitCondBlock->getTerminator());
1000   BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1001   BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1002   if (Succ0 == ExitCondition->getParent())
1003     SplitTerminator->setUnconditionalDest(Succ1);
1004   else
1005     SplitTerminator->setUnconditionalDest(Succ0);
1006
1007   // Remove split condition.
1008   SD.SplitCondition->eraseFromParent();
1009   if (Op0->use_begin() == Op0->use_end())
1010     Op0->eraseFromParent();
1011   if (Op1->use_begin() == Op1->use_end())
1012     Op1->eraseFromParent();
1013       
1014   BranchInst *ExitInsn =
1015     dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1016   assert (ExitInsn && "Unable to find suitable loop exit branch");
1017   BasicBlock *ExitBlock = ExitInsn->getSuccessor(1);
1018   if (L->contains(ExitBlock))
1019     ExitBlock = ExitInsn->getSuccessor(0);
1020
1021   // Update domiantor info. Now, ExitingBlock has only one predecessor, 
1022   // ExitingBBPred, and it is ExitingBlock's immediate domiantor.
1023   DT->changeImmediateDominator(ExitingBlock, ExitingBBPred);
1024   
1025   // If ExitingBlock is a member of loop BB's DF list then replace it with
1026   // loop header and exit block.
1027   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
1028        I != E; ++I) {
1029     BasicBlock *BB = *I;
1030     if (BB == Header || BB == ExitingBlock)
1031       continue;
1032     DominanceFrontier::iterator BBDF = DF->find(BB);
1033     DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1034     DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1035     while (DomSetI != DomSetE) {
1036       DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1037       ++DomSetI;
1038       BasicBlock *DFBB = *CurrentItr;
1039       if (DFBB == ExitingBlock) {
1040         BBDF->second.erase(DFBB);
1041         BBDF->second.insert(Header);
1042         if (Header != ExitingBlock)
1043           BBDF->second.insert(ExitBlock);
1044       }
1045     }
1046   }
1047
1048   return true;
1049 }
1050
1051
1052 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
1053 /// This routine is used to remove split condition's dead branch, dominated by
1054 /// DeadBB. LiveBB dominates split conidition's other branch.
1055 void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP, 
1056                                   BasicBlock *LiveBB) {
1057
1058   // First update DeadBB's dominance frontier. 
1059   SmallVector<BasicBlock *, 8> FrontierBBs;
1060   DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
1061   if (DeadBBDF != DF->end()) {
1062     SmallVector<BasicBlock *, 8> PredBlocks;
1063     
1064     DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
1065     for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
1066            DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
1067       BasicBlock *FrontierBB = *DeadBBSetI;
1068       FrontierBBs.push_back(FrontierBB);
1069
1070       // Rremove any PHI incoming edge from blocks dominated by DeadBB.
1071       PredBlocks.clear();
1072       for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
1073           PI != PE; ++PI) {
1074         BasicBlock *P = *PI;
1075         if (P == DeadBB || DT->dominates(DeadBB, P))
1076           PredBlocks.push_back(P);
1077       }
1078
1079       for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
1080           FBI != FBE; ++FBI) {
1081         if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
1082           for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
1083                 PE = PredBlocks.end(); PI != PE; ++PI) {
1084             BasicBlock *P = *PI;
1085             PN->removeIncomingValue(P);
1086           }
1087         }
1088         else
1089           break;
1090       }      
1091     }
1092   }
1093   
1094   // Now remove DeadBB and all nodes dominated by DeadBB in df order.
1095   SmallVector<BasicBlock *, 32> WorkList;
1096   DomTreeNode *DN = DT->getNode(DeadBB);
1097   for (df_iterator<DomTreeNode*> DI = df_begin(DN),
1098          E = df_end(DN); DI != E; ++DI) {
1099     BasicBlock *BB = DI->getBlock();
1100     WorkList.push_back(BB);
1101     BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
1102   }
1103
1104   while (!WorkList.empty()) {
1105     BasicBlock *BB = WorkList.back(); WorkList.pop_back();
1106     for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end(); 
1107         BBI != BBE; ) {
1108       Instruction *I = BBI;
1109       ++BBI;
1110       I->replaceAllUsesWith(UndefValue::get(I->getType()));
1111       I->eraseFromParent();
1112     }
1113     LPM->deleteSimpleAnalysisValue(BB, LP);
1114     DT->eraseNode(BB);
1115     DF->removeBlock(BB);
1116     LI->removeBlock(BB);
1117     BB->eraseFromParent();
1118   }
1119
1120   // Update Frontier BBs' dominator info.
1121   while (!FrontierBBs.empty()) {
1122     BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
1123     BasicBlock *NewDominator = FBB->getSinglePredecessor();
1124     if (!NewDominator) {
1125       pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
1126       NewDominator = *PI;
1127       ++PI;
1128       if (NewDominator != LiveBB) {
1129         for(; PI != PE; ++PI) {
1130           BasicBlock *P = *PI;
1131           if (P == LiveBB) {
1132             NewDominator = LiveBB;
1133             break;
1134           }
1135           NewDominator = DT->findNearestCommonDominator(NewDominator, P);
1136         }
1137       }
1138     }
1139     assert (NewDominator && "Unable to fix dominator info.");
1140     DT->changeImmediateDominator(FBB, NewDominator);
1141     DF->changeImmediateDominator(FBB, NewDominator, DT);
1142   }
1143
1144 }
1145
1146 /// safeSplitCondition - Return true if it is possible to
1147 /// split loop using given split condition.
1148 bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
1149
1150   BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
1151   BasicBlock *Latch = L->getLoopLatch();  
1152   BranchInst *SplitTerminator = 
1153     cast<BranchInst>(SplitCondBlock->getTerminator());
1154   BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1155   BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1156
1157   // If split block does not dominate the latch then this is not a diamond.
1158   // Such loop may not benefit from index split.
1159   if (!DT->dominates(SplitCondBlock, Latch))
1160     return false;
1161
1162   // Finally this split condition is safe only if merge point for
1163   // split condition branch is loop latch. This check along with previous
1164   // check, to ensure that exit condition is in either loop latch or header,
1165   // filters all loops with non-empty loop body between merge point
1166   // and exit condition.
1167   DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
1168   assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
1169   if (Succ0DF->second.count(Latch))
1170     return true;
1171
1172   DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
1173   assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
1174   if (Succ1DF->second.count(Latch))
1175     return true;
1176   
1177   return false;
1178 }
1179
1180 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
1181 /// based on split value. 
1182 void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
1183
1184   ICmpInst *SC = cast<ICmpInst>(SD.SplitCondition);
1185   ICmpInst::Predicate SP = SC->getPredicate();
1186   const Type *Ty = SD.SplitValue->getType();
1187   bool Sign = ExitCondition->isSignedPredicate();
1188   BasicBlock *Preheader = L->getLoopPreheader();
1189   Instruction *PHTerminator = Preheader->getTerminator();
1190
1191   // Initially use split value as upper loop bound for first loop and lower loop
1192   // bound for second loop.
1193   Value *AEV = SD.SplitValue;
1194   Value *BSV = SD.SplitValue;
1195
1196   if (ExitCondition->getPredicate() == ICmpInst::ICMP_SGT
1197       || ExitCondition->getPredicate() == ICmpInst::ICMP_UGT
1198       || ExitCondition->getPredicate() == ICmpInst::ICMP_SGE
1199       || ExitCondition->getPredicate() == ICmpInst::ICMP_UGE) {
1200     ExitCondition->swapOperands();
1201     if (ExitValueNum)
1202       ExitValueNum = 0;
1203     else
1204       ExitValueNum = 1;
1205   }
1206
1207   switch (ExitCondition->getPredicate()) {
1208   case ICmpInst::ICMP_SGT:
1209   case ICmpInst::ICMP_UGT:
1210   case ICmpInst::ICMP_SGE:
1211   case ICmpInst::ICMP_UGE:
1212   default:
1213     assert (0 && "Unexpected exit condition predicate");
1214
1215   case ICmpInst::ICMP_SLT:
1216   case ICmpInst::ICMP_ULT:
1217     {
1218       switch (SP) {
1219       case ICmpInst::ICMP_SLT:
1220       case ICmpInst::ICMP_ULT:
1221         //
1222         // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
1223         //
1224         // is transformed into
1225         // AEV = BSV = SV
1226         // for (i = LB; i < min(UB, AEV); ++i)
1227         //    A;
1228         // for (i = max(LB, BSV); i < UB; ++i);
1229         //    B;
1230         break;
1231       case ICmpInst::ICMP_SLE:
1232       case ICmpInst::ICMP_ULE:
1233         {
1234           //
1235           // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
1236           //
1237           // is transformed into
1238           //
1239           // AEV = SV + 1
1240           // BSV = SV + 1
1241           // for (i = LB; i < min(UB, AEV); ++i) 
1242           //       A;
1243           // for (i = max(LB, BSV); i < UB; ++i) 
1244           //       B;
1245           BSV = BinaryOperator::CreateAdd(SD.SplitValue,
1246                                           ConstantInt::get(Ty, 1, Sign),
1247                                           "lsplit.add", PHTerminator);
1248           AEV = BSV;
1249         }
1250         break;
1251       case ICmpInst::ICMP_SGE:
1252       case ICmpInst::ICMP_UGE: 
1253         //
1254         // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
1255         // 
1256         // is transformed into
1257         // AEV = BSV = SV
1258         // for (i = LB; i < min(UB, AEV); ++i)
1259         //    B;
1260         // for (i = max(BSV, LB); i < UB; ++i)
1261         //    A;
1262         break;
1263       case ICmpInst::ICMP_SGT:
1264       case ICmpInst::ICMP_UGT: 
1265         {
1266           //
1267           // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
1268           //
1269           // is transformed into
1270           //
1271           // BSV = AEV = SV + 1
1272           // for (i = LB; i < min(UB, AEV); ++i) 
1273           //       B;
1274           // for (i = max(LB, BSV); i < UB; ++i) 
1275           //       A;
1276           BSV = BinaryOperator::CreateAdd(SD.SplitValue,
1277                                           ConstantInt::get(Ty, 1, Sign),
1278                                           "lsplit.add", PHTerminator);
1279           AEV = BSV;
1280         }
1281         break;
1282       default:
1283         assert (0 && "Unexpected split condition predicate");
1284         break;
1285       } // end switch (SP)
1286     }
1287     break;
1288   case ICmpInst::ICMP_SLE:
1289   case ICmpInst::ICMP_ULE:
1290     {
1291       switch (SP) {
1292       case ICmpInst::ICMP_SLT:
1293       case ICmpInst::ICMP_ULT:
1294         //
1295         // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
1296         //
1297         // is transformed into
1298         // AEV = SV - 1;
1299         // BSV = SV;
1300         // for (i = LB; i <= min(UB, AEV); ++i) 
1301         //       A;
1302         // for (i = max(LB, BSV); i <= UB; ++i) 
1303         //       B;
1304         AEV = BinaryOperator::CreateSub(SD.SplitValue,
1305                                         ConstantInt::get(Ty, 1, Sign),
1306                                         "lsplit.sub", PHTerminator);
1307         break;
1308       case ICmpInst::ICMP_SLE:
1309       case ICmpInst::ICMP_ULE:
1310         //
1311         // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
1312         //
1313         // is transformed into
1314         // AEV = SV;
1315         // BSV = SV + 1;
1316         // for (i = LB; i <= min(UB, AEV); ++i) 
1317         //       A;
1318         // for (i = max(LB, BSV); i <= UB; ++i) 
1319         //       B;
1320         BSV = BinaryOperator::CreateAdd(SD.SplitValue,
1321                                         ConstantInt::get(Ty, 1, Sign),
1322                                         "lsplit.add", PHTerminator);
1323         break;
1324       case ICmpInst::ICMP_SGT:
1325       case ICmpInst::ICMP_UGT: 
1326         //
1327         // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
1328         //
1329         // is transformed into
1330         // AEV = SV;
1331         // BSV = SV + 1;
1332         // for (i = LB; i <= min(AEV, UB); ++i)
1333         //      B;
1334         // for (i = max(LB, BSV); i <= UB; ++i)
1335         //      A;
1336         BSV = BinaryOperator::CreateAdd(SD.SplitValue,
1337                                         ConstantInt::get(Ty, 1, Sign),
1338                                         "lsplit.add", PHTerminator);
1339         break;
1340       case ICmpInst::ICMP_SGE:
1341       case ICmpInst::ICMP_UGE: 
1342         // ** TODO **
1343         //
1344         // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
1345         //
1346         // is transformed into
1347         // AEV = SV - 1;
1348         // BSV = SV;
1349         // for (i = LB; i <= min(AEV, UB); ++i)
1350         //      B;
1351         // for (i = max(LB, BSV); i <= UB; ++i)
1352         //      A;
1353         AEV = BinaryOperator::CreateSub(SD.SplitValue,
1354                                         ConstantInt::get(Ty, 1, Sign),
1355                                         "lsplit.sub", PHTerminator);
1356         break;
1357       default:
1358         assert (0 && "Unexpected split condition predicate");
1359         break;
1360       } // end switch (SP)
1361     }
1362     break;
1363   }
1364
1365   // Calculate ALoop induction variable's new exiting value and
1366   // BLoop induction variable's new starting value. Calculuate these
1367   // values in original loop's preheader.
1368   //      A_ExitValue = min(SplitValue, OrignalLoopExitValue)
1369   //      B_StartValue = max(SplitValue, OriginalLoopStartValue)
1370   Instruction *InsertPt = L->getHeader()->getFirstNonPHI();
1371
1372   // If ExitValue operand is also defined in Loop header then
1373   // insert new ExitValue after this operand definition.
1374   if (Instruction *EVN = 
1375       dyn_cast<Instruction>(ExitCondition->getOperand(ExitValueNum))) {
1376     if (!isa<PHINode>(EVN))
1377       if (InsertPt->getParent() == EVN->getParent()) {
1378         BasicBlock::iterator LHBI = L->getHeader()->begin();
1379         BasicBlock::iterator LHBE = L->getHeader()->end();  
1380         for(;LHBI != LHBE; ++LHBI) {
1381           Instruction *I = LHBI;
1382           if (I == EVN) 
1383             break;
1384         }
1385         InsertPt = ++LHBI;
1386       }
1387   }
1388   Value *C1 = new ICmpInst(Sign ?
1389                            ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1390                            AEV,
1391                            ExitCondition->getOperand(ExitValueNum), 
1392                            "lsplit.ev", InsertPt);
1393
1394   SD.A_ExitValue = SelectInst::Create(C1, AEV,
1395                                       ExitCondition->getOperand(ExitValueNum), 
1396                                       "lsplit.ev", InsertPt);
1397
1398   Value *C2 = new ICmpInst(Sign ?
1399                            ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1400                            BSV, StartValue, "lsplit.sv",
1401                            PHTerminator);
1402   SD.B_StartValue = SelectInst::Create(C2, StartValue, BSV,
1403                                        "lsplit.sv", PHTerminator);
1404 }
1405
1406 /// splitLoop - Split current loop L in two loops using split information
1407 /// SD. Update dominator information. Maintain LCSSA form.
1408 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
1409
1410   if (!safeSplitCondition(SD))
1411     return false;
1412
1413   BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
1414   
1415   // Unable to handle triangle loops at the moment.
1416   // In triangle loop, split condition is in header and one of the
1417   // the split destination is loop latch. If split condition is EQ
1418   // then such loops are already handle in processOneIterationLoop().
1419   BasicBlock *Latch = L->getLoopLatch();
1420   BranchInst *SplitTerminator = 
1421     cast<BranchInst>(SplitCondBlock->getTerminator());
1422   BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1423   BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1424   if (L->getHeader() == SplitCondBlock 
1425       && (Latch == Succ0 || Latch == Succ1))
1426     return false;
1427
1428   // If split condition branches heads do not have single predecessor, 
1429   // SplitCondBlock, then is not possible to remove inactive branch.
1430   if (!Succ0->getSinglePredecessor() || !Succ1->getSinglePredecessor())
1431     return false;
1432
1433   // If Exiting block includes loop variant instructions then this
1434   // loop may not be split safely.
1435   if (!safeExitingBlock(SD, ExitCondition->getParent())) 
1436     return false;
1437
1438   // After loop is cloned there are two loops.
1439   //
1440   // First loop, referred as ALoop, executes first part of loop's iteration
1441   // space split.  Second loop, referred as BLoop, executes remaining
1442   // part of loop's iteration space. 
1443   //
1444   // ALoop's exit edge enters BLoop's header through a forwarding block which 
1445   // acts as a BLoop's preheader.
1446   BasicBlock *Preheader = L->getLoopPreheader();
1447
1448   // Calculate ALoop induction variable's new exiting value and
1449   // BLoop induction variable's new starting value.
1450   calculateLoopBounds(SD);
1451
1452   //[*] Clone loop.
1453   DenseMap<const Value *, Value *> ValueMap;
1454   Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
1455   Loop *ALoop = L;
1456   BasicBlock *B_Header = BLoop->getHeader();
1457
1458   //[*] ALoop's exiting edge BLoop's header.
1459   //    ALoop's original exit block becomes BLoop's exit block.
1460   PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1461   BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1462   BranchInst *A_ExitInsn =
1463     dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1464   assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1465   BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1466   if (L->contains(B_ExitBlock)) {
1467     B_ExitBlock = A_ExitInsn->getSuccessor(0);
1468     A_ExitInsn->setSuccessor(0, B_Header);
1469   } else
1470     A_ExitInsn->setSuccessor(1, B_Header);
1471
1472   //[*] Update ALoop's exit value using new exit value.
1473   ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
1474   
1475   // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1476   //     original loop's preheader. Add incoming PHINode values from
1477   //     ALoop's exiting block. Update BLoop header's domiantor info.
1478
1479   // Collect inverse map of Header PHINodes.
1480   DenseMap<Value *, Value *> InverseMap;
1481   for (BasicBlock::iterator BI = L->getHeader()->begin(), 
1482          BE = L->getHeader()->end(); BI != BE; ++BI) {
1483     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1484       PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1485       InverseMap[PNClone] = PN;
1486     } else
1487       break;
1488   }
1489
1490   for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1491        BI != BE; ++BI) {
1492     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1493       // Remove incoming value from original preheader.
1494       PN->removeIncomingValue(Preheader);
1495
1496       // Add incoming value from A_ExitingBlock.
1497       if (PN == B_IndVar)
1498         PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
1499       else { 
1500         PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
1501         Value *V2 = NULL;
1502         // If loop header is also loop exiting block then
1503         // OrigPN is incoming value for B loop header.
1504         if (A_ExitingBlock == L->getHeader())
1505           V2 = OrigPN;
1506         else
1507           V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1508         PN->addIncoming(V2, A_ExitingBlock);
1509       }
1510     } else
1511       break;
1512   }
1513   DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1514   DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
1515   
1516   // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1517   //     block. Remove incoming PHINode values from ALoop's exiting block.
1518   //     Add new incoming values from BLoop's incoming exiting value.
1519   //     Update BLoop exit block's dominator info..
1520   BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1521   for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
1522        BI != BE; ++BI) {
1523     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1524       PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)], 
1525                                                             B_ExitingBlock);
1526       PN->removeIncomingValue(A_ExitingBlock);
1527     } else
1528       break;
1529   }
1530
1531   DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1532   DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
1533
1534   //[*] Split ALoop's exit edge. This creates a new block which
1535   //    serves two purposes. First one is to hold PHINode defnitions
1536   //    to ensure that ALoop's LCSSA form. Second use it to act
1537   //    as a preheader for BLoop.
1538   BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
1539
1540   //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1541   //    in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1542   for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1543       BI != BE; ++BI) {
1544     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1545       Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
1546       PHINode *newPHI = PHINode::Create(PN->getType(), PN->getName());
1547       newPHI->addIncoming(V1, A_ExitingBlock);
1548       A_ExitBlock->getInstList().push_front(newPHI);
1549       PN->removeIncomingValue(A_ExitBlock);
1550       PN->addIncoming(newPHI, A_ExitBlock);
1551     } else
1552       break;
1553   }
1554
1555   //[*] Eliminate split condition's inactive branch from ALoop.
1556   BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1557   BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
1558   BasicBlock *A_InactiveBranch = NULL;
1559   BasicBlock *A_ActiveBranch = NULL;
1560   if (SD.UseTrueBranchFirst) {
1561     A_ActiveBranch = A_BR->getSuccessor(0);
1562     A_InactiveBranch = A_BR->getSuccessor(1);
1563   } else {
1564     A_ActiveBranch = A_BR->getSuccessor(1);
1565     A_InactiveBranch = A_BR->getSuccessor(0);
1566   }
1567   A_BR->setUnconditionalDest(A_ActiveBranch);
1568   removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1569
1570   //[*] Eliminate split condition's inactive branch in from BLoop.
1571   BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1572   BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
1573   BasicBlock *B_InactiveBranch = NULL;
1574   BasicBlock *B_ActiveBranch = NULL;
1575   if (SD.UseTrueBranchFirst) {
1576     B_ActiveBranch = B_BR->getSuccessor(1);
1577     B_InactiveBranch = B_BR->getSuccessor(0);
1578   } else {
1579     B_ActiveBranch = B_BR->getSuccessor(0);
1580     B_InactiveBranch = B_BR->getSuccessor(1);
1581   }
1582   B_BR->setUnconditionalDest(B_ActiveBranch);
1583   removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1584
1585   BasicBlock *A_Header = L->getHeader();
1586   if (A_ExitingBlock == A_Header)
1587     return true;
1588
1589   //[*] Move exit condition into split condition block to avoid
1590   //    executing dead loop iteration.
1591   ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1592   Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
1593   ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
1594
1595   moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
1596                     cast<ICmpInst>(SD.SplitCondition), IndVar, IndVarIncrement, 
1597                     ALoop);
1598
1599   moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
1600                     B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
1601
1602   return true;
1603 }
1604
1605 // moveExitCondition - Move exit condition EC into split condition block CondBB.
1606 void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
1607                                        BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
1608                                        PHINode *IV, Instruction *IVAdd, Loop *LP) {
1609
1610   BasicBlock *ExitingBB = EC->getParent();
1611   Instruction *CurrentBR = CondBB->getTerminator();
1612
1613   // Move exit condition into split condition block.
1614   EC->moveBefore(CurrentBR);
1615   EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
1616
1617   // Move exiting block's branch into split condition block. Update its branch
1618   // destination.
1619   BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
1620   ExitingBR->moveBefore(CurrentBR);
1621   BasicBlock *OrigDestBB = NULL;
1622   if (ExitingBR->getSuccessor(0) == ExitBB) {
1623     OrigDestBB = ExitingBR->getSuccessor(1);
1624     ExitingBR->setSuccessor(1, ActiveBB);
1625   }
1626   else {
1627     OrigDestBB = ExitingBR->getSuccessor(0);
1628     ExitingBR->setSuccessor(0, ActiveBB);
1629   }
1630     
1631   // Remove split condition and current split condition branch.
1632   SC->eraseFromParent();
1633   CurrentBR->eraseFromParent();
1634
1635   // Connect exiting block to original destination.
1636   BranchInst::Create(OrigDestBB, ExitingBB);
1637
1638   // Update PHINodes
1639   updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd, LP);
1640
1641   // Fix dominator info.
1642   // ExitBB is now dominated by CondBB
1643   DT->changeImmediateDominator(ExitBB, CondBB);
1644   DF->changeImmediateDominator(ExitBB, CondBB, DT);
1645   
1646   // Basicblocks dominated by ActiveBB may have ExitingBB or
1647   // a basic block outside the loop in their DF list. If so,
1648   // replace it with CondBB.
1649   DomTreeNode *Node = DT->getNode(ActiveBB);
1650   for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
1651        DI != DE; ++DI) {
1652     BasicBlock *BB = DI->getBlock();
1653     DominanceFrontier::iterator BBDF = DF->find(BB);
1654     DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1655     DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1656     while (DomSetI != DomSetE) {
1657       DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1658       ++DomSetI;
1659       BasicBlock *DFBB = *CurrentItr;
1660       if (DFBB == ExitingBB || !L->contains(DFBB)) {
1661         BBDF->second.erase(DFBB);
1662         BBDF->second.insert(CondBB);
1663       }
1664     }
1665   }
1666 }
1667
1668 /// updatePHINodes - CFG has been changed. 
1669 /// Before 
1670 ///   - ExitBB's single predecessor was Latch
1671 ///   - Latch's second successor was Header
1672 /// Now
1673 ///   - ExitBB's single predecessor is Header
1674 ///   - Latch's one and only successor is Header
1675 ///
1676 /// Update ExitBB PHINodes' to reflect this change.
1677 void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch, 
1678                                     BasicBlock *Header,
1679                                     PHINode *IV, Instruction *IVIncrement,
1680                                     Loop *LP) {
1681
1682   for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end(); 
1683        BI != BE; ) {
1684     PHINode *PN = dyn_cast<PHINode>(BI);
1685     ++BI;
1686     if (!PN)
1687       break;
1688
1689     Value *V = PN->getIncomingValueForBlock(Latch);
1690     if (PHINode *PHV = dyn_cast<PHINode>(V)) {
1691       // PHV is in Latch. PHV has one use is in ExitBB PHINode. And one use
1692       // in Header which is new incoming value for PN.
1693       Value *NewV = NULL;
1694       for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end(); 
1695            UI != E; ++UI) 
1696         if (PHINode *U = dyn_cast<PHINode>(*UI)) 
1697           if (LP->contains(U->getParent())) {
1698             NewV = U;
1699             break;
1700           }
1701
1702       // Add incoming value from header only if PN has any use inside the loop.
1703       if (NewV)
1704         PN->addIncoming(NewV, Header);
1705
1706     } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
1707       // If this instruction is IVIncrement then IV is new incoming value 
1708       // from header otherwise this instruction must be incoming value from 
1709       // header because loop is in LCSSA form.
1710       if (PHI == IVIncrement)
1711         PN->addIncoming(IV, Header);
1712       else
1713         PN->addIncoming(V, Header);
1714     } else
1715       // Otherwise this is an incoming value from header because loop is in 
1716       // LCSSA form.
1717       PN->addIncoming(V, Header);
1718     
1719     // Remove incoming value from Latch.
1720     PN->removeIncomingValue(Latch);
1721   }
1722 }