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