Dominance frontier is now required.
[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
62       // Induction variable's range is split at this value.
63       Value *SplitValue;
64       
65       // This compare instruction compares IndVar against SplitValue.
66       ICmpInst *SplitCondition;
67
68       // Clear split info.
69       void clear() {
70         SplitValue = NULL;
71         SplitCondition = NULL;
72       }
73
74     };
75     
76   private:
77     /// Find condition inside a loop that is suitable candidate for index split.
78     void findSplitCondition();
79
80     /// Find loop's exit condition.
81     void findLoopConditionals();
82
83     /// Return induction variable associated with value V.
84     void findIndVar(Value *V, Loop *L);
85
86     /// processOneIterationLoop - Current loop L contains compare instruction
87     /// that compares induction variable, IndVar, agains loop invariant. If
88     /// entire (i.e. meaningful) loop body is dominated by this compare
89     /// instruction then loop body is executed only for one iteration. In
90     /// such case eliminate loop structure surrounding this loop body. For
91     bool processOneIterationLoop(SplitInfo &SD);
92     
93     /// If loop header includes loop variant instruction operands then
94     /// this loop may not be eliminated.
95     bool safeHeader(SplitInfo &SD,  BasicBlock *BB);
96
97     /// If Exit block includes loop variant instructions then this
98     /// loop may not be eliminated.
99     bool safeExitBlock(SplitInfo &SD, BasicBlock *BB);
100
101     /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
102     /// This routine is used to remove split condition's dead branch, dominated by
103     /// DeadBB. LiveBB dominates split conidition's other branch.
104     void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
105
106     /// Find cost of spliting loop L.
107     unsigned findSplitCost(Loop *L, SplitInfo &SD);
108     bool splitLoop(SplitInfo &SD);
109
110     void initialize() {
111       IndVar = NULL; 
112       IndVarIncrement = NULL;
113       ExitCondition = NULL;
114       StartValue = NULL;
115       ExitValueNum = 0;
116       SplitData.clear();
117     }
118
119   private:
120
121     // Current Loop.
122     Loop *L;
123     LPPassManager *LPM;
124     LoopInfo *LI;
125     ScalarEvolution *SE;
126     DominatorTree *DT;
127     DominanceFrontier *DF;
128     SmallVector<SplitInfo, 4> SplitData;
129
130     // Induction variable whose range is being split by this transformation.
131     PHINode *IndVar;
132     Instruction *IndVarIncrement;
133       
134     // Loop exit condition.
135     ICmpInst *ExitCondition;
136
137     // Induction variable's initial value.
138     Value *StartValue;
139
140     // Induction variable's final loop exit value operand number in exit condition..
141     unsigned ExitValueNum;
142   };
143
144   char LoopIndexSplit::ID = 0;
145   RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
146 }
147
148 LoopPass *llvm::createLoopIndexSplitPass() {
149   return new LoopIndexSplit();
150 }
151
152 // Index split Loop L. Return true if loop is split.
153 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
154   bool Changed = false;
155   L = IncomingLoop;
156   LPM = &LPM_Ref;
157
158   // FIXME - Nested loops make dominator info updates tricky. 
159   if (!L->getSubLoops().empty())
160     return false;
161
162   SE = &getAnalysis<ScalarEvolution>();
163   DT = &getAnalysis<DominatorTree>();
164   LI = &getAnalysis<LoopInfo>();
165   DF = &getAnalysis<DominanceFrontier>();
166
167   initialize();
168
169   findLoopConditionals();
170
171   if (!ExitCondition)
172     return false;
173
174   findSplitCondition();
175
176   if (SplitData.empty())
177     return false;
178
179   // First see if it is possible to eliminate loop itself or not.
180   for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
181          E = SplitData.end(); SI != E; ++SI) {
182     SplitInfo &SD = *SI;
183     if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
184       Changed = processOneIterationLoop(SD);
185       if (Changed) {
186         ++NumIndexSplit;
187         // If is loop is eliminated then nothing else to do here.
188         return Changed;
189       }
190     }
191   }
192
193   unsigned MaxCost = 99;
194   unsigned Index = 0;
195   unsigned MostProfitableSDIndex = 0;
196   for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
197          E = SplitData.end(); SI != E; ++SI, ++Index) {
198     SplitInfo SD = *SI;
199
200     // ICM_EQs are already handled above.
201     if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ)
202       continue;
203     
204     unsigned Cost = findSplitCost(L, SD);
205     if (Cost < MaxCost)
206       MostProfitableSDIndex = Index;
207   }
208
209   // Split most profitiable condition.
210   Changed = splitLoop(SplitData[MostProfitableSDIndex]);
211
212   if (Changed)
213     ++NumIndexSplit;
214   
215   return Changed;
216 }
217
218 /// Return true if V is a induction variable or induction variable's
219 /// increment for loop L.
220 void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
221   
222   Instruction *I = dyn_cast<Instruction>(V);
223   if (!I)
224     return;
225
226   // Check if I is a phi node from loop header or not.
227   if (PHINode *PN = dyn_cast<PHINode>(V)) {
228     if (PN->getParent() == L->getHeader()) {
229       IndVar = PN;
230       return;
231     }
232   }
233  
234   // Check if I is a add instruction whose one operand is
235   // phi node from loop header and second operand is constant.
236   if (I->getOpcode() != Instruction::Add)
237     return;
238   
239   Value *Op0 = I->getOperand(0);
240   Value *Op1 = I->getOperand(1);
241   
242   if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
243     if (PN->getParent() == L->getHeader()
244         && isa<ConstantInt>(Op1)) {
245       IndVar = PN;
246       IndVarIncrement = I;
247       return;
248     }
249   }
250   
251   if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
252     if (PN->getParent() == L->getHeader()
253         && isa<ConstantInt>(Op0)) {
254       IndVar = PN;
255       IndVarIncrement = I;
256       return;
257     }
258   }
259   
260   return;
261 }
262
263 // Find loop's exit condition and associated induction variable.
264 void LoopIndexSplit::findLoopConditionals() {
265
266   BasicBlock *ExitBlock = NULL;
267
268   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
269        I != E; ++I) {
270     BasicBlock *BB = *I;
271     if (!L->isLoopExit(BB))
272       continue;
273     if (ExitBlock)
274       return;
275     ExitBlock = BB;
276   }
277
278   if (!ExitBlock)
279     return;
280   
281   // If exit block's terminator is conditional branch inst then we have found
282   // exit condition.
283   BranchInst *BR = dyn_cast<BranchInst>(ExitBlock->getTerminator());
284   if (!BR || BR->isUnconditional())
285     return;
286   
287   ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
288   if (!CI)
289     return;
290   
291   ExitCondition = CI;
292
293   // Exit condition's one operand is loop invariant exit value and second 
294   // operand is SCEVAddRecExpr based on induction variable.
295   Value *V0 = CI->getOperand(0);
296   Value *V1 = CI->getOperand(1);
297   
298   SCEVHandle SH0 = SE->getSCEV(V0);
299   SCEVHandle SH1 = SE->getSCEV(V1);
300   
301   if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
302     ExitValueNum = 0;
303     findIndVar(V1, L);
304   }
305   else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
306     ExitValueNum =  1;
307     findIndVar(V0, L);
308   }
309
310   if (!IndVar) 
311     ExitCondition = NULL;
312   else if (IndVar) {
313     BasicBlock *Preheader = L->getLoopPreheader();
314     StartValue = IndVar->getIncomingValueForBlock(Preheader);
315   }
316 }
317
318 /// Find condition inside a loop that is suitable candidate for index split.
319 void LoopIndexSplit::findSplitCondition() {
320
321   SplitInfo SD;
322   // Check all basic block's terminators.
323
324   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
325        I != E; ++I) {
326     BasicBlock *BB = *I;
327
328     // If this basic block does not terminate in a conditional branch
329     // then terminator is not a suitable split condition.
330     BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
331     if (!BR)
332       continue;
333     
334     if (BR->isUnconditional())
335       continue;
336
337     ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
338     if (!CI || CI == ExitCondition)
339       return;
340
341     // If one operand is loop invariant and second operand is SCEVAddRecExpr
342     // based on induction variable then CI is a candidate split condition.
343     Value *V0 = CI->getOperand(0);
344     Value *V1 = CI->getOperand(1);
345
346     SCEVHandle SH0 = SE->getSCEV(V0);
347     SCEVHandle SH1 = SE->getSCEV(V1);
348
349     if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
350       SD.SplitValue = V0;
351       SD.SplitCondition = CI;
352       if (PHINode *PN = dyn_cast<PHINode>(V1)) {
353         if (PN == IndVar)
354           SplitData.push_back(SD);
355       }
356       else  if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
357         if (IndVarIncrement && IndVarIncrement == Insn)
358           SplitData.push_back(SD);
359       }
360     }
361     else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
362       SD.SplitValue =  V1;
363       SD.SplitCondition = CI;
364       if (PHINode *PN = dyn_cast<PHINode>(V0)) {
365         if (PN == IndVar)
366           SplitData.push_back(SD);
367       }
368       else  if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
369         if (IndVarIncrement && IndVarIncrement == Insn)
370           SplitData.push_back(SD);
371       }
372     }
373   }
374 }
375
376 /// processOneIterationLoop - Current loop L contains compare instruction
377 /// that compares induction variable, IndVar, against loop invariant. If
378 /// entire (i.e. meaningful) loop body is dominated by this compare
379 /// instruction then loop body is executed only once. In such case eliminate 
380 /// loop structure surrounding this loop body. For example,
381 ///     for (int i = start; i < end; ++i) {
382 ///         if ( i == somevalue) {
383 ///           loop_body
384 ///         }
385 ///     }
386 /// can be transformed into
387 ///     if (somevalue >= start && somevalue < end) {
388 ///        i = somevalue;
389 ///        loop_body
390 ///     }
391 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
392
393   BasicBlock *Header = L->getHeader();
394
395   // First of all, check if SplitCondition dominates entire loop body
396   // or not.
397   
398   // If SplitCondition is not in loop header then this loop is not suitable
399   // for this transformation.
400   if (SD.SplitCondition->getParent() != Header)
401     return false;
402   
403   // If loop header includes loop variant instruction operands then
404   // this loop may not be eliminated.
405   if (!safeHeader(SD, Header)) 
406     return false;
407
408   // If Exit block includes loop variant instructions then this
409   // loop may not be eliminated.
410   if (!safeExitBlock(SD, ExitCondition->getParent())) 
411     return false;
412
413   // Update CFG.
414
415   // As a first step to break this loop, remove Latch to Header edge.
416   BasicBlock *Latch = L->getLoopLatch();
417   BasicBlock *LatchSucc = NULL;
418   BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
419   if (!BR)
420     return false;
421   Header->removePredecessor(Latch);
422   for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
423        SI != E; ++SI) {
424     if (Header != *SI)
425       LatchSucc = *SI;
426   }
427   BR->setUnconditionalDest(LatchSucc);
428
429   Instruction *Terminator = Header->getTerminator();
430   Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
431
432   // Replace split condition in header.
433   // Transform 
434   //      SplitCondition : icmp eq i32 IndVar, SplitValue
435   // into
436   //      c1 = icmp uge i32 SplitValue, StartValue
437   //      c2 = icmp ult i32 vSplitValue, ExitValue
438   //      and i32 c1, c2 
439   bool SignedPredicate = ExitCondition->isSignedPredicate();
440   Instruction *C1 = new ICmpInst(SignedPredicate ? 
441                                  ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
442                                  SD.SplitValue, StartValue, "lisplit", 
443                                  Terminator);
444   Instruction *C2 = new ICmpInst(SignedPredicate ? 
445                                  ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
446                                  SD.SplitValue, ExitValue, "lisplit", 
447                                  Terminator);
448   Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit", 
449                                                       Terminator);
450   SD.SplitCondition->replaceAllUsesWith(NSplitCond);
451   SD.SplitCondition->eraseFromParent();
452
453   // Now, clear latch block. Remove instructions that are responsible
454   // to increment induction variable. 
455   Instruction *LTerminator = Latch->getTerminator();
456   for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
457        LB != LE; ) {
458     Instruction *I = LB;
459     ++LB;
460     if (isa<PHINode>(I) || I == LTerminator)
461       continue;
462
463     if (I == IndVarIncrement) 
464       I->replaceAllUsesWith(ExitValue);
465     else
466       I->replaceAllUsesWith(UndefValue::get(I->getType()));
467     I->eraseFromParent();
468   }
469
470   LPM->deleteLoopFromQueue(L);
471
472   // Update Dominator Info.
473   // Only CFG change done is to remove Latch to Header edge. This
474   // does not change dominator tree because Latch did not dominate
475   // Header.
476   if (DF) {
477     DominanceFrontier::iterator HeaderDF = DF->find(Header);
478     if (HeaderDF != DF->end()) 
479       DF->removeFromFrontier(HeaderDF, Header);
480
481     DominanceFrontier::iterator LatchDF = DF->find(Latch);
482     if (LatchDF != DF->end()) 
483       DF->removeFromFrontier(LatchDF, Header);
484   }
485   return true;
486 }
487
488 // If loop header includes loop variant instruction operands then
489 // this loop can not be eliminated. This is used by processOneIterationLoop().
490 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
491
492   Instruction *Terminator = Header->getTerminator();
493   for(BasicBlock::iterator BI = Header->begin(), BE = Header->end(); 
494       BI != BE; ++BI) {
495     Instruction *I = BI;
496
497     // PHI Nodes are OK.
498     if (isa<PHINode>(I))
499       continue;
500
501     // SplitCondition itself is OK.
502     if (I == SD.SplitCondition)
503       continue;
504
505     // Induction variable is OK.
506     if (I == IndVar)
507       continue;
508
509     // Induction variable increment is OK.
510     if (I == IndVarIncrement)
511       continue;
512
513     // Terminator is also harmless.
514     if (I == Terminator)
515       continue;
516
517     // Otherwise we have a instruction that may not be safe.
518     return false;
519   }
520   
521   return true;
522 }
523
524 // If Exit block includes loop variant instructions then this
525 // loop may not be eliminated. This is used by processOneIterationLoop().
526 bool LoopIndexSplit::safeExitBlock(SplitInfo &SD, BasicBlock *ExitBlock) {
527
528   for (BasicBlock::iterator BI = ExitBlock->begin(), BE = ExitBlock->end();
529        BI != BE; ++BI) {
530     Instruction *I = BI;
531
532     // PHI Nodes are OK.
533     if (isa<PHINode>(I))
534       continue;
535
536     // Induction variable increment is OK.
537     if (IndVarIncrement && IndVarIncrement == I)
538       continue;
539
540     // Check if I is induction variable increment instruction.
541     if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
542
543       Value *Op0 = I->getOperand(0);
544       Value *Op1 = I->getOperand(1);
545       PHINode *PN = NULL;
546       ConstantInt *CI = NULL;
547
548       if ((PN = dyn_cast<PHINode>(Op0))) {
549         if ((CI = dyn_cast<ConstantInt>(Op1)))
550           IndVarIncrement = I;
551       } else 
552         if ((PN = dyn_cast<PHINode>(Op1))) {
553           if ((CI = dyn_cast<ConstantInt>(Op0)))
554             IndVarIncrement = I;
555       }
556           
557       if (IndVarIncrement && PN == IndVar && CI->isOne())
558         continue;
559     }
560
561     // I is an Exit condition if next instruction is block terminator.
562     // Exit condition is OK if it compares loop invariant exit value,
563     // which is checked below.
564     else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
565       if (EC == ExitCondition)
566         continue;
567     }
568
569     if (I == ExitBlock->getTerminator())
570       continue;
571
572     // Otherwise we have instruction that may not be safe.
573     return false;
574   }
575
576   // We could not find any reason to consider ExitBlock unsafe.
577   return true;
578 }
579
580 /// Find cost of spliting loop L. Cost is measured in terms of size growth.
581 /// Size is growth is calculated based on amount of code duplicated in second
582 /// loop.
583 unsigned LoopIndexSplit::findSplitCost(Loop *L, SplitInfo &SD) {
584
585   unsigned Cost = 0;
586   BasicBlock *SDBlock = SD.SplitCondition->getParent();
587   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
588        I != E; ++I) {
589     BasicBlock *BB = *I;
590     // If a block is not dominated by split condition block then
591     // it must be duplicated in both loops.
592     if (!DT->dominates(SDBlock, BB))
593       Cost += BB->size();
594   }
595
596   return Cost;
597 }
598
599 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
600 /// This routine is used to remove split condition's dead branch, dominated by
601 /// DeadBB. LiveBB dominates split conidition's other branch.
602 void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP, 
603                                   BasicBlock *LiveBB) {
604
605   // First update DeadBB's dominance frontier. 
606   DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
607   if (DeadBBDF != DF->end()) {
608     SmallVector<BasicBlock *, 8> PredBlocks;
609     
610     DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
611     for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
612            DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
613       BasicBlock *FrontierBB = *DeadBBSetI;
614       
615       // Rremove any PHI incoming edge from blocks dominated by DeadBB.
616       PredBlocks.clear();
617       for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
618           PI != PE; ++PI) {
619         BasicBlock *P = *PI;
620         if (P == DeadBB || DT->dominates(DeadBB, P))
621           PredBlocks.push_back(P);
622       }
623       
624       for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
625           FBI != FBE; ++FBI) {
626         if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
627           for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
628                 PE = PredBlocks.end(); PI != PE; ++PI) {
629             BasicBlock *P = *PI;
630             PN->removeIncomingValue(P);
631           }
632         }
633         else
634           break;
635       }
636
637       DT->changeImmediateDominator(FrontierBB, LiveBB);
638
639       // LiveBB is now  dominating FrontierBB. Which means FrontierBB's dominance
640       // frontier is member of LiveBB's dominance frontier. However, FrontierBB
641       // itself is not member of LiveBB's dominance frontier.
642       DominanceFrontier::iterator LiveDF = DF->find(LiveBB);
643       DominanceFrontier::iterator FrontierDF = DF->find(FrontierBB);
644       DominanceFrontier::DomSetType FrontierBBSet = FrontierDF->second;
645       for (DominanceFrontier::DomSetType::iterator FrontierBBSetI = FrontierBBSet.begin(),
646              FrontierBBSetE = FrontierBBSet.end(); FrontierBBSetI != FrontierBBSetE; ++FrontierBBSetI) {
647         BasicBlock *DFMember = *FrontierBBSetI;
648         // Insert only if LiveBB dominates DFMember.
649         if (!DT->dominates(LiveBB, DFMember))
650           LiveDF->second.insert(DFMember);
651       }
652       LiveDF->second.erase(FrontierBB);
653     }
654   }
655   
656   // Now remove DeadBB and all nodes dominated by DeadBB in df order.
657   SmallVector<BasicBlock *, 32> WorkList;
658   DomTreeNode *DN = DT->getNode(DeadBB);
659   for (df_iterator<DomTreeNode*> DI = df_begin(DN),
660          E = df_end(DN); DI != E; ++DI) {
661     BasicBlock *BB = DI->getBlock();
662     WorkList.push_back(BB);
663     BB->getTerminator()->eraseFromParent();
664   }
665
666   while (!WorkList.empty()) {
667     BasicBlock *BB = WorkList.back(); WorkList.pop_back();
668     for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end(); 
669         BBI != BBE; ++BBI) {
670       Instruction *I = BBI;
671       I->replaceAllUsesWith(UndefValue::get(I->getType()));
672       I->eraseFromParent();
673     }
674     LPM->deleteSimpleAnalysisValue(BB, LP);
675     DT->eraseNode(BB);
676     DF->removeBlock(BB);
677     LI->removeBlock(BB);
678     BB->eraseFromParent();
679   }
680 }
681
682 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
683
684   BasicBlock *Preheader = L->getLoopPreheader();
685   BasicBlock *SplitBlock = SD.SplitCondition->getParent();
686   BasicBlock *Latch = L->getLoopLatch();
687   BasicBlock *Header = L->getHeader();
688   BranchInst *SplitTerminator = cast<BranchInst>(SplitBlock->getTerminator());
689
690   // FIXME - Unable to handle triange loops at the moment.
691   // In triangle loop, split condition is in header and one of the
692   // the split destination is loop latch. If split condition is EQ
693   // then such loops are already handle in processOneIterationLoop().
694   if (Header == SplitBlock 
695       && (Latch == SplitTerminator->getSuccessor(0) 
696           || Latch == SplitTerminator->getSuccessor(1)))
697     return false;
698
699   // True loop is original loop. False loop is cloned loop.
700
701   bool SignedPredicate = ExitCondition->isSignedPredicate();  
702   //[*] Calculate True loop's new Exit Value in loop preheader.
703   //      TLExitValue = min(SplitValue, ExitValue)
704   //[*] Calculate False loop's new Start Value in loop preheader.
705   //      FLStartValue = min(SplitValue, TrueLoop.StartValue)
706   Value *TLExitValue = NULL;
707   Value *FLStartValue = NULL;
708   if (isa<ConstantInt>(SD.SplitValue)) {
709     TLExitValue = SD.SplitValue;
710     FLStartValue = SD.SplitValue;
711   }
712   else {
713     Value *C1 = new ICmpInst(SignedPredicate ? 
714                             ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
715                             SD.SplitValue, 
716                              ExitCondition->getOperand(ExitValueNum), 
717                              "lsplit.ev",
718                             Preheader->getTerminator());
719     TLExitValue = new SelectInst(C1, SD.SplitValue, 
720                                  ExitCondition->getOperand(ExitValueNum), 
721                                  "lsplit.ev", Preheader->getTerminator());
722
723     Value *C2 = new ICmpInst(SignedPredicate ? 
724                              ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
725                              SD.SplitValue, StartValue, "lsplit.sv",
726                              Preheader->getTerminator());
727     FLStartValue = new SelectInst(C2, SD.SplitValue, StartValue,
728                                   "lsplit.sv", Preheader->getTerminator());
729   }
730
731   //[*] Clone loop. Avoid true destination of split condition and 
732   //    the blocks dominated by true destination. 
733   DenseMap<const Value *, Value *> ValueMap;
734   Loop *FalseLoop = CloneLoop(L, LPM, LI, ValueMap, this);
735   BasicBlock *FalseHeader = FalseLoop->getHeader();
736
737   //[*] True loop's exit edge enters False loop.
738   PHINode *IndVarClone = cast<PHINode>(ValueMap[IndVar]);
739   BasicBlock *ExitBlock = ExitCondition->getParent();
740   BranchInst *ExitInsn = dyn_cast<BranchInst>(ExitBlock->getTerminator());
741   assert (ExitInsn && "Unable to find suitable loop exit branch");
742   BasicBlock *ExitDest = ExitInsn->getSuccessor(1);
743
744   if (L->contains(ExitDest)) {
745     ExitDest = ExitInsn->getSuccessor(0);
746     ExitInsn->setSuccessor(0, FalseHeader);
747   } else
748     ExitInsn->setSuccessor(1, FalseHeader);
749
750   // Collect inverse map of Header PHINodes.
751   DenseMap<Value *, Value *> InverseMap;
752   for (BasicBlock::iterator BI = L->getHeader()->begin(), 
753          BE = L->getHeader()->end(); BI != BE; ++BI) {
754     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
755       PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
756       InverseMap[PNClone] = PN;
757     } else
758       break;
759   }
760
761   // Update False loop's header
762   for (BasicBlock::iterator BI = FalseHeader->begin(), BE = FalseHeader->end();
763        BI != BE; ++BI) {
764     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
765       PN->removeIncomingValue(Preheader);
766       if (PN == IndVarClone)
767         PN->addIncoming(FLStartValue, ExitBlock);
768       else { 
769         PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
770         Value *V2 = OrigPN->getIncomingValueForBlock(ExitBlock);
771         PN->addIncoming(V2, ExitBlock);
772       }
773     } else
774       break;
775   }
776
777   // Update ExitDest. Now it's predecessor is False loop's exit block.
778   BasicBlock *ExitBlockClone = cast<BasicBlock>(ValueMap[ExitBlock]);
779   for (BasicBlock::iterator BI = ExitDest->begin(), BE = ExitDest->end();
780        BI != BE; ++BI) {
781     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
782       PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(ExitBlock)], ExitBlockClone);
783       PN->removeIncomingValue(ExitBlock);
784     } else
785       break;
786   }
787
788   if (DT) {
789     DT->changeImmediateDominator(FalseHeader, ExitBlock);
790     DT->changeImmediateDominator(ExitDest, cast<BasicBlock>(ValueMap[ExitBlock]));
791   }
792
793   assert (!L->contains(ExitDest) && " Unable to find exit edge destination");
794
795   //[*] Split Exit Edge. 
796   SplitEdge(ExitBlock, FalseHeader, this);
797
798   //[*] Eliminate split condition's false branch from True loop.
799   BranchInst *BR = cast<BranchInst>(SplitBlock->getTerminator());
800   BasicBlock *FBB = BR->getSuccessor(1);
801   BR->setUnconditionalDest(BR->getSuccessor(0));
802   removeBlocks(FBB, L, BR->getSuccessor(0));
803
804   //[*] Update True loop's exit value using new exit value.
805   ExitCondition->setOperand(ExitValueNum, TLExitValue);
806
807   //[*] Eliminate split condition's  true branch in False loop CFG.
808   BasicBlock *FSplitBlock = cast<BasicBlock>(ValueMap[SplitBlock]);
809   BranchInst *FBR = cast<BranchInst>(FSplitBlock->getTerminator());
810   BasicBlock *TBB = FBR->getSuccessor(0);
811   FBR->setUnconditionalDest(FBR->getSuccessor(1));
812   removeBlocks(TBB, FalseLoop, cast<BasicBlock>(FBR->getSuccessor(0)));
813
814   return true;
815 }
816