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