1 //===- LoopIndexSplit.cpp - Loop Index Splitting Pass ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements Loop Index Splitting Pass.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "loop-index-split"
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"
28 STATISTIC(NumIndexSplit, "Number of loops index split");
32 class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
35 static char ID; // Pass ID, replacement for typeid
36 LoopIndexSplit() : LoopPass((intptr_t)&ID) {}
38 // Index split Loop L. Return true if loop is split.
39 bool runOnLoop(Loop *L, LPPassManager &LPM);
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>();
60 SplitInfo() : SplitValue(NULL), SplitCondition(NULL),
61 UseTrueBranchFirst(true), A_ExitValue(NULL),
64 // Induction variable's range is split at this value.
67 // This instruction compares IndVar against SplitValue.
68 Instruction *SplitCondition;
70 // True if after loop index split, first loop will execute split condition's
72 bool UseTrueBranchFirst;
74 // Exit value for first loop after loop split.
77 // Start value for second loop after loop split.
83 SplitCondition = NULL;
84 UseTrueBranchFirst = true;
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
97 bool safeICmpInst(ICmpInst *CI, SplitInfo &SD);
99 /// Find condition inside a loop that is suitable candidate for index split.
100 void findSplitCondition();
102 /// Find loop's exit condition.
103 void findLoopConditionals();
105 /// Return induction variable associated with value V.
106 void findIndVar(Value *V, Loop *L);
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);
115 void updateLoopBounds(ICmpInst *CI);
116 /// updateLoopIterationSpace - Current loop body is covered by an AND
117 /// instruction whose operands compares induction variables with loop
118 /// invariants. If possible, hoist this check outside the loop by
119 /// updating appropriate start and end values for induction variable.
120 bool updateLoopIterationSpace(SplitInfo &SD);
122 /// If loop header includes loop variant instruction operands then
123 /// this loop may not be eliminated.
124 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
126 /// If Exiting block includes loop variant instructions then this
127 /// loop may not be eliminated.
128 bool safeExitingBlock(SplitInfo &SD, BasicBlock *BB);
130 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
131 /// This routine is used to remove split condition's dead branch, dominated by
132 /// DeadBB. LiveBB dominates split conidition's other branch.
133 void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
135 /// safeSplitCondition - Return true if it is possible to
136 /// split loop using given split condition.
137 bool safeSplitCondition(SplitInfo &SD);
139 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
140 /// based on split value.
141 void calculateLoopBounds(SplitInfo &SD);
143 /// updatePHINodes - CFG has been changed.
145 /// - ExitBB's single predecessor was Latch
146 /// - Latch's second successor was Header
148 /// - ExitBB's single predecessor was Header
149 /// - Latch's one and only successor was Header
151 /// Update ExitBB PHINodes' to reflect this change.
152 void updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
154 PHINode *IV, Instruction *IVIncrement, Loop *LP);
156 /// moveExitCondition - Move exit condition EC into split condition block CondBB.
157 void moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
158 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
159 PHINode *IV, Instruction *IVAdd, Loop *LP);
161 /// splitLoop - Split current loop L in two loops using split information
162 /// SD. Update dominator information. Maintain LCSSA form.
163 bool splitLoop(SplitInfo &SD);
167 IndVarIncrement = NULL;
168 ExitCondition = NULL;
182 DominanceFrontier *DF;
183 SmallVector<SplitInfo, 4> SplitData;
185 // Induction variable whose range is being split by this transformation.
187 Instruction *IndVarIncrement;
189 // Loop exit condition.
190 ICmpInst *ExitCondition;
192 // Induction variable's initial value.
195 // Induction variable's final loop exit value operand number in exit condition..
196 unsigned ExitValueNum;
200 char LoopIndexSplit::ID = 0;
201 static RegisterPass<LoopIndexSplit>
202 X("loop-index-split", "Index Split Loops");
204 LoopPass *llvm::createLoopIndexSplitPass() {
205 return new LoopIndexSplit();
208 // Index split Loop L. Return true if loop is split.
209 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
210 bool Changed = false;
214 // FIXME - Nested loops make dominator info updates tricky.
215 if (!L->getSubLoops().empty())
218 SE = &getAnalysis<ScalarEvolution>();
219 DT = &getAnalysis<DominatorTree>();
220 LI = &getAnalysis<LoopInfo>();
221 DF = &getAnalysis<DominanceFrontier>();
225 findLoopConditionals();
230 findSplitCondition();
232 if (SplitData.empty())
235 // First see if it is possible to eliminate loop itself or not.
236 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin();
237 SI != SplitData.end();) {
239 ICmpInst *CI = dyn_cast<ICmpInst>(SD.SplitCondition);
240 if (SD.SplitCondition->getOpcode() == Instruction::And) {
241 Changed = updateLoopIterationSpace(SD);
244 // If is loop is eliminated then nothing else to do here.
247 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
248 SI = SplitData.erase(Delete_SI);
251 else if (CI && CI->getPredicate() == ICmpInst::ICMP_EQ) {
252 Changed = processOneIterationLoop(SD);
255 // If is loop is eliminated then nothing else to do here.
258 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
259 SI = SplitData.erase(Delete_SI);
265 if (SplitData.empty())
268 // Split most profitiable condition.
269 // FIXME : Implement cost analysis.
270 unsigned MostProfitableSDIndex = 0;
271 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
279 /// Return true if V is a induction variable or induction variable's
280 /// increment for loop L.
281 void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
283 Instruction *I = dyn_cast<Instruction>(V);
287 // Check if I is a phi node from loop header or not.
288 if (PHINode *PN = dyn_cast<PHINode>(V)) {
289 if (PN->getParent() == L->getHeader()) {
295 // Check if I is a add instruction whose one operand is
296 // phi node from loop header and second operand is constant.
297 if (I->getOpcode() != Instruction::Add)
300 Value *Op0 = I->getOperand(0);
301 Value *Op1 = I->getOperand(1);
303 if (PHINode *PN = dyn_cast<PHINode>(Op0))
304 if (PN->getParent() == L->getHeader())
305 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
312 if (PHINode *PN = dyn_cast<PHINode>(Op1))
313 if (PN->getParent() == L->getHeader())
314 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0))
324 // Find loop's exit condition and associated induction variable.
325 void LoopIndexSplit::findLoopConditionals() {
327 BasicBlock *ExitingBlock = NULL;
329 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
332 if (!L->isLoopExit(BB))
342 // If exiting block is neither loop header nor loop latch then this loop is
344 if (ExitingBlock != L->getHeader() && ExitingBlock != L->getLoopLatch())
347 // If exit block's terminator is conditional branch inst then we have found
349 BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
350 if (!BR || BR->isUnconditional())
353 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
358 if (CI->getPredicate() == ICmpInst::ICMP_EQ
359 || CI->getPredicate() == ICmpInst::ICMP_NE)
364 // Exit condition's one operand is loop invariant exit value and second
365 // operand is SCEVAddRecExpr based on induction variable.
366 Value *V0 = CI->getOperand(0);
367 Value *V1 = CI->getOperand(1);
369 SCEVHandle SH0 = SE->getSCEV(V0);
370 SCEVHandle SH1 = SE->getSCEV(V1);
372 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
376 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
382 ExitCondition = NULL;
384 BasicBlock *Preheader = L->getLoopPreheader();
385 StartValue = IndVar->getIncomingValueForBlock(Preheader);
389 /// Find condition inside a loop that is suitable candidate for index split.
390 void LoopIndexSplit::findSplitCondition() {
393 // Check all basic block's terminators.
394 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
399 // If this basic block does not terminate in a conditional branch
400 // then terminator is not a suitable split condition.
401 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
405 if (BR->isUnconditional())
408 if (Instruction *AndI = dyn_cast<Instruction>(BR->getCondition())) {
409 if (AndI->getOpcode() == Instruction::And) {
410 ICmpInst *Op0 = dyn_cast<ICmpInst>(AndI->getOperand(0));
411 ICmpInst *Op1 = dyn_cast<ICmpInst>(AndI->getOperand(1));
416 if (!safeICmpInst(Op0, SD))
419 if (!safeICmpInst(Op1, SD))
422 SD.SplitCondition = AndI;
423 SplitData.push_back(SD);
427 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
428 if (!CI || CI == ExitCondition)
431 if (CI->getPredicate() == ICmpInst::ICMP_NE)
434 // If split condition predicate is GT or GE then first execute
435 // false branch of split condition.
436 if (CI->getPredicate() == ICmpInst::ICMP_UGT
437 || CI->getPredicate() == ICmpInst::ICMP_SGT
438 || CI->getPredicate() == ICmpInst::ICMP_UGE
439 || CI->getPredicate() == ICmpInst::ICMP_SGE)
440 SD.UseTrueBranchFirst = false;
442 // If one operand is loop invariant and second operand is SCEVAddRecExpr
443 // based on induction variable then CI is a candidate split condition.
444 if (safeICmpInst(CI, SD))
445 SplitData.push_back(SD);
449 // safeIcmpInst - CI is considered safe instruction if one of the operand
450 // is SCEVAddRecExpr based on induction variable and other operand is
451 // loop invariant. If CI is safe then populate SplitInfo object SD appropriately
453 bool LoopIndexSplit::safeICmpInst(ICmpInst *CI, SplitInfo &SD) {
455 Value *V0 = CI->getOperand(0);
456 Value *V1 = CI->getOperand(1);
458 SCEVHandle SH0 = SE->getSCEV(V0);
459 SCEVHandle SH1 = SE->getSCEV(V1);
461 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
463 SD.SplitCondition = CI;
464 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
468 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
469 if (IndVarIncrement && IndVarIncrement == Insn)
473 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
475 SD.SplitCondition = CI;
476 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
480 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
481 if (IndVarIncrement && IndVarIncrement == Insn)
489 /// processOneIterationLoop - Current loop L contains compare instruction
490 /// that compares induction variable, IndVar, against loop invariant. If
491 /// entire (i.e. meaningful) loop body is dominated by this compare
492 /// instruction then loop body is executed only once. In such case eliminate
493 /// loop structure surrounding this loop body. For example,
494 /// for (int i = start; i < end; ++i) {
495 /// if ( i == somevalue) {
499 /// can be transformed into
500 /// if (somevalue >= start && somevalue < end) {
504 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
506 BasicBlock *Header = L->getHeader();
508 // First of all, check if SplitCondition dominates entire loop body
511 // If SplitCondition is not in loop header then this loop is not suitable
512 // for this transformation.
513 if (SD.SplitCondition->getParent() != Header)
516 // If loop header includes loop variant instruction operands then
517 // this loop may not be eliminated.
518 if (!safeHeader(SD, Header))
521 // If Exiting block includes loop variant instructions then this
522 // loop may not be eliminated.
523 if (!safeExitingBlock(SD, ExitCondition->getParent()))
526 // Filter loops where split condition's false branch is not empty.
527 if (ExitCondition->getParent() != Header->getTerminator()->getSuccessor(1))
530 // If split condition is not safe then do not process this loop.
532 // for(int i = 0; i < N; i++) {
541 if (!safeSplitCondition(SD))
544 BasicBlock *Latch = L->getLoopLatch();
545 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
551 // Replace index variable with split value in loop body. Loop body is executed
552 // only when index variable is equal to split value.
553 IndVar->replaceAllUsesWith(SD.SplitValue);
555 // Remove Latch to Header edge.
556 BasicBlock *LatchSucc = NULL;
557 Header->removePredecessor(Latch);
558 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
563 BR->setUnconditionalDest(LatchSucc);
565 Instruction *Terminator = Header->getTerminator();
566 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
568 // Replace split condition in header.
570 // SplitCondition : icmp eq i32 IndVar, SplitValue
572 // c1 = icmp uge i32 SplitValue, StartValue
573 // c2 = icmp ult i32 SplitValue, ExitValue
575 bool SignedPredicate = ExitCondition->isSignedPredicate();
576 Instruction *C1 = new ICmpInst(SignedPredicate ?
577 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
578 SD.SplitValue, StartValue, "lisplit",
580 Instruction *C2 = new ICmpInst(SignedPredicate ?
581 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
582 SD.SplitValue, ExitValue, "lisplit",
584 Instruction *NSplitCond = BinaryOperator::CreateAnd(C1, C2, "lisplit",
586 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
587 SD.SplitCondition->eraseFromParent();
589 // Now, clear latch block. Remove instructions that are responsible
590 // to increment induction variable.
591 Instruction *LTerminator = Latch->getTerminator();
592 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
596 if (isa<PHINode>(I) || I == LTerminator)
599 if (I == IndVarIncrement) {
600 // Replace induction variable increment if it is not used outside
602 bool UsedOutsideLoop = false;
603 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
605 if (Instruction *Use = dyn_cast<Instruction>(UI))
606 if (!L->contains(Use->getParent())) {
607 UsedOutsideLoop = true;
611 if (!UsedOutsideLoop) {
612 I->replaceAllUsesWith(ExitValue);
613 I->eraseFromParent();
617 I->replaceAllUsesWith(UndefValue::get(I->getType()));
618 I->eraseFromParent();
622 LPM->deleteLoopFromQueue(L);
624 // Update Dominator Info.
625 // Only CFG change done is to remove Latch to Header edge. This
626 // does not change dominator tree because Latch did not dominate
629 DominanceFrontier::iterator HeaderDF = DF->find(Header);
630 if (HeaderDF != DF->end())
631 DF->removeFromFrontier(HeaderDF, Header);
633 DominanceFrontier::iterator LatchDF = DF->find(Latch);
634 if (LatchDF != DF->end())
635 DF->removeFromFrontier(LatchDF, Header);
640 // If loop header includes loop variant instruction operands then
641 // this loop can not be eliminated. This is used by processOneIterationLoop().
642 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
644 Instruction *Terminator = Header->getTerminator();
645 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
653 // SplitCondition itself is OK.
654 if (I == SD.SplitCondition)
657 // Induction variable is OK.
661 // Induction variable increment is OK.
662 if (I == IndVarIncrement)
665 // Terminator is also harmless.
669 // Otherwise we have a instruction that may not be safe.
676 // If Exiting block includes loop variant instructions then this
677 // loop may not be eliminated. This is used by processOneIterationLoop().
678 bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD,
679 BasicBlock *ExitingBlock) {
681 for (BasicBlock::iterator BI = ExitingBlock->begin(),
682 BE = ExitingBlock->end(); BI != BE; ++BI) {
689 // Induction variable increment is OK.
690 if (IndVarIncrement && IndVarIncrement == I)
693 // Check if I is induction variable increment instruction.
694 if (I->getOpcode() == Instruction::Add) {
696 Value *Op0 = I->getOperand(0);
697 Value *Op1 = I->getOperand(1);
699 ConstantInt *CI = NULL;
701 if ((PN = dyn_cast<PHINode>(Op0))) {
702 if ((CI = dyn_cast<ConstantInt>(Op1)))
704 if (!IndVarIncrement && PN == IndVar)
706 // else this is another loop induction variable
710 if ((PN = dyn_cast<PHINode>(Op1))) {
711 if ((CI = dyn_cast<ConstantInt>(Op0)))
713 if (!IndVarIncrement && PN == IndVar)
715 // else this is another loop induction variable
721 // I is an Exit condition if next instruction is block terminator.
722 // Exit condition is OK if it compares loop invariant exit value,
723 // which is checked below.
724 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
725 if (EC == ExitCondition)
729 if (I == ExitingBlock->getTerminator())
732 // Otherwise we have instruction that may not be safe.
736 // We could not find any reason to consider ExitingBlock unsafe.
740 void LoopIndexSplit::updateLoopBounds(ICmpInst *CI) {
742 Value *V0 = CI->getOperand(0);
743 Value *V1 = CI->getOperand(1);
746 SCEVHandle SH0 = SE->getSCEV(V0);
748 if (SH0->isLoopInvariant(L))
753 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SGT
754 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGT
755 || ExitCondition->getPredicate() == ICmpInst::ICMP_SGE
756 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGE) {
757 ExitCondition->swapOperands();
766 Value *UB = ExitCondition->getOperand(ExitValueNum);
767 const Type *Ty = NV->getType();
768 bool Sign = ExitCondition->isSignedPredicate();
769 BasicBlock *Preheader = L->getLoopPreheader();
770 Instruction *PHTerminator = Preheader->getTerminator();
772 assert (NV && "Unexpected value");
774 switch (CI->getPredicate()) {
775 case ICmpInst::ICMP_ULE:
776 case ICmpInst::ICMP_SLE:
777 // for (i = LB; i < UB; ++i)
778 // if (i <= NV && ...)
781 // is transformed into
782 // NUB = min (NV+1, UB)
783 // for (i = LB; i < NUB ; ++i)
786 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLT
787 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULT) {
788 Value *A = BinaryOperator::CreateAdd(NV, ConstantInt::get(Ty, 1, Sign),
789 "lsplit.add", PHTerminator);
790 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
791 A, UB,"lsplit,c", PHTerminator);
792 NUB = SelectInst::Create(C, A, UB, "lsplit.nub", PHTerminator);
795 // for (i = LB; i <= UB; ++i)
796 // if (i <= NV && ...)
799 // is transformed into
800 // NUB = min (NV, UB)
801 // for (i = LB; i <= NUB ; ++i)
804 else if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLE
805 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULE) {
806 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
807 NV, UB, "lsplit.c", PHTerminator);
808 NUB = SelectInst::Create(C, NV, UB, "lsplit.nub", PHTerminator);
811 case ICmpInst::ICMP_ULT:
812 case ICmpInst::ICMP_SLT:
813 // for (i = LB; i < UB; ++i)
814 // if (i < NV && ...)
817 // is transformed into
818 // NUB = min (NV, UB)
819 // for (i = LB; i < NUB ; ++i)
822 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLT
823 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULT) {
824 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
825 NV, UB, "lsplit.c", PHTerminator);
826 NUB = SelectInst::Create(C, NV, UB, "lsplit.nub", PHTerminator);
829 // for (i = LB; i <= UB; ++i)
830 // if (i < NV && ...)
833 // is transformed into
834 // NUB = min (NV -1 , UB)
835 // for (i = LB; i <= NUB ; ++i)
838 else if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLE
839 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULE) {
840 Value *S = BinaryOperator::CreateSub(NV, ConstantInt::get(Ty, 1, Sign),
841 "lsplit.add", PHTerminator);
842 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
843 S, UB, "lsplit.c", PHTerminator);
844 NUB = SelectInst::Create(C, S, UB, "lsplit.nub", PHTerminator);
847 case ICmpInst::ICMP_UGE:
848 case ICmpInst::ICMP_SGE:
849 // for (i = LB; i (< or <=) UB; ++i)
850 // if (i >= NV && ...)
853 // is transformed into
854 // NLB = max (NV, LB)
855 // for (i = NLB; i (< or <=) UB ; ++i)
859 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
860 NV, StartValue, "lsplit.c", PHTerminator);
861 NLB = SelectInst::Create(C, StartValue, NV, "lsplit.nlb", PHTerminator);
864 case ICmpInst::ICMP_UGT:
865 case ICmpInst::ICMP_SGT:
866 // for (i = LB; i (< or <=) UB; ++i)
867 // if (i > NV && ...)
870 // is transformed into
871 // NLB = max (NV+1, LB)
872 // for (i = NLB; i (< or <=) UB ; ++i)
876 Value *A = BinaryOperator::CreateAdd(NV, ConstantInt::get(Ty, 1, Sign),
877 "lsplit.add", PHTerminator);
878 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
879 A, StartValue, "lsplit.c", PHTerminator);
880 NLB = SelectInst::Create(C, StartValue, A, "lsplit.nlb", PHTerminator);
884 assert ( 0 && "Unexpected split condition predicate");
888 unsigned i = IndVar->getBasicBlockIndex(Preheader);
889 IndVar->setIncomingValue(i, NLB);
893 ExitCondition->setOperand(ExitValueNum, NUB);
896 /// updateLoopIterationSpace - Current loop body is covered by an AND
897 /// instruction whose operands compares induction variables with loop
898 /// invariants. If possible, hoist this check outside the loop by
899 /// updating appropriate start and end values for induction variable.
900 bool LoopIndexSplit::updateLoopIterationSpace(SplitInfo &SD) {
901 BasicBlock *Header = L->getHeader();
902 BasicBlock *ExitingBlock = ExitCondition->getParent();
903 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
905 ICmpInst *Op0 = cast<ICmpInst>(SD.SplitCondition->getOperand(0));
906 ICmpInst *Op1 = cast<ICmpInst>(SD.SplitCondition->getOperand(1));
908 if (Op0->getPredicate() == ICmpInst::ICMP_EQ
909 || Op0->getPredicate() == ICmpInst::ICMP_NE
910 || Op0->getPredicate() == ICmpInst::ICMP_EQ
911 || Op0->getPredicate() == ICmpInst::ICMP_NE)
914 // Check if SplitCondition dominates entire loop body
917 // If SplitCondition is not in loop header then this loop is not suitable
918 // for this transformation.
919 if (SD.SplitCondition->getParent() != Header)
922 // If loop header includes loop variant instruction operands then
923 // this loop may not be eliminated.
924 Instruction *Terminator = Header->getTerminator();
925 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
933 // SplitCondition itself is OK.
934 if (I == SD.SplitCondition)
936 if (I == Op0 || I == Op1)
939 // Induction variable is OK.
943 // Induction variable increment is OK.
944 if (I == IndVarIncrement)
947 // Terminator is also harmless.
951 // Otherwise we have a instruction that may not be safe.
955 // If Exiting block includes loop variant instructions then this
956 // loop may not be eliminated.
957 if (!safeExitingBlock(SD, ExitCondition->getParent()))
960 // Verify that loop exiting block has only two predecessor, where one predecessor
961 // is split condition block. The other predecessor will become exiting block's
962 // dominator after CFG is updated. TODO : Handle CFG's where exiting block has
963 // more then two predecessors. This requires extra work in updating dominator
965 BasicBlock *ExitingBBPred = NULL;
966 for (pred_iterator PI = pred_begin(ExitingBlock), PE = pred_end(ExitingBlock);
968 BasicBlock *BB = *PI;
969 if (SplitCondBlock == BB)
977 // Update loop bounds to absorb Op0 check.
978 updateLoopBounds(Op0);
979 // Update loop bounds to absorb Op1 check.
980 updateLoopBounds(Op1);
984 // Unconditionally connect split block to its remaining successor.
985 BranchInst *SplitTerminator =
986 cast<BranchInst>(SplitCondBlock->getTerminator());
987 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
988 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
989 if (Succ0 == ExitCondition->getParent())
990 SplitTerminator->setUnconditionalDest(Succ1);
992 SplitTerminator->setUnconditionalDest(Succ0);
994 // Remove split condition.
995 SD.SplitCondition->eraseFromParent();
996 if (Op0->use_begin() == Op0->use_end())
997 Op0->eraseFromParent();
998 if (Op1->use_begin() == Op1->use_end())
999 Op1->eraseFromParent();
1001 BranchInst *ExitInsn =
1002 dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1003 assert (ExitInsn && "Unable to find suitable loop exit branch");
1004 BasicBlock *ExitBlock = ExitInsn->getSuccessor(1);
1005 if (L->contains(ExitBlock))
1006 ExitBlock = ExitInsn->getSuccessor(0);
1008 // Update domiantor info. Now, ExitingBlock has only one predecessor,
1009 // ExitingBBPred, and it is ExitingBlock's immediate domiantor.
1010 DT->changeImmediateDominator(ExitingBlock, ExitingBBPred);
1012 // If ExitingBlock is a member of loop BB's DF list then replace it with
1013 // loop header and exit block.
1014 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
1016 BasicBlock *BB = *I;
1017 if (BB == Header || BB == ExitingBlock)
1019 DominanceFrontier::iterator BBDF = DF->find(BB);
1020 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1021 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1022 while (DomSetI != DomSetE) {
1023 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1025 BasicBlock *DFBB = *CurrentItr;
1026 if (DFBB == ExitingBlock) {
1027 BBDF->second.erase(DFBB);
1028 BBDF->second.insert(Header);
1029 if (Header != ExitingBlock)
1030 BBDF->second.insert(ExitBlock);
1039 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
1040 /// This routine is used to remove split condition's dead branch, dominated by
1041 /// DeadBB. LiveBB dominates split conidition's other branch.
1042 void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
1043 BasicBlock *LiveBB) {
1045 // First update DeadBB's dominance frontier.
1046 SmallVector<BasicBlock *, 8> FrontierBBs;
1047 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
1048 if (DeadBBDF != DF->end()) {
1049 SmallVector<BasicBlock *, 8> PredBlocks;
1051 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
1052 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
1053 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
1054 BasicBlock *FrontierBB = *DeadBBSetI;
1055 FrontierBBs.push_back(FrontierBB);
1057 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
1059 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
1061 BasicBlock *P = *PI;
1062 if (P == DeadBB || DT->dominates(DeadBB, P))
1063 PredBlocks.push_back(P);
1066 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
1067 FBI != FBE; ++FBI) {
1068 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
1069 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
1070 PE = PredBlocks.end(); PI != PE; ++PI) {
1071 BasicBlock *P = *PI;
1072 PN->removeIncomingValue(P);
1081 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
1082 SmallVector<BasicBlock *, 32> WorkList;
1083 DomTreeNode *DN = DT->getNode(DeadBB);
1084 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
1085 E = df_end(DN); DI != E; ++DI) {
1086 BasicBlock *BB = DI->getBlock();
1087 WorkList.push_back(BB);
1088 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
1091 while (!WorkList.empty()) {
1092 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
1093 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
1095 Instruction *I = BBI;
1097 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1098 I->eraseFromParent();
1100 LPM->deleteSimpleAnalysisValue(BB, LP);
1102 DF->removeBlock(BB);
1103 LI->removeBlock(BB);
1104 BB->eraseFromParent();
1107 // Update Frontier BBs' dominator info.
1108 while (!FrontierBBs.empty()) {
1109 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
1110 BasicBlock *NewDominator = FBB->getSinglePredecessor();
1111 if (!NewDominator) {
1112 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
1115 if (NewDominator != LiveBB) {
1116 for(; PI != PE; ++PI) {
1117 BasicBlock *P = *PI;
1119 NewDominator = LiveBB;
1122 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
1126 assert (NewDominator && "Unable to fix dominator info.");
1127 DT->changeImmediateDominator(FBB, NewDominator);
1128 DF->changeImmediateDominator(FBB, NewDominator, DT);
1133 /// safeSplitCondition - Return true if it is possible to
1134 /// split loop using given split condition.
1135 bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
1137 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
1138 BasicBlock *Latch = L->getLoopLatch();
1139 BranchInst *SplitTerminator =
1140 cast<BranchInst>(SplitCondBlock->getTerminator());
1141 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1142 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1144 // If split block does not dominate the latch then this is not a diamond.
1145 // Such loop may not benefit from index split.
1146 if (!DT->dominates(SplitCondBlock, Latch))
1149 // Finally this split condition is safe only if merge point for
1150 // split condition branch is loop latch. This check along with previous
1151 // check, to ensure that exit condition is in either loop latch or header,
1152 // filters all loops with non-empty loop body between merge point
1153 // and exit condition.
1154 DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
1155 assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
1156 if (Succ0DF->second.count(Latch))
1159 DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
1160 assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
1161 if (Succ1DF->second.count(Latch))
1167 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
1168 /// based on split value.
1169 void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
1171 ICmpInst *SC = cast<ICmpInst>(SD.SplitCondition);
1172 ICmpInst::Predicate SP = SC->getPredicate();
1173 const Type *Ty = SD.SplitValue->getType();
1174 bool Sign = ExitCondition->isSignedPredicate();
1175 BasicBlock *Preheader = L->getLoopPreheader();
1176 Instruction *PHTerminator = Preheader->getTerminator();
1178 // Initially use split value as upper loop bound for first loop and lower loop
1179 // bound for second loop.
1180 Value *AEV = SD.SplitValue;
1181 Value *BSV = SD.SplitValue;
1183 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SGT
1184 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGT
1185 || ExitCondition->getPredicate() == ICmpInst::ICMP_SGE
1186 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGE) {
1187 ExitCondition->swapOperands();
1194 switch (ExitCondition->getPredicate()) {
1195 case ICmpInst::ICMP_SGT:
1196 case ICmpInst::ICMP_UGT:
1197 case ICmpInst::ICMP_SGE:
1198 case ICmpInst::ICMP_UGE:
1200 assert (0 && "Unexpected exit condition predicate");
1202 case ICmpInst::ICMP_SLT:
1203 case ICmpInst::ICMP_ULT:
1206 case ICmpInst::ICMP_SLT:
1207 case ICmpInst::ICMP_ULT:
1209 // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
1211 // is transformed into
1213 // for (i = LB; i < min(UB, AEV); ++i)
1215 // for (i = max(LB, BSV); i < UB; ++i);
1218 case ICmpInst::ICMP_SLE:
1219 case ICmpInst::ICMP_ULE:
1222 // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
1224 // is transformed into
1228 // for (i = LB; i < min(UB, AEV); ++i)
1230 // for (i = max(LB, BSV); i < UB; ++i)
1232 BSV = BinaryOperator::CreateAdd(SD.SplitValue,
1233 ConstantInt::get(Ty, 1, Sign),
1234 "lsplit.add", PHTerminator);
1238 case ICmpInst::ICMP_SGE:
1239 case ICmpInst::ICMP_UGE:
1241 // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
1243 // is transformed into
1245 // for (i = LB; i < min(UB, AEV); ++i)
1247 // for (i = max(BSV, LB); i < UB; ++i)
1250 case ICmpInst::ICMP_SGT:
1251 case ICmpInst::ICMP_UGT:
1254 // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
1256 // is transformed into
1258 // BSV = AEV = SV + 1
1259 // for (i = LB; i < min(UB, AEV); ++i)
1261 // for (i = max(LB, BSV); i < UB; ++i)
1263 BSV = BinaryOperator::CreateAdd(SD.SplitValue,
1264 ConstantInt::get(Ty, 1, Sign),
1265 "lsplit.add", PHTerminator);
1270 assert (0 && "Unexpected split condition predicate");
1272 } // end switch (SP)
1275 case ICmpInst::ICMP_SLE:
1276 case ICmpInst::ICMP_ULE:
1279 case ICmpInst::ICMP_SLT:
1280 case ICmpInst::ICMP_ULT:
1282 // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
1284 // is transformed into
1287 // for (i = LB; i <= min(UB, AEV); ++i)
1289 // for (i = max(LB, BSV); i <= UB; ++i)
1291 AEV = BinaryOperator::CreateSub(SD.SplitValue,
1292 ConstantInt::get(Ty, 1, Sign),
1293 "lsplit.sub", PHTerminator);
1295 case ICmpInst::ICMP_SLE:
1296 case ICmpInst::ICMP_ULE:
1298 // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
1300 // is transformed into
1303 // for (i = LB; i <= min(UB, AEV); ++i)
1305 // for (i = max(LB, BSV); i <= UB; ++i)
1307 BSV = BinaryOperator::CreateAdd(SD.SplitValue,
1308 ConstantInt::get(Ty, 1, Sign),
1309 "lsplit.add", PHTerminator);
1311 case ICmpInst::ICMP_SGT:
1312 case ICmpInst::ICMP_UGT:
1314 // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
1316 // is transformed into
1319 // for (i = LB; i <= min(AEV, UB); ++i)
1321 // for (i = max(LB, BSV); i <= UB; ++i)
1323 BSV = BinaryOperator::CreateAdd(SD.SplitValue,
1324 ConstantInt::get(Ty, 1, Sign),
1325 "lsplit.add", PHTerminator);
1327 case ICmpInst::ICMP_SGE:
1328 case ICmpInst::ICMP_UGE:
1331 // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
1333 // is transformed into
1336 // for (i = LB; i <= min(AEV, UB); ++i)
1338 // for (i = max(LB, BSV); i <= UB; ++i)
1340 AEV = BinaryOperator::CreateSub(SD.SplitValue,
1341 ConstantInt::get(Ty, 1, Sign),
1342 "lsplit.sub", PHTerminator);
1345 assert (0 && "Unexpected split condition predicate");
1347 } // end switch (SP)
1352 // Calculate ALoop induction variable's new exiting value and
1353 // BLoop induction variable's new starting value. Calculuate these
1354 // values in original loop's preheader.
1355 // A_ExitValue = min(SplitValue, OrignalLoopExitValue)
1356 // B_StartValue = max(SplitValue, OriginalLoopStartValue)
1357 Instruction *InsertPt = L->getHeader()->getFirstNonPHI();
1359 // If ExitValue operand is also defined in Loop header then
1360 // insert new ExitValue after this operand definition.
1361 if (Instruction *EVN =
1362 dyn_cast<Instruction>(ExitCondition->getOperand(ExitValueNum))) {
1363 if (!isa<PHINode>(EVN))
1364 if (InsertPt->getParent() == EVN->getParent()) {
1365 BasicBlock::iterator LHBI = L->getHeader()->begin();
1366 BasicBlock::iterator LHBE = L->getHeader()->end();
1367 for(;LHBI != LHBE; ++LHBI) {
1368 Instruction *I = LHBI;
1375 Value *C1 = new ICmpInst(Sign ?
1376 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1378 ExitCondition->getOperand(ExitValueNum),
1379 "lsplit.ev", InsertPt);
1381 SD.A_ExitValue = SelectInst::Create(C1, AEV,
1382 ExitCondition->getOperand(ExitValueNum),
1383 "lsplit.ev", InsertPt);
1385 Value *C2 = new ICmpInst(Sign ?
1386 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1387 BSV, StartValue, "lsplit.sv",
1389 SD.B_StartValue = SelectInst::Create(C2, StartValue, BSV,
1390 "lsplit.sv", PHTerminator);
1393 /// splitLoop - Split current loop L in two loops using split information
1394 /// SD. Update dominator information. Maintain LCSSA form.
1395 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
1397 if (!safeSplitCondition(SD))
1400 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
1402 // Unable to handle triange loops at the moment.
1403 // In triangle loop, split condition is in header and one of the
1404 // the split destination is loop latch. If split condition is EQ
1405 // then such loops are already handle in processOneIterationLoop().
1406 BasicBlock *Latch = L->getLoopLatch();
1407 BranchInst *SplitTerminator =
1408 cast<BranchInst>(SplitCondBlock->getTerminator());
1409 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1410 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1411 if (L->getHeader() == SplitCondBlock
1412 && (Latch == Succ0 || Latch == Succ1))
1415 // If split condition branches heads do not have single predecessor,
1416 // SplitCondBlock, then is not possible to remove inactive branch.
1417 if (!Succ0->getSinglePredecessor() || !Succ1->getSinglePredecessor())
1420 // If Exiting block includes loop variant instructions then this
1421 // loop may not be split safely.
1422 if (!safeExitingBlock(SD, ExitCondition->getParent()))
1425 // After loop is cloned there are two loops.
1427 // First loop, referred as ALoop, executes first part of loop's iteration
1428 // space split. Second loop, referred as BLoop, executes remaining
1429 // part of loop's iteration space.
1431 // ALoop's exit edge enters BLoop's header through a forwarding block which
1432 // acts as a BLoop's preheader.
1433 BasicBlock *Preheader = L->getLoopPreheader();
1435 // Calculate ALoop induction variable's new exiting value and
1436 // BLoop induction variable's new starting value.
1437 calculateLoopBounds(SD);
1440 DenseMap<const Value *, Value *> ValueMap;
1441 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
1443 BasicBlock *B_Header = BLoop->getHeader();
1445 //[*] ALoop's exiting edge BLoop's header.
1446 // ALoop's original exit block becomes BLoop's exit block.
1447 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1448 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1449 BranchInst *A_ExitInsn =
1450 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1451 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1452 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1453 if (L->contains(B_ExitBlock)) {
1454 B_ExitBlock = A_ExitInsn->getSuccessor(0);
1455 A_ExitInsn->setSuccessor(0, B_Header);
1457 A_ExitInsn->setSuccessor(1, B_Header);
1459 //[*] Update ALoop's exit value using new exit value.
1460 ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
1462 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1463 // original loop's preheader. Add incoming PHINode values from
1464 // ALoop's exiting block. Update BLoop header's domiantor info.
1466 // Collect inverse map of Header PHINodes.
1467 DenseMap<Value *, Value *> InverseMap;
1468 for (BasicBlock::iterator BI = L->getHeader()->begin(),
1469 BE = L->getHeader()->end(); BI != BE; ++BI) {
1470 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1471 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1472 InverseMap[PNClone] = PN;
1477 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1479 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1480 // Remove incoming value from original preheader.
1481 PN->removeIncomingValue(Preheader);
1483 // Add incoming value from A_ExitingBlock.
1485 PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
1487 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
1489 // If loop header is also loop exiting block then
1490 // OrigPN is incoming value for B loop header.
1491 if (A_ExitingBlock == L->getHeader())
1494 V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1495 PN->addIncoming(V2, A_ExitingBlock);
1500 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1501 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
1503 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1504 // block. Remove incoming PHINode values from ALoop's exiting block.
1505 // Add new incoming values from BLoop's incoming exiting value.
1506 // Update BLoop exit block's dominator info..
1507 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1508 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
1510 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1511 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1513 PN->removeIncomingValue(A_ExitingBlock);
1518 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1519 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
1521 //[*] Split ALoop's exit edge. This creates a new block which
1522 // serves two purposes. First one is to hold PHINode defnitions
1523 // to ensure that ALoop's LCSSA form. Second use it to act
1524 // as a preheader for BLoop.
1525 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
1527 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1528 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1529 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1531 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1532 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
1533 PHINode *newPHI = PHINode::Create(PN->getType(), PN->getName());
1534 newPHI->addIncoming(V1, A_ExitingBlock);
1535 A_ExitBlock->getInstList().push_front(newPHI);
1536 PN->removeIncomingValue(A_ExitBlock);
1537 PN->addIncoming(newPHI, A_ExitBlock);
1542 //[*] Eliminate split condition's inactive branch from ALoop.
1543 BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1544 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
1545 BasicBlock *A_InactiveBranch = NULL;
1546 BasicBlock *A_ActiveBranch = NULL;
1547 if (SD.UseTrueBranchFirst) {
1548 A_ActiveBranch = A_BR->getSuccessor(0);
1549 A_InactiveBranch = A_BR->getSuccessor(1);
1551 A_ActiveBranch = A_BR->getSuccessor(1);
1552 A_InactiveBranch = A_BR->getSuccessor(0);
1554 A_BR->setUnconditionalDest(A_ActiveBranch);
1555 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1557 //[*] Eliminate split condition's inactive branch in from BLoop.
1558 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1559 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
1560 BasicBlock *B_InactiveBranch = NULL;
1561 BasicBlock *B_ActiveBranch = NULL;
1562 if (SD.UseTrueBranchFirst) {
1563 B_ActiveBranch = B_BR->getSuccessor(1);
1564 B_InactiveBranch = B_BR->getSuccessor(0);
1566 B_ActiveBranch = B_BR->getSuccessor(0);
1567 B_InactiveBranch = B_BR->getSuccessor(1);
1569 B_BR->setUnconditionalDest(B_ActiveBranch);
1570 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1572 BasicBlock *A_Header = L->getHeader();
1573 if (A_ExitingBlock == A_Header)
1576 //[*] Move exit condition into split condition block to avoid
1577 // executing dead loop iteration.
1578 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1579 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
1580 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
1582 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
1583 cast<ICmpInst>(SD.SplitCondition), IndVar, IndVarIncrement,
1586 moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
1587 B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
1592 // moveExitCondition - Move exit condition EC into split condition block CondBB.
1593 void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
1594 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
1595 PHINode *IV, Instruction *IVAdd, Loop *LP) {
1597 BasicBlock *ExitingBB = EC->getParent();
1598 Instruction *CurrentBR = CondBB->getTerminator();
1600 // Move exit condition into split condition block.
1601 EC->moveBefore(CurrentBR);
1602 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
1604 // Move exiting block's branch into split condition block. Update its branch
1606 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
1607 ExitingBR->moveBefore(CurrentBR);
1608 BasicBlock *OrigDestBB = NULL;
1609 if (ExitingBR->getSuccessor(0) == ExitBB) {
1610 OrigDestBB = ExitingBR->getSuccessor(1);
1611 ExitingBR->setSuccessor(1, ActiveBB);
1614 OrigDestBB = ExitingBR->getSuccessor(0);
1615 ExitingBR->setSuccessor(0, ActiveBB);
1618 // Remove split condition and current split condition branch.
1619 SC->eraseFromParent();
1620 CurrentBR->eraseFromParent();
1622 // Connect exiting block to original destination.
1623 BranchInst::Create(OrigDestBB, ExitingBB);
1626 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd, LP);
1628 // Fix dominator info.
1629 // ExitBB is now dominated by CondBB
1630 DT->changeImmediateDominator(ExitBB, CondBB);
1631 DF->changeImmediateDominator(ExitBB, CondBB, DT);
1633 // Basicblocks dominated by ActiveBB may have ExitingBB or
1634 // a basic block outside the loop in their DF list. If so,
1635 // replace it with CondBB.
1636 DomTreeNode *Node = DT->getNode(ActiveBB);
1637 for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
1639 BasicBlock *BB = DI->getBlock();
1640 DominanceFrontier::iterator BBDF = DF->find(BB);
1641 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1642 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1643 while (DomSetI != DomSetE) {
1644 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1646 BasicBlock *DFBB = *CurrentItr;
1647 if (DFBB == ExitingBB || !L->contains(DFBB)) {
1648 BBDF->second.erase(DFBB);
1649 BBDF->second.insert(CondBB);
1655 /// updatePHINodes - CFG has been changed.
1657 /// - ExitBB's single predecessor was Latch
1658 /// - Latch's second successor was Header
1660 /// - ExitBB's single predecessor is Header
1661 /// - Latch's one and only successor is Header
1663 /// Update ExitBB PHINodes' to reflect this change.
1664 void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
1666 PHINode *IV, Instruction *IVIncrement,
1669 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
1671 PHINode *PN = dyn_cast<PHINode>(BI);
1676 Value *V = PN->getIncomingValueForBlock(Latch);
1677 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
1678 // PHV is in Latch. PHV has one use is in ExitBB PHINode. And one use
1679 // in Header which is new incoming value for PN.
1681 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
1683 if (PHINode *U = dyn_cast<PHINode>(*UI))
1684 if (LP->contains(U->getParent())) {
1689 // Add incoming value from header only if PN has any use inside the loop.
1691 PN->addIncoming(NewV, Header);
1693 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
1694 // If this instruction is IVIncrement then IV is new incoming value
1695 // from header otherwise this instruction must be incoming value from
1696 // header because loop is in LCSSA form.
1697 if (PHI == IVIncrement)
1698 PN->addIncoming(IV, Header);
1700 PN->addIncoming(V, Header);
1702 // Otherwise this is an incoming value from header because loop is in
1704 PN->addIncoming(V, Header);
1706 // Remove incoming value from Latch.
1707 PN->removeIncomingValue(Latch);