Move exit condition and exit branch from exiting block into loop header and dominator...
[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 compare instruction compares IndVar against SplitValue.
68       ICmpInst *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     /// Find condition inside a loop that is suitable candidate for index split.
93     void findSplitCondition();
94
95     /// Find loop's exit condition.
96     void findLoopConditionals();
97
98     /// Return induction variable associated with value V.
99     void findIndVar(Value *V, Loop *L);
100
101     /// processOneIterationLoop - Current loop L contains compare instruction
102     /// that compares induction variable, IndVar, agains loop invariant. If
103     /// entire (i.e. meaningful) loop body is dominated by this compare
104     /// instruction then loop body is executed only for one iteration. In
105     /// such case eliminate loop structure surrounding this loop body. For
106     bool processOneIterationLoop(SplitInfo &SD);
107     
108     /// If loop header includes loop variant instruction operands then
109     /// this loop may not be eliminated.
110     bool safeHeader(SplitInfo &SD,  BasicBlock *BB);
111
112     /// If Exiting block includes loop variant instructions then this
113     /// loop may not be eliminated.
114     bool safeExitingBlock(SplitInfo &SD, BasicBlock *BB);
115
116     /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
117     /// This routine is used to remove split condition's dead branch, dominated by
118     /// DeadBB. LiveBB dominates split conidition's other branch.
119     void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
120
121     /// safeSplitCondition - Return true if it is possible to
122     /// split loop using given split condition.
123     bool safeSplitCondition(SplitInfo &SD);
124
125     /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
126     /// based on split value. 
127     void calculateLoopBounds(SplitInfo &SD);
128
129     /// updatePHINodes - CFG has been changed. 
130     /// Before 
131     ///   - ExitBB's single predecessor was Latch
132     ///   - Latch's second successor was Header
133     /// Now
134     ///   - ExitBB's single predecessor was Header
135     ///   - Latch's one and only successor was Header
136     ///
137     /// Update ExitBB PHINodes' to reflect this change.
138     void updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch, 
139                         BasicBlock *Header,
140                         PHINode *IV, Instruction *IVIncrement);
141
142     /// moveExitCondition - Move exit condition EC into split condition block CondBB.
143     void moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
144                            BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
145                            PHINode *IV, Instruction *IVAdd, Loop *LP);
146
147     /// splitLoop - Split current loop L in two loops using split information
148     /// SD. Update dominator information. Maintain LCSSA form.
149     bool splitLoop(SplitInfo &SD);
150
151     void initialize() {
152       IndVar = NULL; 
153       IndVarIncrement = NULL;
154       ExitCondition = NULL;
155       StartValue = NULL;
156       ExitValueNum = 0;
157       SplitData.clear();
158     }
159
160   private:
161
162     // Current Loop.
163     Loop *L;
164     LPPassManager *LPM;
165     LoopInfo *LI;
166     ScalarEvolution *SE;
167     DominatorTree *DT;
168     DominanceFrontier *DF;
169     SmallVector<SplitInfo, 4> SplitData;
170
171     // Induction variable whose range is being split by this transformation.
172     PHINode *IndVar;
173     Instruction *IndVarIncrement;
174       
175     // Loop exit condition.
176     ICmpInst *ExitCondition;
177
178     // Induction variable's initial value.
179     Value *StartValue;
180
181     // Induction variable's final loop exit value operand number in exit condition..
182     unsigned ExitValueNum;
183   };
184
185   char LoopIndexSplit::ID = 0;
186   RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
187 }
188
189 LoopPass *llvm::createLoopIndexSplitPass() {
190   return new LoopIndexSplit();
191 }
192
193 // Index split Loop L. Return true if loop is split.
194 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
195   bool Changed = false;
196   L = IncomingLoop;
197   LPM = &LPM_Ref;
198
199   // FIXME - Nested loops make dominator info updates tricky. 
200   if (!L->getSubLoops().empty())
201     return false;
202
203   SE = &getAnalysis<ScalarEvolution>();
204   DT = &getAnalysis<DominatorTree>();
205   LI = &getAnalysis<LoopInfo>();
206   DF = &getAnalysis<DominanceFrontier>();
207
208   initialize();
209
210   findLoopConditionals();
211
212   if (!ExitCondition)
213     return false;
214
215   findSplitCondition();
216
217   if (SplitData.empty())
218     return false;
219
220   // First see if it is possible to eliminate loop itself or not.
221   for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
222          E = SplitData.end(); SI != E;) {
223     SplitInfo &SD = *SI;
224     if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
225       Changed = processOneIterationLoop(SD);
226       if (Changed) {
227         ++NumIndexSplit;
228         // If is loop is eliminated then nothing else to do here.
229         return Changed;
230       } else {
231         SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
232         ++SI;
233         SplitData.erase(Delete_SI);
234       }
235     } else
236       ++SI;
237   }
238
239   if (SplitData.empty())
240     return false;
241
242   // Split most profitiable condition.
243   // FIXME : Implement cost analysis.
244   unsigned MostProfitableSDIndex = 0;
245   Changed = splitLoop(SplitData[MostProfitableSDIndex]);
246
247   if (Changed)
248     ++NumIndexSplit;
249   
250   return Changed;
251 }
252
253 /// Return true if V is a induction variable or induction variable's
254 /// increment for loop L.
255 void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
256   
257   Instruction *I = dyn_cast<Instruction>(V);
258   if (!I)
259     return;
260
261   // Check if I is a phi node from loop header or not.
262   if (PHINode *PN = dyn_cast<PHINode>(V)) {
263     if (PN->getParent() == L->getHeader()) {
264       IndVar = PN;
265       return;
266     }
267   }
268  
269   // Check if I is a add instruction whose one operand is
270   // phi node from loop header and second operand is constant.
271   if (I->getOpcode() != Instruction::Add)
272     return;
273   
274   Value *Op0 = I->getOperand(0);
275   Value *Op1 = I->getOperand(1);
276   
277   if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
278     if (PN->getParent() == L->getHeader()
279         && isa<ConstantInt>(Op1)) {
280       IndVar = PN;
281       IndVarIncrement = I;
282       return;
283     }
284   }
285   
286   if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
287     if (PN->getParent() == L->getHeader()
288         && isa<ConstantInt>(Op0)) {
289       IndVar = PN;
290       IndVarIncrement = I;
291       return;
292     }
293   }
294   
295   return;
296 }
297
298 // Find loop's exit condition and associated induction variable.
299 void LoopIndexSplit::findLoopConditionals() {
300
301   BasicBlock *ExitingBlock = NULL;
302
303   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
304        I != E; ++I) {
305     BasicBlock *BB = *I;
306     if (!L->isLoopExit(BB))
307       continue;
308     if (ExitingBlock)
309       return;
310     ExitingBlock = BB;
311   }
312
313   if (!ExitingBlock)
314     return;
315
316   // If exiting block is neither loop header nor loop latch then this loop is
317   // not suitable. 
318   if (ExitingBlock != L->getHeader() && ExitingBlock != L->getLoopLatch())
319     return;
320
321   // If exit block's terminator is conditional branch inst then we have found
322   // exit condition.
323   BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
324   if (!BR || BR->isUnconditional())
325     return;
326   
327   ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
328   if (!CI)
329     return;
330
331   // FIXME 
332   if (CI->getPredicate() == ICmpInst::ICMP_SGT
333       || CI->getPredicate() == ICmpInst::ICMP_UGT
334       || CI->getPredicate() == ICmpInst::ICMP_SGE
335       || CI->getPredicate() == ICmpInst::ICMP_UGE)
336     return;
337
338   ExitCondition = CI;
339
340   // Exit condition's one operand is loop invariant exit value and second 
341   // operand is SCEVAddRecExpr based on induction variable.
342   Value *V0 = CI->getOperand(0);
343   Value *V1 = CI->getOperand(1);
344   
345   SCEVHandle SH0 = SE->getSCEV(V0);
346   SCEVHandle SH1 = SE->getSCEV(V1);
347   
348   if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
349     ExitValueNum = 0;
350     findIndVar(V1, L);
351   }
352   else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
353     ExitValueNum =  1;
354     findIndVar(V0, L);
355   }
356
357   if (!IndVar) 
358     ExitCondition = NULL;
359   else if (IndVar) {
360     BasicBlock *Preheader = L->getLoopPreheader();
361     StartValue = IndVar->getIncomingValueForBlock(Preheader);
362   }
363 }
364
365 /// Find condition inside a loop that is suitable candidate for index split.
366 void LoopIndexSplit::findSplitCondition() {
367
368   SplitInfo SD;
369   // Check all basic block's terminators.
370
371   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
372        I != E; ++I) {
373     BasicBlock *BB = *I;
374
375     // If this basic block does not terminate in a conditional branch
376     // then terminator is not a suitable split condition.
377     BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
378     if (!BR)
379       continue;
380     
381     if (BR->isUnconditional())
382       continue;
383
384     ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
385     if (!CI || CI == ExitCondition)
386       return;
387
388     if (CI->getPredicate() == ICmpInst::ICMP_NE)
389       return;
390
391     // If split condition predicate is GT or GE then first execute
392     // false branch of split condition.
393     if (CI->getPredicate() != ICmpInst::ICMP_ULT
394         && CI->getPredicate() != ICmpInst::ICMP_SLT
395         && CI->getPredicate() != ICmpInst::ICMP_ULE
396         && CI->getPredicate() != ICmpInst::ICMP_SLE)
397       SD.UseTrueBranchFirst = false;
398
399     // If one operand is loop invariant and second operand is SCEVAddRecExpr
400     // based on induction variable then CI is a candidate split condition.
401     Value *V0 = CI->getOperand(0);
402     Value *V1 = CI->getOperand(1);
403
404     SCEVHandle SH0 = SE->getSCEV(V0);
405     SCEVHandle SH1 = SE->getSCEV(V1);
406
407     if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
408       SD.SplitValue = V0;
409       SD.SplitCondition = CI;
410       if (PHINode *PN = dyn_cast<PHINode>(V1)) {
411         if (PN == IndVar)
412           SplitData.push_back(SD);
413       }
414       else  if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
415         if (IndVarIncrement && IndVarIncrement == Insn)
416           SplitData.push_back(SD);
417       }
418     }
419     else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
420       SD.SplitValue =  V1;
421       SD.SplitCondition = CI;
422       if (PHINode *PN = dyn_cast<PHINode>(V0)) {
423         if (PN == IndVar)
424           SplitData.push_back(SD);
425       }
426       else  if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
427         if (IndVarIncrement && IndVarIncrement == Insn)
428           SplitData.push_back(SD);
429       }
430     }
431   }
432 }
433
434 /// processOneIterationLoop - Current loop L contains compare instruction
435 /// that compares induction variable, IndVar, against loop invariant. If
436 /// entire (i.e. meaningful) loop body is dominated by this compare
437 /// instruction then loop body is executed only once. In such case eliminate 
438 /// loop structure surrounding this loop body. For example,
439 ///     for (int i = start; i < end; ++i) {
440 ///         if ( i == somevalue) {
441 ///           loop_body
442 ///         }
443 ///     }
444 /// can be transformed into
445 ///     if (somevalue >= start && somevalue < end) {
446 ///        i = somevalue;
447 ///        loop_body
448 ///     }
449 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
450
451   BasicBlock *Header = L->getHeader();
452
453   // First of all, check if SplitCondition dominates entire loop body
454   // or not.
455   
456   // If SplitCondition is not in loop header then this loop is not suitable
457   // for this transformation.
458   if (SD.SplitCondition->getParent() != Header)
459     return false;
460   
461   // If loop header includes loop variant instruction operands then
462   // this loop may not be eliminated.
463   if (!safeHeader(SD, Header)) 
464     return false;
465
466   // If Exiting block includes loop variant instructions then this
467   // loop may not be eliminated.
468   if (!safeExitingBlock(SD, ExitCondition->getParent())) 
469     return false;
470
471   // Update CFG.
472
473   // Replace index variable with split value in loop body. Loop body is executed
474   // only when index variable is equal to split value.
475   IndVar->replaceAllUsesWith(SD.SplitValue);
476
477   // Remove Latch to Header edge.
478   BasicBlock *Latch = L->getLoopLatch();
479   BasicBlock *LatchSucc = NULL;
480   BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
481   if (!BR)
482     return false;
483   Header->removePredecessor(Latch);
484   for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
485        SI != E; ++SI) {
486     if (Header != *SI)
487       LatchSucc = *SI;
488   }
489   BR->setUnconditionalDest(LatchSucc);
490
491   Instruction *Terminator = Header->getTerminator();
492   Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
493
494   // Replace split condition in header.
495   // Transform 
496   //      SplitCondition : icmp eq i32 IndVar, SplitValue
497   // into
498   //      c1 = icmp uge i32 SplitValue, StartValue
499   //      c2 = icmp ult i32 vSplitValue, ExitValue
500   //      and i32 c1, c2 
501   bool SignedPredicate = ExitCondition->isSignedPredicate();
502   Instruction *C1 = new ICmpInst(SignedPredicate ? 
503                                  ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
504                                  SD.SplitValue, StartValue, "lisplit", 
505                                  Terminator);
506   Instruction *C2 = new ICmpInst(SignedPredicate ? 
507                                  ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
508                                  SD.SplitValue, ExitValue, "lisplit", 
509                                  Terminator);
510   Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit", 
511                                                       Terminator);
512   SD.SplitCondition->replaceAllUsesWith(NSplitCond);
513   SD.SplitCondition->eraseFromParent();
514
515   // Now, clear latch block. Remove instructions that are responsible
516   // to increment induction variable. 
517   Instruction *LTerminator = Latch->getTerminator();
518   for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
519        LB != LE; ) {
520     Instruction *I = LB;
521     ++LB;
522     if (isa<PHINode>(I) || I == LTerminator)
523       continue;
524
525     if (I == IndVarIncrement) 
526       I->replaceAllUsesWith(ExitValue);
527     else
528       I->replaceAllUsesWith(UndefValue::get(I->getType()));
529     I->eraseFromParent();
530   }
531
532   LPM->deleteLoopFromQueue(L);
533
534   // Update Dominator Info.
535   // Only CFG change done is to remove Latch to Header edge. This
536   // does not change dominator tree because Latch did not dominate
537   // Header.
538   if (DF) {
539     DominanceFrontier::iterator HeaderDF = DF->find(Header);
540     if (HeaderDF != DF->end()) 
541       DF->removeFromFrontier(HeaderDF, Header);
542
543     DominanceFrontier::iterator LatchDF = DF->find(Latch);
544     if (LatchDF != DF->end()) 
545       DF->removeFromFrontier(LatchDF, Header);
546   }
547   return true;
548 }
549
550 // If loop header includes loop variant instruction operands then
551 // this loop can not be eliminated. This is used by processOneIterationLoop().
552 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
553
554   Instruction *Terminator = Header->getTerminator();
555   for(BasicBlock::iterator BI = Header->begin(), BE = Header->end(); 
556       BI != BE; ++BI) {
557     Instruction *I = BI;
558
559     // PHI Nodes are OK.
560     if (isa<PHINode>(I))
561       continue;
562
563     // SplitCondition itself is OK.
564     if (I == SD.SplitCondition)
565       continue;
566
567     // Induction variable is OK.
568     if (I == IndVar)
569       continue;
570
571     // Induction variable increment is OK.
572     if (I == IndVarIncrement)
573       continue;
574
575     // Terminator is also harmless.
576     if (I == Terminator)
577       continue;
578
579     // Otherwise we have a instruction that may not be safe.
580     return false;
581   }
582   
583   return true;
584 }
585
586 // If Exiting block includes loop variant instructions then this
587 // loop may not be eliminated. This is used by processOneIterationLoop().
588 bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD, 
589                                        BasicBlock *ExitingBlock) {
590
591   for (BasicBlock::iterator BI = ExitingBlock->begin(), 
592          BE = ExitingBlock->end(); BI != BE; ++BI) {
593     Instruction *I = BI;
594
595     // PHI Nodes are OK.
596     if (isa<PHINode>(I))
597       continue;
598
599     // Induction variable increment is OK.
600     if (IndVarIncrement && IndVarIncrement == I)
601       continue;
602
603     // Check if I is induction variable increment instruction.
604     if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
605
606       Value *Op0 = I->getOperand(0);
607       Value *Op1 = I->getOperand(1);
608       PHINode *PN = NULL;
609       ConstantInt *CI = NULL;
610
611       if ((PN = dyn_cast<PHINode>(Op0))) {
612         if ((CI = dyn_cast<ConstantInt>(Op1)))
613           IndVarIncrement = I;
614       } else 
615         if ((PN = dyn_cast<PHINode>(Op1))) {
616           if ((CI = dyn_cast<ConstantInt>(Op0)))
617             IndVarIncrement = I;
618       }
619           
620       if (IndVarIncrement && PN == IndVar && CI->isOne())
621         continue;
622     }
623
624     // I is an Exit condition if next instruction is block terminator.
625     // Exit condition is OK if it compares loop invariant exit value,
626     // which is checked below.
627     else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
628       if (EC == ExitCondition)
629         continue;
630     }
631
632     if (I == ExitingBlock->getTerminator())
633       continue;
634
635     // Otherwise we have instruction that may not be safe.
636     return false;
637   }
638
639   // We could not find any reason to consider ExitingBlock unsafe.
640   return true;
641 }
642
643 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
644 /// This routine is used to remove split condition's dead branch, dominated by
645 /// DeadBB. LiveBB dominates split conidition's other branch.
646 void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP, 
647                                   BasicBlock *LiveBB) {
648
649   // First update DeadBB's dominance frontier. 
650   SmallVector<BasicBlock *, 8> FrontierBBs;
651   DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
652   if (DeadBBDF != DF->end()) {
653     SmallVector<BasicBlock *, 8> PredBlocks;
654     
655     DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
656     for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
657            DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
658       BasicBlock *FrontierBB = *DeadBBSetI;
659       FrontierBBs.push_back(FrontierBB);
660
661       // Rremove any PHI incoming edge from blocks dominated by DeadBB.
662       PredBlocks.clear();
663       for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
664           PI != PE; ++PI) {
665         BasicBlock *P = *PI;
666         if (P == DeadBB || DT->dominates(DeadBB, P))
667           PredBlocks.push_back(P);
668       }
669
670       for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
671           FBI != FBE; ++FBI) {
672         if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
673           for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
674                 PE = PredBlocks.end(); PI != PE; ++PI) {
675             BasicBlock *P = *PI;
676             PN->removeIncomingValue(P);
677           }
678         }
679         else
680           break;
681       }      
682     }
683   }
684   
685   // Now remove DeadBB and all nodes dominated by DeadBB in df order.
686   SmallVector<BasicBlock *, 32> WorkList;
687   DomTreeNode *DN = DT->getNode(DeadBB);
688   for (df_iterator<DomTreeNode*> DI = df_begin(DN),
689          E = df_end(DN); DI != E; ++DI) {
690     BasicBlock *BB = DI->getBlock();
691     WorkList.push_back(BB);
692     BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
693   }
694
695   while (!WorkList.empty()) {
696     BasicBlock *BB = WorkList.back(); WorkList.pop_back();
697     for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end(); 
698         BBI != BBE; ++BBI) {
699       Instruction *I = BBI;
700       I->replaceAllUsesWith(UndefValue::get(I->getType()));
701       I->eraseFromParent();
702     }
703     LPM->deleteSimpleAnalysisValue(BB, LP);
704     DT->eraseNode(BB);
705     DF->removeBlock(BB);
706     LI->removeBlock(BB);
707     BB->eraseFromParent();
708   }
709
710   // Update Frontier BBs' dominator info.
711   while (!FrontierBBs.empty()) {
712     BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
713     BasicBlock *NewDominator = FBB->getSinglePredecessor();
714     if (!NewDominator) {
715       pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
716       NewDominator = *PI;
717       ++PI;
718       if (NewDominator != LiveBB) {
719         for(; PI != PE; ++PI) {
720           BasicBlock *P = *PI;
721           if (P == LiveBB) {
722             NewDominator = LiveBB;
723             break;
724           }
725           NewDominator = DT->findNearestCommonDominator(NewDominator, P);
726         }
727       }
728     }
729     assert (NewDominator && "Unable to fix dominator info.");
730     DT->changeImmediateDominator(FBB, NewDominator);
731     DF->changeImmediateDominator(FBB, NewDominator, DT);
732   }
733
734 }
735
736 /// safeSplitCondition - Return true if it is possible to
737 /// split loop using given split condition.
738 bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
739
740   BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
741   
742   // Unable to handle triange loops at the moment.
743   // In triangle loop, split condition is in header and one of the
744   // the split destination is loop latch. If split condition is EQ
745   // then such loops are already handle in processOneIterationLoop().
746   BasicBlock *Latch = L->getLoopLatch();
747   BranchInst *SplitTerminator = 
748     cast<BranchInst>(SplitCondBlock->getTerminator());
749   BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
750   BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
751   if (L->getHeader() == SplitCondBlock 
752       && (Latch == Succ0 || Latch == Succ1))
753     return false;
754   
755   // If one of the split condition branch is post dominating other then loop 
756   // index split is not appropriate.
757   if (DT->dominates(Succ0, Latch) || DT->dominates(Succ1, Latch))
758     return false;
759   
760   // If one of the split condition branch is a predecessor of the other
761   // split condition branch head then do not split loop on this condition.
762   for(pred_iterator PI = pred_begin(Succ0), PE = pred_end(Succ0); 
763       PI != PE; ++PI)
764     if (Succ1 == *PI)
765       return false;
766   for(pred_iterator PI = pred_begin(Succ1), PE = pred_end(Succ1); 
767       PI != PE; ++PI)
768     if (Succ0 == *PI)
769       return false;
770
771   // Finally this split condition is safe only if merge point for
772   // split condition branch is loop latch. This check along with previous
773   // check, to ensure that exit condition is in either loop latch or header,
774   // filters all loops with non-empty loop body between merge point
775   // and exit condition.
776   DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
777   assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
778   if (Succ0DF->second.count(Latch))
779     return true;
780
781   DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
782   assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
783   if (Succ1DF->second.count(Latch))
784     return true;
785   
786   return false;
787 }
788
789 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
790 /// based on split value. 
791 void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
792
793   ICmpInst::Predicate SP = SD.SplitCondition->getPredicate();
794   const Type *Ty = SD.SplitValue->getType();
795   bool Sign = ExitCondition->isSignedPredicate();
796   BasicBlock *Preheader = L->getLoopPreheader();
797   Instruction *PHTerminator = Preheader->getTerminator();
798
799   // Initially use split value as upper loop bound for first loop and lower loop
800   // bound for second loop.
801   Value *AEV = SD.SplitValue;
802   Value *BSV = SD.SplitValue;
803
804   switch (ExitCondition->getPredicate()) {
805   case ICmpInst::ICMP_SGT:
806   case ICmpInst::ICMP_UGT:
807   case ICmpInst::ICMP_SGE:
808   case ICmpInst::ICMP_UGE:
809   default:
810     assert (0 && "Unexpected exit condition predicate");
811
812   case ICmpInst::ICMP_SLT:
813   case ICmpInst::ICMP_ULT:
814     {
815       switch (SP) {
816       case ICmpInst::ICMP_SLT:
817       case ICmpInst::ICMP_ULT:
818         //
819         // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
820         //
821         // is transformed into
822         // AEV = BSV = SV
823         // for (i = LB; i < min(UB, AEV); ++i)
824         //    A;
825         // for (i = max(LB, BSV); i < UB; ++i);
826         //    B;
827         break;
828       case ICmpInst::ICMP_SLE:
829       case ICmpInst::ICMP_ULE:
830         {
831           //
832           // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
833           //
834           // is transformed into
835           //
836           // AEV = SV + 1
837           // BSV = SV + 1
838           // for (i = LB; i < min(UB, AEV); ++i) 
839           //       A;
840           // for (i = max(LB, BSV); i < UB; ++i) 
841           //       B;
842           BSV = BinaryOperator::createAdd(SD.SplitValue,
843                                           ConstantInt::get(Ty, 1, Sign),
844                                           "lsplit.add", PHTerminator);
845           AEV = BSV;
846         }
847         break;
848       case ICmpInst::ICMP_SGE:
849       case ICmpInst::ICMP_UGE: 
850         //
851         // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
852         // 
853         // is transformed into
854         // AEV = BSV = SV
855         // for (i = LB; i < min(UB, AEV); ++i)
856         //    B;
857         // for (i = max(BSV, LB); i < UB; ++i)
858         //    A;
859         break;
860       case ICmpInst::ICMP_SGT:
861       case ICmpInst::ICMP_UGT: 
862         {
863           //
864           // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
865           //
866           // is transformed into
867           //
868           // BSV = AEV = SV + 1
869           // for (i = LB; i < min(UB, AEV); ++i) 
870           //       B;
871           // for (i = max(LB, BSV); i < UB; ++i) 
872           //       A;
873           BSV = BinaryOperator::createAdd(SD.SplitValue,
874                                           ConstantInt::get(Ty, 1, Sign),
875                                           "lsplit.add", PHTerminator);
876           AEV = BSV;
877         }
878         break;
879       default:
880         assert (0 && "Unexpected split condition predicate");
881         break;
882       } // end switch (SP)
883     }
884     break;
885   case ICmpInst::ICMP_SLE:
886   case ICmpInst::ICMP_ULE:
887     {
888       switch (SP) {
889       case ICmpInst::ICMP_SLT:
890       case ICmpInst::ICMP_ULT:
891         //
892         // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
893         //
894         // is transformed into
895         // AEV = SV - 1;
896         // BSV = SV;
897         // for (i = LB; i <= min(UB, AEV); ++i) 
898         //       A;
899         // for (i = max(LB, BSV); i <= UB; ++i) 
900         //       B;
901         AEV = BinaryOperator::createSub(SD.SplitValue,
902                                         ConstantInt::get(Ty, 1, Sign),
903                                         "lsplit.sub", PHTerminator);
904         break;
905       case ICmpInst::ICMP_SLE:
906       case ICmpInst::ICMP_ULE:
907         //
908         // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
909         //
910         // is transformed into
911         // AEV = SV;
912         // BSV = SV + 1;
913         // for (i = LB; i <= min(UB, AEV); ++i) 
914         //       A;
915         // for (i = max(LB, BSV); i <= UB; ++i) 
916         //       B;
917         BSV = BinaryOperator::createAdd(SD.SplitValue,
918                                         ConstantInt::get(Ty, 1, Sign),
919                                         "lsplit.add", PHTerminator);
920         break;
921       case ICmpInst::ICMP_SGT:
922       case ICmpInst::ICMP_UGT: 
923         //
924         // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
925         //
926         // is transformed into
927         // AEV = SV;
928         // BSV = SV + 1;
929         // for (i = LB; i <= min(AEV, UB); ++i)
930         //      B;
931         // for (i = max(LB, BSV); i <= UB; ++i)
932         //      A;
933         BSV = BinaryOperator::createAdd(SD.SplitValue,
934                                         ConstantInt::get(Ty, 1, Sign),
935                                         "lsplit.add", PHTerminator);
936         break;
937       case ICmpInst::ICMP_SGE:
938       case ICmpInst::ICMP_UGE: 
939         // ** TODO **
940         //
941         // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
942         //
943         // is transformed into
944         // AEV = SV - 1;
945         // BSV = SV;
946         // for (i = LB; i <= min(AEV, UB); ++i)
947         //      B;
948         // for (i = max(LB, BSV); i <= UB; ++i)
949         //      A;
950         AEV = BinaryOperator::createSub(SD.SplitValue,
951                                         ConstantInt::get(Ty, 1, Sign),
952                                         "lsplit.sub", PHTerminator);
953         break;
954       default:
955         assert (0 && "Unexpected split condition predicate");
956         break;
957       } // end switch (SP)
958     }
959     break;
960   }
961
962   // Calculate ALoop induction variable's new exiting value and
963   // BLoop induction variable's new starting value. Calculuate these
964   // values in original loop's preheader.
965   //      A_ExitValue = min(SplitValue, OrignalLoopExitValue)
966   //      B_StartValue = max(SplitValue, OriginalLoopStartValue)
967   Value *C1 = new ICmpInst(Sign ?
968                            ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
969                            AEV,
970                            ExitCondition->getOperand(ExitValueNum), 
971                            "lsplit.ev", PHTerminator);
972   SD.A_ExitValue = new SelectInst(C1, AEV,
973                                   ExitCondition->getOperand(ExitValueNum), 
974                                   "lsplit.ev", PHTerminator);
975   
976   Value *C2 = new ICmpInst(Sign ?
977                            ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
978                            BSV, StartValue, "lsplit.sv",
979                            PHTerminator);
980   SD.B_StartValue = new SelectInst(C2, StartValue, BSV,
981                                    "lsplit.sv", PHTerminator);
982 }
983
984 /// splitLoop - Split current loop L in two loops using split information
985 /// SD. Update dominator information. Maintain LCSSA form.
986 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
987
988   if (!safeSplitCondition(SD))
989     return false;
990
991   // After loop is cloned there are two loops.
992   //
993   // First loop, referred as ALoop, executes first part of loop's iteration
994   // space split.  Second loop, referred as BLoop, executes remaining
995   // part of loop's iteration space. 
996   //
997   // ALoop's exit edge enters BLoop's header through a forwarding block which 
998   // acts as a BLoop's preheader.
999   BasicBlock *Preheader = L->getLoopPreheader();
1000
1001   // Calculate ALoop induction variable's new exiting value and
1002   // BLoop induction variable's new starting value.
1003   calculateLoopBounds(SD);
1004
1005   //[*] Clone loop.
1006   DenseMap<const Value *, Value *> ValueMap;
1007   Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
1008   Loop *ALoop = L;
1009   BasicBlock *B_Header = BLoop->getHeader();
1010
1011   //[*] ALoop's exiting edge BLoop's header.
1012   //    ALoop's original exit block becomes BLoop's exit block.
1013   PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1014   BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1015   BranchInst *A_ExitInsn =
1016     dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1017   assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1018   BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1019   if (L->contains(B_ExitBlock)) {
1020     B_ExitBlock = A_ExitInsn->getSuccessor(0);
1021     A_ExitInsn->setSuccessor(0, B_Header);
1022   } else
1023     A_ExitInsn->setSuccessor(1, B_Header);
1024
1025   //[*] Update ALoop's exit value using new exit value.
1026   ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
1027   
1028   // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1029   //     original loop's preheader. Add incoming PHINode values from
1030   //     ALoop's exiting block. Update BLoop header's domiantor info.
1031
1032   // Collect inverse map of Header PHINodes.
1033   DenseMap<Value *, Value *> InverseMap;
1034   for (BasicBlock::iterator BI = L->getHeader()->begin(), 
1035          BE = L->getHeader()->end(); BI != BE; ++BI) {
1036     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1037       PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1038       InverseMap[PNClone] = PN;
1039     } else
1040       break;
1041   }
1042
1043   for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1044        BI != BE; ++BI) {
1045     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1046       // Remove incoming value from original preheader.
1047       PN->removeIncomingValue(Preheader);
1048
1049       // Add incoming value from A_ExitingBlock.
1050       if (PN == B_IndVar)
1051         PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
1052       else { 
1053         PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
1054         Value *V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1055         PN->addIncoming(V2, A_ExitingBlock);
1056       }
1057     } else
1058       break;
1059   }
1060   DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1061   DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
1062   
1063   // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1064   //     block. Remove incoming PHINode values from ALoop's exiting block.
1065   //     Add new incoming values from BLoop's incoming exiting value.
1066   //     Update BLoop exit block's dominator info..
1067   BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1068   for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
1069        BI != BE; ++BI) {
1070     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1071       PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)], 
1072                                                             B_ExitingBlock);
1073       PN->removeIncomingValue(A_ExitingBlock);
1074     } else
1075       break;
1076   }
1077
1078   DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1079   DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
1080
1081   //[*] Split ALoop's exit edge. This creates a new block which
1082   //    serves two purposes. First one is to hold PHINode defnitions
1083   //    to ensure that ALoop's LCSSA form. Second use it to act
1084   //    as a preheader for BLoop.
1085   BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
1086
1087   //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1088   //    in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1089   for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1090       BI != BE; ++BI) {
1091     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1092       Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
1093       PHINode *newPHI = new PHINode(PN->getType(), PN->getName());
1094       newPHI->addIncoming(V1, A_ExitingBlock);
1095       A_ExitBlock->getInstList().push_front(newPHI);
1096       PN->removeIncomingValue(A_ExitBlock);
1097       PN->addIncoming(newPHI, A_ExitBlock);
1098     } else
1099       break;
1100   }
1101
1102   //[*] Eliminate split condition's inactive branch from ALoop.
1103   BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1104   BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
1105   BasicBlock *A_InactiveBranch = NULL;
1106   BasicBlock *A_ActiveBranch = NULL;
1107   if (SD.UseTrueBranchFirst) {
1108     A_ActiveBranch = A_BR->getSuccessor(0);
1109     A_InactiveBranch = A_BR->getSuccessor(1);
1110   } else {
1111     A_ActiveBranch = A_BR->getSuccessor(1);
1112     A_InactiveBranch = A_BR->getSuccessor(0);
1113   }
1114   A_BR->setUnconditionalDest(A_ActiveBranch);
1115   removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1116
1117   //[*] Eliminate split condition's inactive branch in from BLoop.
1118   BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1119   BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
1120   BasicBlock *B_InactiveBranch = NULL;
1121   BasicBlock *B_ActiveBranch = NULL;
1122   if (SD.UseTrueBranchFirst) {
1123     B_ActiveBranch = B_BR->getSuccessor(1);
1124     B_InactiveBranch = B_BR->getSuccessor(0);
1125   } else {
1126     B_ActiveBranch = B_BR->getSuccessor(0);
1127     B_InactiveBranch = B_BR->getSuccessor(1);
1128   }
1129   B_BR->setUnconditionalDest(B_ActiveBranch);
1130   removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1131
1132   BasicBlock *A_Header = L->getHeader();
1133   if (A_ExitingBlock == A_Header)
1134     return true;
1135
1136   //[*] Move exit condition into split condition block to avoid
1137   //    executing dead loop iteration.
1138   ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1139   Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
1140   ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
1141
1142   moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
1143                     SD.SplitCondition, IndVar, IndVarIncrement, ALoop);
1144
1145   moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
1146                     B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
1147
1148   return true;
1149 }
1150
1151 // moveExitCondition - Move exit condition EC into split condition block CondBB.
1152 void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
1153                                        BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
1154                                        PHINode *IV, Instruction *IVAdd, Loop *LP) {
1155
1156   BasicBlock *ExitingBB = EC->getParent();
1157   Instruction *CurrentBR = CondBB->getTerminator();
1158
1159   // Move exit condition into split condition block.
1160   EC->moveBefore(CurrentBR);
1161   EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
1162
1163   // Move exiting block's branch into split condition block. Update its branch
1164   // destination.
1165   BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
1166   ExitingBR->moveBefore(CurrentBR);
1167   if (ExitingBR->getSuccessor(0) == ExitBB)
1168     ExitingBR->setSuccessor(1, ActiveBB);
1169   else
1170     ExitingBR->setSuccessor(0, ActiveBB);
1171     
1172   // Remove split condition and current split condition branch.
1173   SC->eraseFromParent();
1174   CurrentBR->eraseFromParent();
1175
1176   // Connect exiting block to split condition block.
1177   new BranchInst(CondBB, ExitingBB);
1178
1179   // Update PHINodes
1180   updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd);
1181
1182   // Fix dominator info.
1183   // ExitBB is now dominated by CondBB
1184   DT->changeImmediateDominator(ExitBB, CondBB);
1185   DF->changeImmediateDominator(ExitBB, CondBB, DT);
1186   
1187   // Basicblocks dominated by ActiveBB may have ExitingBB or
1188   // a basic block outside the loop in their DF list. If so,
1189   // replace it with CondBB.
1190   DomTreeNode *Node = DT->getNode(ActiveBB);
1191   for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
1192        DI != DE; ++DI) {
1193     BasicBlock *BB = DI->getBlock();
1194     DominanceFrontier::iterator BBDF = DF->find(BB);
1195     DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1196     DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1197     while (DomSetI != DomSetE) {
1198       DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1199       ++DomSetI;
1200       BasicBlock *DFBB = *CurrentItr;
1201       if (DFBB == ExitingBB || !L->contains(DFBB)) {
1202         BBDF->second.erase(DFBB);
1203         BBDF->second.insert(CondBB);
1204       }
1205     }
1206   }
1207 }
1208
1209 /// updatePHINodes - CFG has been changed. 
1210 /// Before 
1211 ///   - ExitBB's single predecessor was Latch
1212 ///   - Latch's second successor was Header
1213 /// Now
1214 ///   - ExitBB's single predecessor was Header
1215 ///   - Latch's one and only successor was Header
1216 ///
1217 /// Update ExitBB PHINodes' to reflect this change.
1218 void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch, 
1219                                     BasicBlock *Header,
1220                                     PHINode *IV, Instruction *IVIncrement) {
1221
1222   for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end(); 
1223        BI != BE; ++BI) {
1224     PHINode *PN = dyn_cast<PHINode>(BI);
1225     if (!PN)
1226       break;
1227
1228     Value *V = PN->getIncomingValueForBlock(Latch);
1229     if (PHINode *PHV = dyn_cast<PHINode>(V)) {
1230       // PHV is in Latch. PHV has two uses, one use is in ExitBB PHINode 
1231       // (i.e. PN :)). 
1232       // The second use is in Header and it is new incoming value for PN.
1233       PHINode *U1 = NULL;
1234       PHINode *U2 = NULL;
1235       Value *NewV = NULL;
1236       for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end(); 
1237            UI != E; ++UI) {
1238         if (!U1)
1239           U1 = cast<PHINode>(*UI);
1240         else if (!U2)
1241           U2 = cast<PHINode>(*UI);
1242         else
1243           assert ( 0 && "Unexpected third use of this PHINode");
1244       }
1245       assert (U1 && U2 && "Unable to find two uses");
1246       
1247       if (U1->getParent() == Header) 
1248         NewV = U1;
1249       else
1250         NewV = U2;
1251       PN->addIncoming(NewV, Header);
1252
1253     } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
1254       // If this instruction is IVIncrement then IV is new incoming value 
1255       // from header otherwise this instruction must be incoming value from 
1256       // header because loop is in LCSSA form.
1257       if (PHI == IVIncrement)
1258         PN->addIncoming(IV, Header);
1259       else
1260         PN->addIncoming(V, Header);
1261     } else
1262       // Otherwise this is an incoming value from header because loop is in 
1263       // LCSSA form.
1264       PN->addIncoming(V, Header);
1265     
1266     // Remove incoming value from Latch.
1267     PN->removeIncomingValue(Latch);
1268   }
1269 }