Move FN_NOTE_AlwaysInline and other out of ParamAttrs namespace.
[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 is distributed under the University of Illinois Open Source
6 // 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(&ID) {}
37
38     // Index split Loop L. Return true if loop is split.
39     bool runOnLoop(Loop *L, LPPassManager &LPM);
40
41     void getAnalysisUsage(AnalysisUsage &AU) const {
42       AU.addRequired<ScalarEvolution>();
43       AU.addPreserved<ScalarEvolution>();
44       AU.addRequiredID(LCSSAID);
45       AU.addPreservedID(LCSSAID);
46       AU.addRequired<LoopInfo>();
47       AU.addPreserved<LoopInfo>();
48       AU.addRequiredID(LoopSimplifyID);
49       AU.addPreservedID(LoopSimplifyID);
50       AU.addRequired<DominatorTree>();
51       AU.addRequired<DominanceFrontier>();
52       AU.addPreserved<DominatorTree>();
53       AU.addPreserved<DominanceFrontier>();
54     }
55
56   private:
57
58     class SplitInfo {
59     public:
60       SplitInfo() : SplitValue(NULL), SplitCondition(NULL), 
61                     UseTrueBranchFirst(true), A_ExitValue(NULL), 
62                     B_StartValue(NULL) {}
63
64       // Induction variable's range is split at this value.
65       Value *SplitValue;
66       
67       // This instruction compares IndVar against SplitValue.
68       Instruction *SplitCondition;
69
70       // True if after loop index split, first loop will execute split condition's
71       // true branch.
72       bool UseTrueBranchFirst;
73
74       // Exit value for first loop after loop split.
75       Value *A_ExitValue;
76
77       // Start value for second loop after loop split.
78       Value *B_StartValue;
79
80       // Clear split info.
81       void clear() {
82         SplitValue = NULL;
83         SplitCondition = NULL;
84         UseTrueBranchFirst = true;
85         A_ExitValue = NULL;
86         B_StartValue = NULL;
87       }
88
89     };
90     
91   private:
92
93     // safeIcmpInst - CI is considered safe instruction if one of the operand
94     // is SCEVAddRecExpr based on induction variable and other operand is
95     // loop invariant. If CI is safe then populate SplitInfo object SD appropriately
96     // and return true;
97     bool safeICmpInst(ICmpInst *CI, SplitInfo &SD);
98
99     /// Find condition inside a loop that is suitable candidate for index split.
100     void findSplitCondition();
101
102     /// Find loop's exit condition.
103     void findLoopConditionals();
104
105     /// Return induction variable associated with value V.
106     void findIndVar(Value *V, Loop *L);
107
108     /// processOneIterationLoop - Current loop L contains compare instruction
109     /// that compares induction variable, IndVar, agains loop invariant. If
110     /// entire (i.e. meaningful) loop body is dominated by this compare
111     /// instruction then loop body is executed only for one iteration. In
112     /// such case eliminate loop structure surrounding this loop body. For
113     bool processOneIterationLoop(SplitInfo &SD);
114     
115     /// isOneIterationLoop - Return true if split condition is EQ and 
116     /// the IV is not used outside the loop.
117     bool isOneIterationLoop(ICmpInst *CI);
118
119     void updateLoopBounds(ICmpInst *CI);
120     /// updateLoopIterationSpace - Current loop body is covered by an AND
121     /// instruction whose operands compares induction variables with loop
122     /// invariants. If possible, hoist this check outside the loop by
123     /// updating appropriate start and end values for induction variable.
124     bool updateLoopIterationSpace(SplitInfo &SD);
125
126     /// If loop header includes loop variant instruction operands then
127     /// this loop may not be eliminated.
128     bool safeHeader(SplitInfo &SD,  BasicBlock *BB);
129
130     /// If Exiting block includes loop variant instructions then this
131     /// loop may not be eliminated.
132     bool safeExitingBlock(SplitInfo &SD, BasicBlock *BB);
133
134     /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
135     /// This routine is used to remove split condition's dead branch, dominated by
136     /// DeadBB. LiveBB dominates split conidition's other branch.
137     void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
138
139     /// safeSplitCondition - Return true if it is possible to
140     /// split loop using given split condition.
141     bool safeSplitCondition(SplitInfo &SD);
142
143     /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
144     /// based on split value. 
145     void calculateLoopBounds(SplitInfo &SD);
146
147     /// updatePHINodes - CFG has been changed. 
148     /// Before 
149     ///   - ExitBB's single predecessor was Latch
150     ///   - Latch's second successor was Header
151     /// Now
152     ///   - ExitBB's single predecessor was Header
153     ///   - Latch's one and only successor was Header
154     ///
155     /// Update ExitBB PHINodes' to reflect this change.
156     void updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch, 
157                         BasicBlock *Header,
158                         PHINode *IV, Instruction *IVIncrement, Loop *LP);
159
160     /// moveExitCondition - Move exit condition EC into split condition block CondBB.
161     void moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
162                            BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
163                            PHINode *IV, Instruction *IVAdd, Loop *LP);
164
165     /// splitLoop - Split current loop L in two loops using split information
166     /// SD. Update dominator information. Maintain LCSSA form.
167     bool splitLoop(SplitInfo &SD);
168
169     void initialize() {
170       IndVar = NULL; 
171       IndVarIncrement = NULL;
172       ExitCondition = NULL;
173       StartValue = NULL;
174       ExitValueNum = 0;
175       SplitData.clear();
176     }
177
178   private:
179
180     // Current Loop.
181     Loop *L;
182     LPPassManager *LPM;
183     LoopInfo *LI;
184     ScalarEvolution *SE;
185     DominatorTree *DT;
186     DominanceFrontier *DF;
187     SmallVector<SplitInfo, 4> SplitData;
188
189     // Induction variable whose range is being split by this transformation.
190     PHINode *IndVar;
191     Instruction *IndVarIncrement;
192       
193     // Loop exit condition.
194     ICmpInst *ExitCondition;
195
196     // Induction variable's initial value.
197     Value *StartValue;
198
199     // Induction variable's final loop exit value operand number in exit condition..
200     unsigned ExitValueNum;
201   };
202 }
203
204 char LoopIndexSplit::ID = 0;
205 static RegisterPass<LoopIndexSplit>
206 X("loop-index-split", "Index Split Loops");
207
208 LoopPass *llvm::createLoopIndexSplitPass() {
209   return new LoopIndexSplit();
210 }
211
212 // Index split Loop L. Return true if loop is split.
213 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
214   bool Changed = false;
215   L = IncomingLoop;
216   LPM = &LPM_Ref;
217
218   // FIXME - Nested loops make dominator info updates tricky. 
219   if (!L->getSubLoops().empty())
220     return false;
221
222   SE = &getAnalysis<ScalarEvolution>();
223   DT = &getAnalysis<DominatorTree>();
224   LI = &getAnalysis<LoopInfo>();
225   DF = &getAnalysis<DominanceFrontier>();
226
227   initialize();
228
229   findLoopConditionals();
230
231   if (!ExitCondition)
232     return false;
233
234   findSplitCondition();
235
236   if (SplitData.empty())
237     return false;
238
239   // First see if it is possible to eliminate loop itself or not.
240   for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin();
241        SI != SplitData.end();) {
242     SplitInfo &SD = *SI;
243     ICmpInst *CI = dyn_cast<ICmpInst>(SD.SplitCondition);
244     if (SD.SplitCondition->getOpcode() == Instruction::And) {
245       Changed = updateLoopIterationSpace(SD);
246       if (Changed) {
247         ++NumIndexSplit;
248         // If is loop is eliminated then nothing else to do here.
249         return Changed;
250       } else {
251         SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
252         SI = SplitData.erase(Delete_SI);
253       }
254     }
255     else if (isOneIterationLoop(CI)) {
256       Changed = processOneIterationLoop(SD);
257       if (Changed) {
258         ++NumIndexSplit;
259         // If is loop is eliminated then nothing else to do here.
260         return Changed;
261       } else {
262         SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
263         SI = SplitData.erase(Delete_SI);
264       }
265     } else
266       ++SI;
267   }
268
269   if (SplitData.empty())
270     return false;
271
272   // Split most profitiable condition.
273   // FIXME : Implement cost analysis.
274   unsigned MostProfitableSDIndex = 0;
275   Changed = splitLoop(SplitData[MostProfitableSDIndex]);
276
277   if (Changed)
278     ++NumIndexSplit;
279   
280   return Changed;
281 }
282
283 /// isOneIterationLoop - Return true if split condition is EQ and 
284 /// the IV is not used outside the loop.
285 bool LoopIndexSplit::isOneIterationLoop(ICmpInst *CI) {
286   if (!CI)
287     return false;
288   if (CI->getPredicate() != ICmpInst::ICMP_EQ)
289     return false;
290
291   Value *Incr = IndVar->getIncomingValueForBlock(L->getLoopLatch());
292   for (Value::use_iterator UI = Incr->use_begin(), E = Incr->use_end(); 
293        UI != E; ++UI)
294     if (!L->contains(cast<Instruction>(*UI)->getParent()))
295       return false;
296
297   return true;
298 }
299 /// Return true if V is a induction variable or induction variable's
300 /// increment for loop L.
301 void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
302   
303   Instruction *I = dyn_cast<Instruction>(V);
304   if (!I)
305     return;
306
307   // Check if I is a phi node from loop header or not.
308   if (PHINode *PN = dyn_cast<PHINode>(V)) {
309     if (PN->getParent() == L->getHeader()) {
310       IndVar = PN;
311       return;
312     }
313   }
314  
315   // Check if I is a add instruction whose one operand is
316   // phi node from loop header and second operand is constant.
317   if (I->getOpcode() != Instruction::Add)
318     return;
319   
320   Value *Op0 = I->getOperand(0);
321   Value *Op1 = I->getOperand(1);
322   
323   if (PHINode *PN = dyn_cast<PHINode>(Op0)) 
324     if (PN->getParent() == L->getHeader()) 
325       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) 
326         if (CI->isOne()) {
327           IndVar = PN;
328           IndVarIncrement = I;
329           return;
330         }
331
332   if (PHINode *PN = dyn_cast<PHINode>(Op1)) 
333     if (PN->getParent() == L->getHeader()) 
334       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0)) 
335         if (CI->isOne()) {
336           IndVar = PN;
337           IndVarIncrement = I;
338           return;
339         }
340   
341   return;
342 }
343
344 // Find loop's exit condition and associated induction variable.
345 void LoopIndexSplit::findLoopConditionals() {
346
347   BasicBlock *ExitingBlock = NULL;
348
349   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
350        I != E; ++I) {
351     BasicBlock *BB = *I;
352     if (!L->isLoopExit(BB))
353       continue;
354     if (ExitingBlock)
355       return;
356     ExitingBlock = BB;
357   }
358
359   if (!ExitingBlock)
360     return;
361
362   // If exiting block is neither loop header nor loop latch then this loop is
363   // not suitable. 
364   if (ExitingBlock != L->getHeader() && ExitingBlock != L->getLoopLatch())
365     return;
366
367   // If exit block's terminator is conditional branch inst then we have found
368   // exit condition.
369   BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
370   if (!BR || BR->isUnconditional())
371     return;
372   
373   ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
374   if (!CI)
375     return;
376
377   // FIXME 
378   if (CI->getPredicate() == ICmpInst::ICMP_EQ
379       || CI->getPredicate() == ICmpInst::ICMP_NE)
380     return;
381
382   ExitCondition = CI;
383
384   // Exit condition's one operand is loop invariant exit value and second 
385   // operand is SCEVAddRecExpr based on induction variable.
386   Value *V0 = CI->getOperand(0);
387   Value *V1 = CI->getOperand(1);
388   
389   SCEVHandle SH0 = SE->getSCEV(V0);
390   SCEVHandle SH1 = SE->getSCEV(V1);
391   
392   if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
393     ExitValueNum = 0;
394     findIndVar(V1, L);
395   }
396   else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
397     ExitValueNum =  1;
398     findIndVar(V0, L);
399   }
400
401   if (!IndVar) 
402     ExitCondition = NULL;
403   else if (IndVar) {
404     BasicBlock *Preheader = L->getLoopPreheader();
405     StartValue = IndVar->getIncomingValueForBlock(Preheader);
406   }
407
408   // If start value is more then exit value where induction variable
409   // increments by 1 then we are potentially dealing with an infinite loop.
410   // Do not index split this loop.
411   if (ExitCondition) {
412     ConstantInt *SV = dyn_cast<ConstantInt>(StartValue);
413     ConstantInt *EV = 
414       dyn_cast<ConstantInt>(ExitCondition->getOperand(ExitValueNum));
415     if (SV && EV && SV->getSExtValue() > EV->getSExtValue())
416       ExitCondition = NULL;
417     else if (EV && EV->isZero())
418       ExitCondition = NULL;
419   }
420 }
421
422 /// Find condition inside a loop that is suitable candidate for index split.
423 void LoopIndexSplit::findSplitCondition() {
424
425   SplitInfo SD;
426   // Check all basic block's terminators.
427   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
428        I != E; ++I) {
429     SD.clear();
430     BasicBlock *BB = *I;
431
432     // If this basic block does not terminate in a conditional branch
433     // then terminator is not a suitable split condition.
434     BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
435     if (!BR)
436       continue;
437     
438     if (BR->isUnconditional())
439       continue;
440
441     if (Instruction *AndI = dyn_cast<Instruction>(BR->getCondition())) {
442       if (AndI->getOpcode() == Instruction::And) {
443         ICmpInst *Op0 = dyn_cast<ICmpInst>(AndI->getOperand(0));
444         ICmpInst *Op1 = dyn_cast<ICmpInst>(AndI->getOperand(1));
445
446         if (!Op0 || !Op1)
447           continue;
448
449         if (!safeICmpInst(Op0, SD))
450           continue;
451         SD.clear();
452         if (!safeICmpInst(Op1, SD))
453           continue;
454         SD.clear();
455         SD.SplitCondition = AndI;
456         SplitData.push_back(SD);
457         continue;
458       }
459     }
460     ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
461     if (!CI || CI == ExitCondition)
462       continue;
463
464     if (CI->getPredicate() == ICmpInst::ICMP_NE)
465       continue;
466
467     // If split condition predicate is GT or GE then first execute
468     // false branch of split condition.
469     if (CI->getPredicate() == ICmpInst::ICMP_UGT
470         || CI->getPredicate() == ICmpInst::ICMP_SGT
471         || CI->getPredicate() == ICmpInst::ICMP_UGE
472         || CI->getPredicate() == ICmpInst::ICMP_SGE)
473       SD.UseTrueBranchFirst = false;
474
475     // If one operand is loop invariant and second operand is SCEVAddRecExpr
476     // based on induction variable then CI is a candidate split condition.
477     if (safeICmpInst(CI, SD))
478       SplitData.push_back(SD);
479   }
480 }
481
482 // safeIcmpInst - CI is considered safe instruction if one of the operand
483 // is SCEVAddRecExpr based on induction variable and other operand is
484 // loop invariant. If CI is safe then populate SplitInfo object SD appropriately
485 // and return true;
486 bool LoopIndexSplit::safeICmpInst(ICmpInst *CI, SplitInfo &SD) {
487
488   Value *V0 = CI->getOperand(0);
489   Value *V1 = CI->getOperand(1);
490   
491   SCEVHandle SH0 = SE->getSCEV(V0);
492   SCEVHandle SH1 = SE->getSCEV(V1);
493   
494   if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
495     SD.SplitValue = V0;
496     SD.SplitCondition = CI;
497     if (PHINode *PN = dyn_cast<PHINode>(V1)) {
498       if (PN == IndVar)
499         return true;
500     }
501     else  if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
502       if (IndVarIncrement && IndVarIncrement == Insn)
503         return true;
504     }
505   }
506   else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
507     SD.SplitValue =  V1;
508     SD.SplitCondition = CI;
509     if (PHINode *PN = dyn_cast<PHINode>(V0)) {
510       if (PN == IndVar)
511         return true;
512     }
513     else  if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
514       if (IndVarIncrement && IndVarIncrement == Insn)
515         return true;
516     }
517   }
518
519   return false;
520 }
521
522 /// processOneIterationLoop - Current loop L contains compare instruction
523 /// that compares induction variable, IndVar, against loop invariant. If
524 /// entire (i.e. meaningful) loop body is dominated by this compare
525 /// instruction then loop body is executed only once. In such case eliminate 
526 /// loop structure surrounding this loop body. For example,
527 ///     for (int i = start; i < end; ++i) {
528 ///         if ( i == somevalue) {
529 ///           loop_body
530 ///         }
531 ///     }
532 /// can be transformed into
533 ///     if (somevalue >= start && somevalue < end) {
534 ///        i = somevalue;
535 ///        loop_body
536 ///     }
537 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
538
539   BasicBlock *Header = L->getHeader();
540
541   // First of all, check if SplitCondition dominates entire loop body
542   // or not.
543   
544   // If SplitCondition is not in loop header then this loop is not suitable
545   // for this transformation.
546   if (SD.SplitCondition->getParent() != Header)
547     return false;
548   
549   // If loop header includes loop variant instruction operands then
550   // this loop may not be eliminated.
551   if (!safeHeader(SD, Header)) 
552     return false;
553
554   // If Exiting block includes loop variant instructions then this
555   // loop may not be eliminated.
556   if (!safeExitingBlock(SD, ExitCondition->getParent())) 
557     return false;
558
559   // Filter loops where split condition's false branch is not empty.
560   if (ExitCondition->getParent() != Header->getTerminator()->getSuccessor(1))
561     return false;
562
563   // If split condition is not safe then do not process this loop.
564   // For example,
565   // for(int i = 0; i < N; i++) {
566   //    if ( i == XYZ) {
567   //      A;
568   //    else
569   //      B;
570   //    }
571   //   C;
572   //   D;
573   // }
574   if (!safeSplitCondition(SD))
575     return false;
576
577   BasicBlock *Latch = L->getLoopLatch();
578   BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
579   if (!BR)
580     return false;
581
582   // Update CFG.
583
584   // Replace index variable with split value in loop body. Loop body is executed
585   // only when index variable is equal to split value.
586   IndVar->replaceAllUsesWith(SD.SplitValue);
587
588   // Remove Latch to Header edge.
589   BasicBlock *LatchSucc = NULL;
590   Header->removePredecessor(Latch);
591   for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
592        SI != E; ++SI) {
593     if (Header != *SI)
594       LatchSucc = *SI;
595   }
596   BR->setUnconditionalDest(LatchSucc);
597
598   Instruction *Terminator = Header->getTerminator();
599   Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
600
601   // Replace split condition in header.
602   // Transform 
603   //      SplitCondition : icmp eq i32 IndVar, SplitValue
604   // into
605   //      c1 = icmp uge i32 SplitValue, StartValue
606   //      c2 = icmp ult i32 SplitValue, ExitValue
607   //      and i32 c1, c2 
608   bool SignedPredicate = ExitCondition->isSignedPredicate();
609   Instruction *C1 = new ICmpInst(SignedPredicate ? 
610                                  ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
611                                  SD.SplitValue, StartValue, "lisplit", 
612                                  Terminator);
613   Instruction *C2 = new ICmpInst(SignedPredicate ? 
614                                  ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
615                                  SD.SplitValue, ExitValue, "lisplit", 
616                                  Terminator);
617   Instruction *NSplitCond = BinaryOperator::CreateAnd(C1, C2, "lisplit", 
618                                                       Terminator);
619   SD.SplitCondition->replaceAllUsesWith(NSplitCond);
620   SD.SplitCondition->eraseFromParent();
621
622   // Now, clear latch block. Remove instructions that are responsible
623   // to increment induction variable. 
624   Instruction *LTerminator = Latch->getTerminator();
625   for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
626        LB != LE; ) {
627     Instruction *I = LB;
628     ++LB;
629     if (isa<PHINode>(I) || I == LTerminator)
630       continue;
631
632     if (I == IndVarIncrement) {
633       // Replace induction variable increment if it is not used outside 
634       // the loop.
635       bool UsedOutsideLoop = false;
636       for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); 
637            UI != E; ++UI) {
638         if (Instruction *Use = dyn_cast<Instruction>(UI)) 
639           if (!L->contains(Use->getParent())) {
640             UsedOutsideLoop = true;
641             break;
642           }
643       }
644       if (!UsedOutsideLoop) {
645         I->replaceAllUsesWith(ExitValue);
646         I->eraseFromParent();
647       }
648     }
649     else {
650       I->replaceAllUsesWith(UndefValue::get(I->getType()));
651       I->eraseFromParent();
652     }
653   }
654
655   LPM->deleteLoopFromQueue(L);
656
657   // Update Dominator Info.
658   // Only CFG change done is to remove Latch to Header edge. This
659   // does not change dominator tree because Latch did not dominate
660   // Header.
661   if (DF) {
662     DominanceFrontier::iterator HeaderDF = DF->find(Header);
663     if (HeaderDF != DF->end()) 
664       DF->removeFromFrontier(HeaderDF, Header);
665
666     DominanceFrontier::iterator LatchDF = DF->find(Latch);
667     if (LatchDF != DF->end()) 
668       DF->removeFromFrontier(LatchDF, Header);
669   }
670   return true;
671 }
672
673 // If loop header includes loop variant instruction operands then
674 // this loop can not be eliminated. This is used by processOneIterationLoop().
675 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
676
677   Instruction *Terminator = Header->getTerminator();
678   for(BasicBlock::iterator BI = Header->begin(), BE = Header->end(); 
679       BI != BE; ++BI) {
680     Instruction *I = BI;
681
682     // PHI Nodes are OK.
683     if (isa<PHINode>(I))
684       continue;
685
686     // SplitCondition itself is OK.
687     if (I == SD.SplitCondition)
688       continue;
689
690     // Induction variable is OK.
691     if (I == IndVar)
692       continue;
693
694     // Induction variable increment is OK.
695     if (I == IndVarIncrement)
696       continue;
697
698     // Terminator is also harmless.
699     if (I == Terminator)
700       continue;
701
702     // Otherwise we have a instruction that may not be safe.
703     return false;
704   }
705   
706   return true;
707 }
708
709 // If Exiting block includes loop variant instructions then this
710 // loop may not be eliminated. This is used by processOneIterationLoop().
711 bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD, 
712                                        BasicBlock *ExitingBlock) {
713
714   for (BasicBlock::iterator BI = ExitingBlock->begin(), 
715          BE = ExitingBlock->end(); BI != BE; ++BI) {
716     Instruction *I = BI;
717
718     // PHI Nodes are OK.
719     if (isa<PHINode>(I))
720       continue;
721
722     // Induction variable increment is OK.
723     if (IndVarIncrement && IndVarIncrement == I)
724       continue;
725
726     // Check if I is induction variable increment instruction.
727     if (I->getOpcode() == Instruction::Add) {
728
729       Value *Op0 = I->getOperand(0);
730       Value *Op1 = I->getOperand(1);
731       PHINode *PN = NULL;
732       ConstantInt *CI = NULL;
733
734       if ((PN = dyn_cast<PHINode>(Op0))) {
735         if ((CI = dyn_cast<ConstantInt>(Op1)))
736           if (CI->isOne()) {
737             if (!IndVarIncrement && PN == IndVar)
738               IndVarIncrement = I;
739             // else this is another loop induction variable
740             continue;
741           }
742       } else 
743         if ((PN = dyn_cast<PHINode>(Op1))) {
744           if ((CI = dyn_cast<ConstantInt>(Op0)))
745             if (CI->isOne()) {
746               if (!IndVarIncrement && PN == IndVar)
747                 IndVarIncrement = I;
748               // else this is another loop induction variable
749               continue;
750             }
751       }
752     } 
753
754     // I is an Exit condition if next instruction is block terminator.
755     // Exit condition is OK if it compares loop invariant exit value,
756     // which is checked below.
757     else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
758       if (EC == ExitCondition)
759         continue;
760     }
761
762     if (I == ExitingBlock->getTerminator())
763       continue;
764
765     // Otherwise we have instruction that may not be safe.
766     return false;
767   }
768
769   // We could not find any reason to consider ExitingBlock unsafe.
770   return true;
771 }
772
773 void LoopIndexSplit::updateLoopBounds(ICmpInst *CI) {
774
775   Value *V0 = CI->getOperand(0);
776   Value *V1 = CI->getOperand(1);
777   Value *NV = NULL;
778
779   SCEVHandle SH0 = SE->getSCEV(V0);
780   
781   if (SH0->isLoopInvariant(L))
782     NV = V0;
783   else
784     NV = V1;
785
786   if (ExitCondition->getPredicate() == ICmpInst::ICMP_SGT
787       || ExitCondition->getPredicate() == ICmpInst::ICMP_UGT
788       || ExitCondition->getPredicate() == ICmpInst::ICMP_SGE
789       || ExitCondition->getPredicate() == ICmpInst::ICMP_UGE)  {
790     ExitCondition->swapOperands();
791     if (ExitValueNum)
792       ExitValueNum = 0;
793     else
794       ExitValueNum = 1;
795   }
796
797   Value *NUB = NULL;
798   Value *NLB = NULL;
799   Value *UB = ExitCondition->getOperand(ExitValueNum);
800   const Type *Ty = NV->getType();
801   bool Sign = ExitCondition->isSignedPredicate();
802   BasicBlock *Preheader = L->getLoopPreheader();
803   Instruction *PHTerminator = Preheader->getTerminator();
804
805   assert (NV && "Unexpected value");
806
807   switch (CI->getPredicate()) {
808   case ICmpInst::ICMP_ULE:
809   case ICmpInst::ICMP_SLE:
810     // for (i = LB; i < UB; ++i)
811     //   if (i <= NV && ...)
812     //      LOOP_BODY
813     // 
814     // is transformed into
815     // NUB = min (NV+1, UB)
816     // for (i = LB; i < NUB ; ++i)
817     //   LOOP_BODY
818     //
819     if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLT
820         || ExitCondition->getPredicate() == ICmpInst::ICMP_ULT) {
821       Value *A = BinaryOperator::CreateAdd(NV, ConstantInt::get(Ty, 1, Sign),
822                                            "lsplit.add", PHTerminator);
823       Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
824                               A, UB,"lsplit,c", PHTerminator);
825       NUB = SelectInst::Create(C, A, UB, "lsplit.nub", PHTerminator);
826     }
827     
828     // for (i = LB; i <= UB; ++i)
829     //   if (i <= NV && ...)
830     //      LOOP_BODY
831     // 
832     // is transformed into
833     // NUB = min (NV, UB)
834     // for (i = LB; i <= NUB ; ++i)
835     //   LOOP_BODY
836     //
837     else if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLE
838              || ExitCondition->getPredicate() == ICmpInst::ICMP_ULE) {
839       Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
840                               NV, UB, "lsplit.c", PHTerminator);
841       NUB = SelectInst::Create(C, NV, UB, "lsplit.nub", PHTerminator);
842     }
843     break;
844   case ICmpInst::ICMP_ULT:
845   case ICmpInst::ICMP_SLT:
846     // for (i = LB; i < UB; ++i)
847     //   if (i < NV && ...)
848     //      LOOP_BODY
849     // 
850     // is transformed into
851     // NUB = min (NV, UB)
852     // for (i = LB; i < NUB ; ++i)
853     //   LOOP_BODY
854     //
855     if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLT
856         || ExitCondition->getPredicate() == ICmpInst::ICMP_ULT) {
857       Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
858                               NV, UB, "lsplit.c", PHTerminator);
859       NUB = SelectInst::Create(C, NV, UB, "lsplit.nub", PHTerminator);
860     }
861
862     // for (i = LB; i <= UB; ++i)
863     //   if (i < NV && ...)
864     //      LOOP_BODY
865     // 
866     // is transformed into
867     // NUB = min (NV -1 , UB)
868     // for (i = LB; i <= NUB ; ++i)
869     //   LOOP_BODY
870     //
871     else if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLE
872              || ExitCondition->getPredicate() == ICmpInst::ICMP_ULE) {
873       Value *S = BinaryOperator::CreateSub(NV, ConstantInt::get(Ty, 1, Sign),
874                                            "lsplit.add", PHTerminator);
875       Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
876                               S, UB, "lsplit.c", PHTerminator);
877       NUB = SelectInst::Create(C, S, UB, "lsplit.nub", PHTerminator);
878     }
879     break;
880   case ICmpInst::ICMP_UGE:
881   case ICmpInst::ICMP_SGE:
882     // for (i = LB; i (< or <=) UB; ++i)
883     //   if (i >= NV && ...)
884     //      LOOP_BODY
885     // 
886     // is transformed into
887     // NLB = max (NV, LB)
888     // for (i = NLB; i (< or <=) UB ; ++i)
889     //   LOOP_BODY
890     //
891     {
892       Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
893                               NV, StartValue, "lsplit.c", PHTerminator);
894       NLB = SelectInst::Create(C, StartValue, NV, "lsplit.nlb", PHTerminator);
895     }
896     break;
897   case ICmpInst::ICMP_UGT:
898   case ICmpInst::ICMP_SGT:
899     // for (i = LB; i (< or <=) UB; ++i)
900     //   if (i > NV && ...)
901     //      LOOP_BODY
902     // 
903     // is transformed into
904     // NLB = max (NV+1, LB)
905     // for (i = NLB; i (< or <=) UB ; ++i)
906     //   LOOP_BODY
907     //
908     {
909       Value *A = BinaryOperator::CreateAdd(NV, ConstantInt::get(Ty, 1, Sign),
910                                            "lsplit.add", PHTerminator);
911       Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
912                               A, StartValue, "lsplit.c", PHTerminator);
913       NLB = SelectInst::Create(C, StartValue, A, "lsplit.nlb", PHTerminator);
914     }
915     break;
916   default:
917     assert ( 0 && "Unexpected split condition predicate");
918   }
919
920   if (NLB) {
921     unsigned i = IndVar->getBasicBlockIndex(Preheader);
922     IndVar->setIncomingValue(i, NLB);
923   }
924
925   if (NUB) {
926     ExitCondition->setOperand(ExitValueNum, NUB);
927   }
928 }
929 /// updateLoopIterationSpace - Current loop body is covered by an AND
930 /// instruction whose operands compares induction variables with loop
931 /// invariants. If possible, hoist this check outside the loop by
932 /// updating appropriate start and end values for induction variable.
933 bool LoopIndexSplit::updateLoopIterationSpace(SplitInfo &SD) {
934   BasicBlock *Header = L->getHeader();
935   BasicBlock *ExitingBlock = ExitCondition->getParent();
936   BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
937
938   ICmpInst *Op0 = cast<ICmpInst>(SD.SplitCondition->getOperand(0));
939   ICmpInst *Op1 = cast<ICmpInst>(SD.SplitCondition->getOperand(1));
940
941   if (Op0->getPredicate() == ICmpInst::ICMP_EQ 
942       || Op0->getPredicate() == ICmpInst::ICMP_NE
943       || Op0->getPredicate() == ICmpInst::ICMP_EQ 
944       || Op0->getPredicate() == ICmpInst::ICMP_NE)
945     return false;
946
947   // Check if SplitCondition dominates entire loop body
948   // or not.
949   
950   // If SplitCondition is not in loop header then this loop is not suitable
951   // for this transformation.
952   if (SD.SplitCondition->getParent() != Header)
953     return false;
954   
955   // If loop header includes loop variant instruction operands then
956   // this loop may not be eliminated.
957   Instruction *Terminator = Header->getTerminator();
958   for(BasicBlock::iterator BI = Header->begin(), BE = Header->end(); 
959       BI != BE; ++BI) {
960     Instruction *I = BI;
961
962     // PHI Nodes are OK.
963     if (isa<PHINode>(I))
964       continue;
965
966     // SplitCondition itself is OK.
967     if (I == SD.SplitCondition)
968       continue;
969     if (I == Op0 || I == Op1)
970       continue;
971
972     // Induction variable is OK.
973     if (I == IndVar)
974       continue;
975
976     // Induction variable increment is OK.
977     if (I == IndVarIncrement)
978       continue;
979
980     // Terminator is also harmless.
981     if (I == Terminator)
982       continue;
983
984     // Otherwise we have a instruction that may not be safe.
985     return false;
986   }
987
988   // If Exiting block includes loop variant instructions then this
989   // loop may not be eliminated.
990   if (!safeExitingBlock(SD, ExitCondition->getParent())) 
991     return false;
992   
993   // Verify that loop exiting block has only two predecessor, where one predecessor
994   // is split condition block. The other predecessor will become exiting block's
995   // dominator after CFG is updated. TODO : Handle CFG's where exiting block has
996   // more then two predecessors. This requires extra work in updating dominator
997   // information.
998   BasicBlock *ExitingBBPred = NULL;
999   for (pred_iterator PI = pred_begin(ExitingBlock), PE = pred_end(ExitingBlock);
1000        PI != PE; ++PI) {
1001     BasicBlock *BB = *PI;
1002     if (SplitCondBlock == BB) 
1003       continue;
1004     if (ExitingBBPred)
1005       return false;
1006     else
1007       ExitingBBPred = BB;
1008   }
1009   
1010   // Update loop bounds to absorb Op0 check.
1011   updateLoopBounds(Op0);
1012   // Update loop bounds to absorb Op1 check.
1013   updateLoopBounds(Op1);
1014
1015   // Update CFG
1016
1017   // Unconditionally connect split block to its remaining successor. 
1018   BranchInst *SplitTerminator = 
1019     cast<BranchInst>(SplitCondBlock->getTerminator());
1020   BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1021   BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1022   if (Succ0 == ExitCondition->getParent())
1023     SplitTerminator->setUnconditionalDest(Succ1);
1024   else
1025     SplitTerminator->setUnconditionalDest(Succ0);
1026
1027   // Remove split condition.
1028   SD.SplitCondition->eraseFromParent();
1029   if (Op0->use_empty())
1030     Op0->eraseFromParent();
1031   if (Op1->use_empty())
1032     Op1->eraseFromParent();
1033       
1034   BranchInst *ExitInsn =
1035     dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1036   assert (ExitInsn && "Unable to find suitable loop exit branch");
1037   BasicBlock *ExitBlock = ExitInsn->getSuccessor(1);
1038   if (L->contains(ExitBlock))
1039     ExitBlock = ExitInsn->getSuccessor(0);
1040
1041   // Update domiantor info. Now, ExitingBlock has only one predecessor, 
1042   // ExitingBBPred, and it is ExitingBlock's immediate domiantor.
1043   DT->changeImmediateDominator(ExitingBlock, ExitingBBPred);
1044   
1045   // If ExitingBlock is a member of loop BB's DF list then replace it with
1046   // loop header and exit block.
1047   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
1048        I != E; ++I) {
1049     BasicBlock *BB = *I;
1050     if (BB == Header || BB == ExitingBlock)
1051       continue;
1052     DominanceFrontier::iterator BBDF = DF->find(BB);
1053     DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1054     DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1055     while (DomSetI != DomSetE) {
1056       DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1057       ++DomSetI;
1058       BasicBlock *DFBB = *CurrentItr;
1059       if (DFBB == ExitingBlock) {
1060         BBDF->second.erase(DFBB);
1061         BBDF->second.insert(Header);
1062         if (Header != ExitingBlock)
1063           BBDF->second.insert(ExitBlock);
1064       }
1065     }
1066   }
1067
1068   return true;
1069 }
1070
1071
1072 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
1073 /// This routine is used to remove split condition's dead branch, dominated by
1074 /// DeadBB. LiveBB dominates split conidition's other branch.
1075 void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP, 
1076                                   BasicBlock *LiveBB) {
1077
1078   // First update DeadBB's dominance frontier. 
1079   SmallVector<BasicBlock *, 8> FrontierBBs;
1080   DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
1081   if (DeadBBDF != DF->end()) {
1082     SmallVector<BasicBlock *, 8> PredBlocks;
1083     
1084     DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
1085     for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
1086            DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
1087       BasicBlock *FrontierBB = *DeadBBSetI;
1088       FrontierBBs.push_back(FrontierBB);
1089
1090       // Rremove any PHI incoming edge from blocks dominated by DeadBB.
1091       PredBlocks.clear();
1092       for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
1093           PI != PE; ++PI) {
1094         BasicBlock *P = *PI;
1095         if (P == DeadBB || DT->dominates(DeadBB, P))
1096           PredBlocks.push_back(P);
1097       }
1098
1099       for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
1100           FBI != FBE; ++FBI) {
1101         if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
1102           for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
1103                 PE = PredBlocks.end(); PI != PE; ++PI) {
1104             BasicBlock *P = *PI;
1105             PN->removeIncomingValue(P);
1106           }
1107         }
1108         else
1109           break;
1110       }      
1111     }
1112   }
1113   
1114   // Now remove DeadBB and all nodes dominated by DeadBB in df order.
1115   SmallVector<BasicBlock *, 32> WorkList;
1116   DomTreeNode *DN = DT->getNode(DeadBB);
1117   for (df_iterator<DomTreeNode*> DI = df_begin(DN),
1118          E = df_end(DN); DI != E; ++DI) {
1119     BasicBlock *BB = DI->getBlock();
1120     WorkList.push_back(BB);
1121     BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
1122   }
1123
1124   while (!WorkList.empty()) {
1125     BasicBlock *BB = WorkList.back(); WorkList.pop_back();
1126     for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end(); 
1127         BBI != BBE; ) {
1128       Instruction *I = BBI;
1129       ++BBI;
1130       I->replaceAllUsesWith(UndefValue::get(I->getType()));
1131       I->eraseFromParent();
1132     }
1133     LPM->deleteSimpleAnalysisValue(BB, LP);
1134     DT->eraseNode(BB);
1135     DF->removeBlock(BB);
1136     LI->removeBlock(BB);
1137     BB->eraseFromParent();
1138   }
1139
1140   // Update Frontier BBs' dominator info.
1141   while (!FrontierBBs.empty()) {
1142     BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
1143     BasicBlock *NewDominator = FBB->getSinglePredecessor();
1144     if (!NewDominator) {
1145       pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
1146       NewDominator = *PI;
1147       ++PI;
1148       if (NewDominator != LiveBB) {
1149         for(; PI != PE; ++PI) {
1150           BasicBlock *P = *PI;
1151           if (P == LiveBB) {
1152             NewDominator = LiveBB;
1153             break;
1154           }
1155           NewDominator = DT->findNearestCommonDominator(NewDominator, P);
1156         }
1157       }
1158     }
1159     assert (NewDominator && "Unable to fix dominator info.");
1160     DT->changeImmediateDominator(FBB, NewDominator);
1161     DF->changeImmediateDominator(FBB, NewDominator, DT);
1162   }
1163
1164 }
1165
1166 /// safeSplitCondition - Return true if it is possible to
1167 /// split loop using given split condition.
1168 bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
1169
1170   BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
1171   BasicBlock *Latch = L->getLoopLatch();  
1172   BranchInst *SplitTerminator = 
1173     cast<BranchInst>(SplitCondBlock->getTerminator());
1174   BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1175   BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1176
1177   // If split block does not dominate the latch then this is not a diamond.
1178   // Such loop may not benefit from index split.
1179   if (!DT->dominates(SplitCondBlock, Latch))
1180     return false;
1181
1182   // Finally this split condition is safe only if merge point for
1183   // split condition branch is loop latch. This check along with previous
1184   // check, to ensure that exit condition is in either loop latch or header,
1185   // filters all loops with non-empty loop body between merge point
1186   // and exit condition.
1187   DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
1188   assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
1189   if (Succ0DF->second.count(Latch))
1190     return true;
1191
1192   DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
1193   assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
1194   if (Succ1DF->second.count(Latch))
1195     return true;
1196   
1197   return false;
1198 }
1199
1200 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
1201 /// based on split value. 
1202 void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
1203
1204   ICmpInst *SC = cast<ICmpInst>(SD.SplitCondition);
1205   ICmpInst::Predicate SP = SC->getPredicate();
1206   const Type *Ty = SD.SplitValue->getType();
1207   bool Sign = ExitCondition->isSignedPredicate();
1208   BasicBlock *Preheader = L->getLoopPreheader();
1209   Instruction *PHTerminator = Preheader->getTerminator();
1210
1211   // Initially use split value as upper loop bound for first loop and lower loop
1212   // bound for second loop.
1213   Value *AEV = SD.SplitValue;
1214   Value *BSV = SD.SplitValue;
1215
1216   if (ExitCondition->getPredicate() == ICmpInst::ICMP_SGT
1217       || ExitCondition->getPredicate() == ICmpInst::ICMP_UGT
1218       || ExitCondition->getPredicate() == ICmpInst::ICMP_SGE
1219       || ExitCondition->getPredicate() == ICmpInst::ICMP_UGE) {
1220     ExitCondition->swapOperands();
1221     if (ExitValueNum)
1222       ExitValueNum = 0;
1223     else
1224       ExitValueNum = 1;
1225   }
1226
1227   switch (ExitCondition->getPredicate()) {
1228   case ICmpInst::ICMP_SGT:
1229   case ICmpInst::ICMP_UGT:
1230   case ICmpInst::ICMP_SGE:
1231   case ICmpInst::ICMP_UGE:
1232   default:
1233     assert (0 && "Unexpected exit condition predicate");
1234
1235   case ICmpInst::ICMP_SLT:
1236   case ICmpInst::ICMP_ULT:
1237     {
1238       switch (SP) {
1239       case ICmpInst::ICMP_SLT:
1240       case ICmpInst::ICMP_ULT:
1241         //
1242         // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
1243         //
1244         // is transformed into
1245         // AEV = BSV = SV
1246         // for (i = LB; i < min(UB, AEV); ++i)
1247         //    A;
1248         // for (i = max(LB, BSV); i < UB; ++i);
1249         //    B;
1250         break;
1251       case ICmpInst::ICMP_SLE:
1252       case ICmpInst::ICMP_ULE:
1253         {
1254           //
1255           // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
1256           //
1257           // is transformed into
1258           //
1259           // AEV = SV + 1
1260           // BSV = SV + 1
1261           // for (i = LB; i < min(UB, AEV); ++i) 
1262           //       A;
1263           // for (i = max(LB, BSV); i < UB; ++i) 
1264           //       B;
1265           BSV = BinaryOperator::CreateAdd(SD.SplitValue,
1266                                           ConstantInt::get(Ty, 1, Sign),
1267                                           "lsplit.add", PHTerminator);
1268           AEV = BSV;
1269         }
1270         break;
1271       case ICmpInst::ICMP_SGE:
1272       case ICmpInst::ICMP_UGE: 
1273         //
1274         // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
1275         // 
1276         // is transformed into
1277         // AEV = BSV = SV
1278         // for (i = LB; i < min(UB, AEV); ++i)
1279         //    B;
1280         // for (i = max(BSV, LB); i < UB; ++i)
1281         //    A;
1282         break;
1283       case ICmpInst::ICMP_SGT:
1284       case ICmpInst::ICMP_UGT: 
1285         {
1286           //
1287           // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
1288           //
1289           // is transformed into
1290           //
1291           // BSV = AEV = SV + 1
1292           // for (i = LB; i < min(UB, AEV); ++i) 
1293           //       B;
1294           // for (i = max(LB, BSV); i < UB; ++i) 
1295           //       A;
1296           BSV = BinaryOperator::CreateAdd(SD.SplitValue,
1297                                           ConstantInt::get(Ty, 1, Sign),
1298                                           "lsplit.add", PHTerminator);
1299           AEV = BSV;
1300         }
1301         break;
1302       default:
1303         assert (0 && "Unexpected split condition predicate");
1304         break;
1305       } // end switch (SP)
1306     }
1307     break;
1308   case ICmpInst::ICMP_SLE:
1309   case ICmpInst::ICMP_ULE:
1310     {
1311       switch (SP) {
1312       case ICmpInst::ICMP_SLT:
1313       case ICmpInst::ICMP_ULT:
1314         //
1315         // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
1316         //
1317         // is transformed into
1318         // AEV = SV - 1;
1319         // BSV = SV;
1320         // for (i = LB; i <= min(UB, AEV); ++i) 
1321         //       A;
1322         // for (i = max(LB, BSV); i <= UB; ++i) 
1323         //       B;
1324         AEV = BinaryOperator::CreateSub(SD.SplitValue,
1325                                         ConstantInt::get(Ty, 1, Sign),
1326                                         "lsplit.sub", PHTerminator);
1327         break;
1328       case ICmpInst::ICMP_SLE:
1329       case ICmpInst::ICMP_ULE:
1330         //
1331         // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
1332         //
1333         // is transformed into
1334         // AEV = SV;
1335         // BSV = SV + 1;
1336         // for (i = LB; i <= min(UB, AEV); ++i) 
1337         //       A;
1338         // for (i = max(LB, BSV); i <= UB; ++i) 
1339         //       B;
1340         BSV = BinaryOperator::CreateAdd(SD.SplitValue,
1341                                         ConstantInt::get(Ty, 1, Sign),
1342                                         "lsplit.add", PHTerminator);
1343         break;
1344       case ICmpInst::ICMP_SGT:
1345       case ICmpInst::ICMP_UGT: 
1346         //
1347         // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
1348         //
1349         // is transformed into
1350         // AEV = SV;
1351         // BSV = SV + 1;
1352         // for (i = LB; i <= min(AEV, UB); ++i)
1353         //      B;
1354         // for (i = max(LB, BSV); i <= UB; ++i)
1355         //      A;
1356         BSV = BinaryOperator::CreateAdd(SD.SplitValue,
1357                                         ConstantInt::get(Ty, 1, Sign),
1358                                         "lsplit.add", PHTerminator);
1359         break;
1360       case ICmpInst::ICMP_SGE:
1361       case ICmpInst::ICMP_UGE: 
1362         // ** TODO **
1363         //
1364         // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
1365         //
1366         // is transformed into
1367         // AEV = SV - 1;
1368         // BSV = SV;
1369         // for (i = LB; i <= min(AEV, UB); ++i)
1370         //      B;
1371         // for (i = max(LB, BSV); i <= UB; ++i)
1372         //      A;
1373         AEV = BinaryOperator::CreateSub(SD.SplitValue,
1374                                         ConstantInt::get(Ty, 1, Sign),
1375                                         "lsplit.sub", PHTerminator);
1376         break;
1377       default:
1378         assert (0 && "Unexpected split condition predicate");
1379         break;
1380       } // end switch (SP)
1381     }
1382     break;
1383   }
1384
1385   // Calculate ALoop induction variable's new exiting value and
1386   // BLoop induction variable's new starting value. Calculuate these
1387   // values in original loop's preheader.
1388   //      A_ExitValue = min(SplitValue, OrignalLoopExitValue)
1389   //      B_StartValue = max(SplitValue, OriginalLoopStartValue)
1390   Instruction *InsertPt = L->getHeader()->getFirstNonPHI();
1391
1392   // If ExitValue operand is also defined in Loop header then
1393   // insert new ExitValue after this operand definition.
1394   if (Instruction *EVN = 
1395       dyn_cast<Instruction>(ExitCondition->getOperand(ExitValueNum))) {
1396     if (!isa<PHINode>(EVN))
1397       if (InsertPt->getParent() == EVN->getParent()) {
1398         BasicBlock::iterator LHBI = L->getHeader()->begin();
1399         BasicBlock::iterator LHBE = L->getHeader()->end();  
1400         for(;LHBI != LHBE; ++LHBI) {
1401           Instruction *I = LHBI;
1402           if (I == EVN) 
1403             break;
1404         }
1405         InsertPt = ++LHBI;
1406       }
1407   }
1408   Value *C1 = new ICmpInst(Sign ?
1409                            ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1410                            AEV,
1411                            ExitCondition->getOperand(ExitValueNum), 
1412                            "lsplit.ev", InsertPt);
1413
1414   SD.A_ExitValue = SelectInst::Create(C1, AEV,
1415                                       ExitCondition->getOperand(ExitValueNum), 
1416                                       "lsplit.ev", InsertPt);
1417
1418   Value *C2 = new ICmpInst(Sign ?
1419                            ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1420                            BSV, StartValue, "lsplit.sv",
1421                            PHTerminator);
1422   SD.B_StartValue = SelectInst::Create(C2, StartValue, BSV,
1423                                        "lsplit.sv", PHTerminator);
1424 }
1425
1426 /// splitLoop - Split current loop L in two loops using split information
1427 /// SD. Update dominator information. Maintain LCSSA form.
1428 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
1429
1430   if (!safeSplitCondition(SD))
1431     return false;
1432
1433   // If split condition EQ is not handled.
1434   if (ICmpInst *ICMP = dyn_cast<ICmpInst>(SD.SplitCondition)) {
1435     if (ICMP->getPredicate() == ICmpInst::ICMP_EQ)
1436       return false;
1437   }
1438   
1439   BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
1440   
1441   // Unable to handle triangle loops at the moment.
1442   // In triangle loop, split condition is in header and one of the
1443   // the split destination is loop latch. If split condition is EQ
1444   // then such loops are already handle in processOneIterationLoop().
1445   BasicBlock *Latch = L->getLoopLatch();
1446   BranchInst *SplitTerminator = 
1447     cast<BranchInst>(SplitCondBlock->getTerminator());
1448   BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1449   BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1450   if (L->getHeader() == SplitCondBlock 
1451       && (Latch == Succ0 || Latch == Succ1))
1452     return false;
1453
1454   // If split condition branches heads do not have single predecessor, 
1455   // SplitCondBlock, then is not possible to remove inactive branch.
1456   if (!Succ0->getSinglePredecessor() || !Succ1->getSinglePredecessor())
1457     return false;
1458
1459   // If Exiting block includes loop variant instructions then this
1460   // loop may not be split safely.
1461   if (!safeExitingBlock(SD, ExitCondition->getParent())) 
1462     return false;
1463
1464   // After loop is cloned there are two loops.
1465   //
1466   // First loop, referred as ALoop, executes first part of loop's iteration
1467   // space split.  Second loop, referred as BLoop, executes remaining
1468   // part of loop's iteration space. 
1469   //
1470   // ALoop's exit edge enters BLoop's header through a forwarding block which 
1471   // acts as a BLoop's preheader.
1472   BasicBlock *Preheader = L->getLoopPreheader();
1473
1474   // Calculate ALoop induction variable's new exiting value and
1475   // BLoop induction variable's new starting value.
1476   calculateLoopBounds(SD);
1477
1478   //[*] Clone loop.
1479   DenseMap<const Value *, Value *> ValueMap;
1480   Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
1481   Loop *ALoop = L;
1482   BasicBlock *B_Header = BLoop->getHeader();
1483
1484   //[*] ALoop's exiting edge BLoop's header.
1485   //    ALoop's original exit block becomes BLoop's exit block.
1486   PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1487   BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1488   BranchInst *A_ExitInsn =
1489     dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1490   assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1491   BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1492   if (L->contains(B_ExitBlock)) {
1493     B_ExitBlock = A_ExitInsn->getSuccessor(0);
1494     A_ExitInsn->setSuccessor(0, B_Header);
1495   } else
1496     A_ExitInsn->setSuccessor(1, B_Header);
1497
1498   //[*] Update ALoop's exit value using new exit value.
1499   ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
1500   
1501   // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1502   //     original loop's preheader. Add incoming PHINode values from
1503   //     ALoop's exiting block. Update BLoop header's domiantor info.
1504
1505   // Collect inverse map of Header PHINodes.
1506   DenseMap<Value *, Value *> InverseMap;
1507   for (BasicBlock::iterator BI = L->getHeader()->begin(), 
1508          BE = L->getHeader()->end(); BI != BE; ++BI) {
1509     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1510       PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1511       InverseMap[PNClone] = PN;
1512     } else
1513       break;
1514   }
1515
1516   for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1517        BI != BE; ++BI) {
1518     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1519       // Remove incoming value from original preheader.
1520       PN->removeIncomingValue(Preheader);
1521
1522       // Add incoming value from A_ExitingBlock.
1523       if (PN == B_IndVar)
1524         PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
1525       else { 
1526         PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
1527         Value *V2 = NULL;
1528         // If loop header is also loop exiting block then
1529         // OrigPN is incoming value for B loop header.
1530         if (A_ExitingBlock == L->getHeader())
1531           V2 = OrigPN;
1532         else
1533           V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1534         PN->addIncoming(V2, A_ExitingBlock);
1535       }
1536     } else
1537       break;
1538   }
1539   DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1540   DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
1541   
1542   // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1543   //     block. Remove incoming PHINode values from ALoop's exiting block.
1544   //     Add new incoming values from BLoop's incoming exiting value.
1545   //     Update BLoop exit block's dominator info..
1546   BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1547   for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
1548        BI != BE; ++BI) {
1549     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1550       PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)], 
1551                                                             B_ExitingBlock);
1552       PN->removeIncomingValue(A_ExitingBlock);
1553     } else
1554       break;
1555   }
1556
1557   DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1558   DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
1559
1560   //[*] Split ALoop's exit edge. This creates a new block which
1561   //    serves two purposes. First one is to hold PHINode defnitions
1562   //    to ensure that ALoop's LCSSA form. Second use it to act
1563   //    as a preheader for BLoop.
1564   BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
1565
1566   //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1567   //    in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1568   for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1569       BI != BE; ++BI) {
1570     if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1571       Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
1572       PHINode *newPHI = PHINode::Create(PN->getType(), PN->getName());
1573       newPHI->addIncoming(V1, A_ExitingBlock);
1574       A_ExitBlock->getInstList().push_front(newPHI);
1575       PN->removeIncomingValue(A_ExitBlock);
1576       PN->addIncoming(newPHI, A_ExitBlock);
1577     } else
1578       break;
1579   }
1580
1581   //[*] Eliminate split condition's inactive branch from ALoop.
1582   BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1583   BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
1584   BasicBlock *A_InactiveBranch = NULL;
1585   BasicBlock *A_ActiveBranch = NULL;
1586   if (SD.UseTrueBranchFirst) {
1587     A_ActiveBranch = A_BR->getSuccessor(0);
1588     A_InactiveBranch = A_BR->getSuccessor(1);
1589   } else {
1590     A_ActiveBranch = A_BR->getSuccessor(1);
1591     A_InactiveBranch = A_BR->getSuccessor(0);
1592   }
1593   A_BR->setUnconditionalDest(A_ActiveBranch);
1594   removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1595
1596   //[*] Eliminate split condition's inactive branch in from BLoop.
1597   BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1598   BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
1599   BasicBlock *B_InactiveBranch = NULL;
1600   BasicBlock *B_ActiveBranch = NULL;
1601   if (SD.UseTrueBranchFirst) {
1602     B_ActiveBranch = B_BR->getSuccessor(1);
1603     B_InactiveBranch = B_BR->getSuccessor(0);
1604   } else {
1605     B_ActiveBranch = B_BR->getSuccessor(0);
1606     B_InactiveBranch = B_BR->getSuccessor(1);
1607   }
1608   B_BR->setUnconditionalDest(B_ActiveBranch);
1609   removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1610
1611   BasicBlock *A_Header = L->getHeader();
1612   if (A_ExitingBlock == A_Header)
1613     return true;
1614
1615   //[*] Move exit condition into split condition block to avoid
1616   //    executing dead loop iteration.
1617   ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1618   Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
1619   ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
1620
1621   moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
1622                     cast<ICmpInst>(SD.SplitCondition), IndVar, IndVarIncrement, 
1623                     ALoop);
1624
1625   moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
1626                     B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
1627
1628   return true;
1629 }
1630
1631 // moveExitCondition - Move exit condition EC into split condition block CondBB.
1632 void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
1633                                        BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
1634                                        PHINode *IV, Instruction *IVAdd, Loop *LP) {
1635
1636   BasicBlock *ExitingBB = EC->getParent();
1637   Instruction *CurrentBR = CondBB->getTerminator();
1638
1639   // Move exit condition into split condition block.
1640   EC->moveBefore(CurrentBR);
1641   EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
1642
1643   // Move exiting block's branch into split condition block. Update its branch
1644   // destination.
1645   BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
1646   ExitingBR->moveBefore(CurrentBR);
1647   BasicBlock *OrigDestBB = NULL;
1648   if (ExitingBR->getSuccessor(0) == ExitBB) {
1649     OrigDestBB = ExitingBR->getSuccessor(1);
1650     ExitingBR->setSuccessor(1, ActiveBB);
1651   }
1652   else {
1653     OrigDestBB = ExitingBR->getSuccessor(0);
1654     ExitingBR->setSuccessor(0, ActiveBB);
1655   }
1656     
1657   // Remove split condition and current split condition branch.
1658   SC->eraseFromParent();
1659   CurrentBR->eraseFromParent();
1660
1661   // Connect exiting block to original destination.
1662   BranchInst::Create(OrigDestBB, ExitingBB);
1663
1664   // Update PHINodes
1665   updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd, LP);
1666
1667   // Fix dominator info.
1668   // ExitBB is now dominated by CondBB
1669   DT->changeImmediateDominator(ExitBB, CondBB);
1670   DF->changeImmediateDominator(ExitBB, CondBB, DT);
1671   
1672   // Basicblocks dominated by ActiveBB may have ExitingBB or
1673   // a basic block outside the loop in their DF list. If so,
1674   // replace it with CondBB.
1675   DomTreeNode *Node = DT->getNode(ActiveBB);
1676   for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
1677        DI != DE; ++DI) {
1678     BasicBlock *BB = DI->getBlock();
1679     DominanceFrontier::iterator BBDF = DF->find(BB);
1680     DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1681     DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1682     while (DomSetI != DomSetE) {
1683       DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1684       ++DomSetI;
1685       BasicBlock *DFBB = *CurrentItr;
1686       if (DFBB == ExitingBB || !L->contains(DFBB)) {
1687         BBDF->second.erase(DFBB);
1688         BBDF->second.insert(CondBB);
1689       }
1690     }
1691   }
1692 }
1693
1694 /// updatePHINodes - CFG has been changed. 
1695 /// Before 
1696 ///   - ExitBB's single predecessor was Latch
1697 ///   - Latch's second successor was Header
1698 /// Now
1699 ///   - ExitBB's single predecessor is Header
1700 ///   - Latch's one and only successor is Header
1701 ///
1702 /// Update ExitBB PHINodes' to reflect this change.
1703 void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch, 
1704                                     BasicBlock *Header,
1705                                     PHINode *IV, Instruction *IVIncrement,
1706                                     Loop *LP) {
1707
1708   for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end(); 
1709        BI != BE; ) {
1710     PHINode *PN = dyn_cast<PHINode>(BI);
1711     ++BI;
1712     if (!PN)
1713       break;
1714
1715     Value *V = PN->getIncomingValueForBlock(Latch);
1716     if (PHINode *PHV = dyn_cast<PHINode>(V)) {
1717       // PHV is in Latch. PHV has one use is in ExitBB PHINode. And one use
1718       // in Header which is new incoming value for PN.
1719       Value *NewV = NULL;
1720       for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end(); 
1721            UI != E; ++UI) 
1722         if (PHINode *U = dyn_cast<PHINode>(*UI)) 
1723           if (LP->contains(U->getParent())) {
1724             NewV = U;
1725             break;
1726           }
1727
1728       // Add incoming value from header only if PN has any use inside the loop.
1729       if (NewV)
1730         PN->addIncoming(NewV, Header);
1731
1732     } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
1733       // If this instruction is IVIncrement then IV is new incoming value 
1734       // from header otherwise this instruction must be incoming value from 
1735       // header because loop is in LCSSA form.
1736       if (PHI == IVIncrement)
1737         PN->addIncoming(IV, Header);
1738       else
1739         PN->addIncoming(V, Header);
1740     } else
1741       // Otherwise this is an incoming value from header because loop is in 
1742       // LCSSA form.
1743       PN->addIncoming(V, Header);
1744     
1745     // Remove incoming value from Latch.
1746     PN->removeIncomingValue(Latch);
1747   }
1748 }