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