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