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);
388 // If start value is more then exit value where induction variable
389 // increments by 1 then we are potentially dealing with an infinite loop.
390 // Do not index split this loop.
392 ConstantInt *SV = dyn_cast<ConstantInt>(StartValue);
394 dyn_cast<ConstantInt>(ExitCondition->getOperand(ExitValueNum));
395 if (SV && EV && SV->getSExtValue() > EV->getSExtValue())
396 ExitCondition = NULL;
397 else if (EV && EV->isZero())
398 ExitCondition = NULL;
402 /// Find condition inside a loop that is suitable candidate for index split.
403 void LoopIndexSplit::findSplitCondition() {
406 // Check all basic block's terminators.
407 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
412 // If this basic block does not terminate in a conditional branch
413 // then terminator is not a suitable split condition.
414 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
418 if (BR->isUnconditional())
421 if (Instruction *AndI = dyn_cast<Instruction>(BR->getCondition())) {
422 if (AndI->getOpcode() == Instruction::And) {
423 ICmpInst *Op0 = dyn_cast<ICmpInst>(AndI->getOperand(0));
424 ICmpInst *Op1 = dyn_cast<ICmpInst>(AndI->getOperand(1));
429 if (!safeICmpInst(Op0, SD))
432 if (!safeICmpInst(Op1, SD))
435 SD.SplitCondition = AndI;
436 SplitData.push_back(SD);
440 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
441 if (!CI || CI == ExitCondition)
444 if (CI->getPredicate() == ICmpInst::ICMP_NE)
447 // If split condition predicate is GT or GE then first execute
448 // false branch of split condition.
449 if (CI->getPredicate() == ICmpInst::ICMP_UGT
450 || CI->getPredicate() == ICmpInst::ICMP_SGT
451 || CI->getPredicate() == ICmpInst::ICMP_UGE
452 || CI->getPredicate() == ICmpInst::ICMP_SGE)
453 SD.UseTrueBranchFirst = false;
455 // If one operand is loop invariant and second operand is SCEVAddRecExpr
456 // based on induction variable then CI is a candidate split condition.
457 if (safeICmpInst(CI, SD))
458 SplitData.push_back(SD);
462 // safeIcmpInst - CI is considered safe instruction if one of the operand
463 // is SCEVAddRecExpr based on induction variable and other operand is
464 // loop invariant. If CI is safe then populate SplitInfo object SD appropriately
466 bool LoopIndexSplit::safeICmpInst(ICmpInst *CI, SplitInfo &SD) {
468 Value *V0 = CI->getOperand(0);
469 Value *V1 = CI->getOperand(1);
471 SCEVHandle SH0 = SE->getSCEV(V0);
472 SCEVHandle SH1 = SE->getSCEV(V1);
474 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
476 SD.SplitCondition = CI;
477 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
481 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
482 if (IndVarIncrement && IndVarIncrement == Insn)
486 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
488 SD.SplitCondition = CI;
489 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
493 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
494 if (IndVarIncrement && IndVarIncrement == Insn)
502 /// processOneIterationLoop - Current loop L contains compare instruction
503 /// that compares induction variable, IndVar, against loop invariant. If
504 /// entire (i.e. meaningful) loop body is dominated by this compare
505 /// instruction then loop body is executed only once. In such case eliminate
506 /// loop structure surrounding this loop body. For example,
507 /// for (int i = start; i < end; ++i) {
508 /// if ( i == somevalue) {
512 /// can be transformed into
513 /// if (somevalue >= start && somevalue < end) {
517 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
519 BasicBlock *Header = L->getHeader();
521 // First of all, check if SplitCondition dominates entire loop body
524 // If SplitCondition is not in loop header then this loop is not suitable
525 // for this transformation.
526 if (SD.SplitCondition->getParent() != Header)
529 // If loop header includes loop variant instruction operands then
530 // this loop may not be eliminated.
531 if (!safeHeader(SD, Header))
534 // If Exiting block includes loop variant instructions then this
535 // loop may not be eliminated.
536 if (!safeExitingBlock(SD, ExitCondition->getParent()))
539 // Filter loops where split condition's false branch is not empty.
540 if (ExitCondition->getParent() != Header->getTerminator()->getSuccessor(1))
543 // If split condition is not safe then do not process this loop.
545 // for(int i = 0; i < N; i++) {
554 if (!safeSplitCondition(SD))
557 BasicBlock *Latch = L->getLoopLatch();
558 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
564 // Replace index variable with split value in loop body. Loop body is executed
565 // only when index variable is equal to split value.
566 IndVar->replaceAllUsesWith(SD.SplitValue);
568 // Remove Latch to Header edge.
569 BasicBlock *LatchSucc = NULL;
570 Header->removePredecessor(Latch);
571 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
576 BR->setUnconditionalDest(LatchSucc);
578 Instruction *Terminator = Header->getTerminator();
579 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
581 // Replace split condition in header.
583 // SplitCondition : icmp eq i32 IndVar, SplitValue
585 // c1 = icmp uge i32 SplitValue, StartValue
586 // c2 = icmp ult i32 SplitValue, ExitValue
588 bool SignedPredicate = ExitCondition->isSignedPredicate();
589 Instruction *C1 = new ICmpInst(SignedPredicate ?
590 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
591 SD.SplitValue, StartValue, "lisplit",
593 Instruction *C2 = new ICmpInst(SignedPredicate ?
594 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
595 SD.SplitValue, ExitValue, "lisplit",
597 Instruction *NSplitCond = BinaryOperator::CreateAnd(C1, C2, "lisplit",
599 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
600 SD.SplitCondition->eraseFromParent();
602 // Now, clear latch block. Remove instructions that are responsible
603 // to increment induction variable.
604 Instruction *LTerminator = Latch->getTerminator();
605 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
609 if (isa<PHINode>(I) || I == LTerminator)
612 if (I == IndVarIncrement) {
613 // Replace induction variable increment if it is not used outside
615 bool UsedOutsideLoop = false;
616 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
618 if (Instruction *Use = dyn_cast<Instruction>(UI))
619 if (!L->contains(Use->getParent())) {
620 UsedOutsideLoop = true;
624 if (!UsedOutsideLoop) {
625 I->replaceAllUsesWith(ExitValue);
626 I->eraseFromParent();
630 I->replaceAllUsesWith(UndefValue::get(I->getType()));
631 I->eraseFromParent();
635 LPM->deleteLoopFromQueue(L);
637 // Update Dominator Info.
638 // Only CFG change done is to remove Latch to Header edge. This
639 // does not change dominator tree because Latch did not dominate
642 DominanceFrontier::iterator HeaderDF = DF->find(Header);
643 if (HeaderDF != DF->end())
644 DF->removeFromFrontier(HeaderDF, Header);
646 DominanceFrontier::iterator LatchDF = DF->find(Latch);
647 if (LatchDF != DF->end())
648 DF->removeFromFrontier(LatchDF, Header);
653 // If loop header includes loop variant instruction operands then
654 // this loop can not be eliminated. This is used by processOneIterationLoop().
655 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
657 Instruction *Terminator = Header->getTerminator();
658 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
666 // SplitCondition itself is OK.
667 if (I == SD.SplitCondition)
670 // Induction variable is OK.
674 // Induction variable increment is OK.
675 if (I == IndVarIncrement)
678 // Terminator is also harmless.
682 // Otherwise we have a instruction that may not be safe.
689 // If Exiting block includes loop variant instructions then this
690 // loop may not be eliminated. This is used by processOneIterationLoop().
691 bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD,
692 BasicBlock *ExitingBlock) {
694 for (BasicBlock::iterator BI = ExitingBlock->begin(),
695 BE = ExitingBlock->end(); BI != BE; ++BI) {
702 // Induction variable increment is OK.
703 if (IndVarIncrement && IndVarIncrement == I)
706 // Check if I is induction variable increment instruction.
707 if (I->getOpcode() == Instruction::Add) {
709 Value *Op0 = I->getOperand(0);
710 Value *Op1 = I->getOperand(1);
712 ConstantInt *CI = NULL;
714 if ((PN = dyn_cast<PHINode>(Op0))) {
715 if ((CI = dyn_cast<ConstantInt>(Op1)))
717 if (!IndVarIncrement && PN == IndVar)
719 // else this is another loop induction variable
723 if ((PN = dyn_cast<PHINode>(Op1))) {
724 if ((CI = dyn_cast<ConstantInt>(Op0)))
726 if (!IndVarIncrement && PN == IndVar)
728 // else this is another loop induction variable
734 // I is an Exit condition if next instruction is block terminator.
735 // Exit condition is OK if it compares loop invariant exit value,
736 // which is checked below.
737 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
738 if (EC == ExitCondition)
742 if (I == ExitingBlock->getTerminator())
745 // Otherwise we have instruction that may not be safe.
749 // We could not find any reason to consider ExitingBlock unsafe.
753 void LoopIndexSplit::updateLoopBounds(ICmpInst *CI) {
755 Value *V0 = CI->getOperand(0);
756 Value *V1 = CI->getOperand(1);
759 SCEVHandle SH0 = SE->getSCEV(V0);
761 if (SH0->isLoopInvariant(L))
766 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SGT
767 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGT
768 || ExitCondition->getPredicate() == ICmpInst::ICMP_SGE
769 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGE) {
770 ExitCondition->swapOperands();
779 Value *UB = ExitCondition->getOperand(ExitValueNum);
780 const Type *Ty = NV->getType();
781 bool Sign = ExitCondition->isSignedPredicate();
782 BasicBlock *Preheader = L->getLoopPreheader();
783 Instruction *PHTerminator = Preheader->getTerminator();
785 assert (NV && "Unexpected value");
787 switch (CI->getPredicate()) {
788 case ICmpInst::ICMP_ULE:
789 case ICmpInst::ICMP_SLE:
790 // for (i = LB; i < UB; ++i)
791 // if (i <= NV && ...)
794 // is transformed into
795 // NUB = min (NV+1, UB)
796 // for (i = LB; i < NUB ; ++i)
799 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLT
800 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULT) {
801 Value *A = BinaryOperator::CreateAdd(NV, ConstantInt::get(Ty, 1, Sign),
802 "lsplit.add", PHTerminator);
803 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
804 A, UB,"lsplit,c", PHTerminator);
805 NUB = SelectInst::Create(C, A, UB, "lsplit.nub", PHTerminator);
808 // for (i = LB; i <= UB; ++i)
809 // if (i <= NV && ...)
812 // is transformed into
813 // NUB = min (NV, UB)
814 // for (i = LB; i <= NUB ; ++i)
817 else if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLE
818 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULE) {
819 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
820 NV, UB, "lsplit.c", PHTerminator);
821 NUB = SelectInst::Create(C, NV, UB, "lsplit.nub", PHTerminator);
824 case ICmpInst::ICMP_ULT:
825 case ICmpInst::ICMP_SLT:
826 // for (i = LB; i < UB; ++i)
827 // if (i < NV && ...)
830 // is transformed into
831 // NUB = min (NV, UB)
832 // for (i = LB; i < NUB ; ++i)
835 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLT
836 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULT) {
837 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
838 NV, UB, "lsplit.c", PHTerminator);
839 NUB = SelectInst::Create(C, NV, UB, "lsplit.nub", PHTerminator);
842 // for (i = LB; i <= UB; ++i)
843 // if (i < NV && ...)
846 // is transformed into
847 // NUB = min (NV -1 , UB)
848 // for (i = LB; i <= NUB ; ++i)
851 else if (ExitCondition->getPredicate() == ICmpInst::ICMP_SLE
852 || ExitCondition->getPredicate() == ICmpInst::ICMP_ULE) {
853 Value *S = BinaryOperator::CreateSub(NV, ConstantInt::get(Ty, 1, Sign),
854 "lsplit.add", PHTerminator);
855 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
856 S, UB, "lsplit.c", PHTerminator);
857 NUB = SelectInst::Create(C, S, UB, "lsplit.nub", PHTerminator);
860 case ICmpInst::ICMP_UGE:
861 case ICmpInst::ICMP_SGE:
862 // for (i = LB; i (< or <=) UB; ++i)
863 // if (i >= NV && ...)
866 // is transformed into
867 // NLB = max (NV, LB)
868 // for (i = NLB; i (< or <=) UB ; ++i)
872 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
873 NV, StartValue, "lsplit.c", PHTerminator);
874 NLB = SelectInst::Create(C, StartValue, NV, "lsplit.nlb", PHTerminator);
877 case ICmpInst::ICMP_UGT:
878 case ICmpInst::ICMP_SGT:
879 // for (i = LB; i (< or <=) UB; ++i)
880 // if (i > NV && ...)
883 // is transformed into
884 // NLB = max (NV+1, LB)
885 // for (i = NLB; i (< or <=) UB ; ++i)
889 Value *A = BinaryOperator::CreateAdd(NV, ConstantInt::get(Ty, 1, Sign),
890 "lsplit.add", PHTerminator);
891 Value *C = new ICmpInst(Sign ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
892 A, StartValue, "lsplit.c", PHTerminator);
893 NLB = SelectInst::Create(C, StartValue, A, "lsplit.nlb", PHTerminator);
897 assert ( 0 && "Unexpected split condition predicate");
901 unsigned i = IndVar->getBasicBlockIndex(Preheader);
902 IndVar->setIncomingValue(i, NLB);
906 ExitCondition->setOperand(ExitValueNum, NUB);
909 /// updateLoopIterationSpace - Current loop body is covered by an AND
910 /// instruction whose operands compares induction variables with loop
911 /// invariants. If possible, hoist this check outside the loop by
912 /// updating appropriate start and end values for induction variable.
913 bool LoopIndexSplit::updateLoopIterationSpace(SplitInfo &SD) {
914 BasicBlock *Header = L->getHeader();
915 BasicBlock *ExitingBlock = ExitCondition->getParent();
916 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
918 ICmpInst *Op0 = cast<ICmpInst>(SD.SplitCondition->getOperand(0));
919 ICmpInst *Op1 = cast<ICmpInst>(SD.SplitCondition->getOperand(1));
921 if (Op0->getPredicate() == ICmpInst::ICMP_EQ
922 || Op0->getPredicate() == ICmpInst::ICMP_NE
923 || Op0->getPredicate() == ICmpInst::ICMP_EQ
924 || Op0->getPredicate() == ICmpInst::ICMP_NE)
927 // Check if SplitCondition dominates entire loop body
930 // If SplitCondition is not in loop header then this loop is not suitable
931 // for this transformation.
932 if (SD.SplitCondition->getParent() != Header)
935 // If loop header includes loop variant instruction operands then
936 // this loop may not be eliminated.
937 Instruction *Terminator = Header->getTerminator();
938 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
946 // SplitCondition itself is OK.
947 if (I == SD.SplitCondition)
949 if (I == Op0 || I == Op1)
952 // Induction variable is OK.
956 // Induction variable increment is OK.
957 if (I == IndVarIncrement)
960 // Terminator is also harmless.
964 // Otherwise we have a instruction that may not be safe.
968 // If Exiting block includes loop variant instructions then this
969 // loop may not be eliminated.
970 if (!safeExitingBlock(SD, ExitCondition->getParent()))
973 // Verify that loop exiting block has only two predecessor, where one predecessor
974 // is split condition block. The other predecessor will become exiting block's
975 // dominator after CFG is updated. TODO : Handle CFG's where exiting block has
976 // more then two predecessors. This requires extra work in updating dominator
978 BasicBlock *ExitingBBPred = NULL;
979 for (pred_iterator PI = pred_begin(ExitingBlock), PE = pred_end(ExitingBlock);
981 BasicBlock *BB = *PI;
982 if (SplitCondBlock == BB)
990 // Update loop bounds to absorb Op0 check.
991 updateLoopBounds(Op0);
992 // Update loop bounds to absorb Op1 check.
993 updateLoopBounds(Op1);
997 // Unconditionally connect split block to its remaining successor.
998 BranchInst *SplitTerminator =
999 cast<BranchInst>(SplitCondBlock->getTerminator());
1000 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1001 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1002 if (Succ0 == ExitCondition->getParent())
1003 SplitTerminator->setUnconditionalDest(Succ1);
1005 SplitTerminator->setUnconditionalDest(Succ0);
1007 // Remove split condition.
1008 SD.SplitCondition->eraseFromParent();
1009 if (Op0->use_empty())
1010 Op0->eraseFromParent();
1011 if (Op1->use_empty())
1012 Op1->eraseFromParent();
1014 BranchInst *ExitInsn =
1015 dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1016 assert (ExitInsn && "Unable to find suitable loop exit branch");
1017 BasicBlock *ExitBlock = ExitInsn->getSuccessor(1);
1018 if (L->contains(ExitBlock))
1019 ExitBlock = ExitInsn->getSuccessor(0);
1021 // Update domiantor info. Now, ExitingBlock has only one predecessor,
1022 // ExitingBBPred, and it is ExitingBlock's immediate domiantor.
1023 DT->changeImmediateDominator(ExitingBlock, ExitingBBPred);
1025 // If ExitingBlock is a member of loop BB's DF list then replace it with
1026 // loop header and exit block.
1027 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
1029 BasicBlock *BB = *I;
1030 if (BB == Header || BB == ExitingBlock)
1032 DominanceFrontier::iterator BBDF = DF->find(BB);
1033 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1034 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1035 while (DomSetI != DomSetE) {
1036 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1038 BasicBlock *DFBB = *CurrentItr;
1039 if (DFBB == ExitingBlock) {
1040 BBDF->second.erase(DFBB);
1041 BBDF->second.insert(Header);
1042 if (Header != ExitingBlock)
1043 BBDF->second.insert(ExitBlock);
1052 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
1053 /// This routine is used to remove split condition's dead branch, dominated by
1054 /// DeadBB. LiveBB dominates split conidition's other branch.
1055 void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
1056 BasicBlock *LiveBB) {
1058 // First update DeadBB's dominance frontier.
1059 SmallVector<BasicBlock *, 8> FrontierBBs;
1060 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
1061 if (DeadBBDF != DF->end()) {
1062 SmallVector<BasicBlock *, 8> PredBlocks;
1064 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
1065 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
1066 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
1067 BasicBlock *FrontierBB = *DeadBBSetI;
1068 FrontierBBs.push_back(FrontierBB);
1070 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
1072 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
1074 BasicBlock *P = *PI;
1075 if (P == DeadBB || DT->dominates(DeadBB, P))
1076 PredBlocks.push_back(P);
1079 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
1080 FBI != FBE; ++FBI) {
1081 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
1082 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
1083 PE = PredBlocks.end(); PI != PE; ++PI) {
1084 BasicBlock *P = *PI;
1085 PN->removeIncomingValue(P);
1094 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
1095 SmallVector<BasicBlock *, 32> WorkList;
1096 DomTreeNode *DN = DT->getNode(DeadBB);
1097 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
1098 E = df_end(DN); DI != E; ++DI) {
1099 BasicBlock *BB = DI->getBlock();
1100 WorkList.push_back(BB);
1101 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
1104 while (!WorkList.empty()) {
1105 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
1106 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
1108 Instruction *I = BBI;
1110 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1111 I->eraseFromParent();
1113 LPM->deleteSimpleAnalysisValue(BB, LP);
1115 DF->removeBlock(BB);
1116 LI->removeBlock(BB);
1117 BB->eraseFromParent();
1120 // Update Frontier BBs' dominator info.
1121 while (!FrontierBBs.empty()) {
1122 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
1123 BasicBlock *NewDominator = FBB->getSinglePredecessor();
1124 if (!NewDominator) {
1125 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
1128 if (NewDominator != LiveBB) {
1129 for(; PI != PE; ++PI) {
1130 BasicBlock *P = *PI;
1132 NewDominator = LiveBB;
1135 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
1139 assert (NewDominator && "Unable to fix dominator info.");
1140 DT->changeImmediateDominator(FBB, NewDominator);
1141 DF->changeImmediateDominator(FBB, NewDominator, DT);
1146 /// safeSplitCondition - Return true if it is possible to
1147 /// split loop using given split condition.
1148 bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
1150 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
1151 BasicBlock *Latch = L->getLoopLatch();
1152 BranchInst *SplitTerminator =
1153 cast<BranchInst>(SplitCondBlock->getTerminator());
1154 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1155 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1157 // If split block does not dominate the latch then this is not a diamond.
1158 // Such loop may not benefit from index split.
1159 if (!DT->dominates(SplitCondBlock, Latch))
1162 // Finally this split condition is safe only if merge point for
1163 // split condition branch is loop latch. This check along with previous
1164 // check, to ensure that exit condition is in either loop latch or header,
1165 // filters all loops with non-empty loop body between merge point
1166 // and exit condition.
1167 DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
1168 assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
1169 if (Succ0DF->second.count(Latch))
1172 DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
1173 assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
1174 if (Succ1DF->second.count(Latch))
1180 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
1181 /// based on split value.
1182 void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
1184 ICmpInst *SC = cast<ICmpInst>(SD.SplitCondition);
1185 ICmpInst::Predicate SP = SC->getPredicate();
1186 const Type *Ty = SD.SplitValue->getType();
1187 bool Sign = ExitCondition->isSignedPredicate();
1188 BasicBlock *Preheader = L->getLoopPreheader();
1189 Instruction *PHTerminator = Preheader->getTerminator();
1191 // Initially use split value as upper loop bound for first loop and lower loop
1192 // bound for second loop.
1193 Value *AEV = SD.SplitValue;
1194 Value *BSV = SD.SplitValue;
1196 if (ExitCondition->getPredicate() == ICmpInst::ICMP_SGT
1197 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGT
1198 || ExitCondition->getPredicate() == ICmpInst::ICMP_SGE
1199 || ExitCondition->getPredicate() == ICmpInst::ICMP_UGE) {
1200 ExitCondition->swapOperands();
1207 switch (ExitCondition->getPredicate()) {
1208 case ICmpInst::ICMP_SGT:
1209 case ICmpInst::ICMP_UGT:
1210 case ICmpInst::ICMP_SGE:
1211 case ICmpInst::ICMP_UGE:
1213 assert (0 && "Unexpected exit condition predicate");
1215 case ICmpInst::ICMP_SLT:
1216 case ICmpInst::ICMP_ULT:
1219 case ICmpInst::ICMP_SLT:
1220 case ICmpInst::ICMP_ULT:
1222 // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
1224 // is transformed into
1226 // for (i = LB; i < min(UB, AEV); ++i)
1228 // for (i = max(LB, BSV); i < UB; ++i);
1231 case ICmpInst::ICMP_SLE:
1232 case ICmpInst::ICMP_ULE:
1235 // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
1237 // is transformed into
1241 // for (i = LB; i < min(UB, AEV); ++i)
1243 // for (i = max(LB, BSV); i < UB; ++i)
1245 BSV = BinaryOperator::CreateAdd(SD.SplitValue,
1246 ConstantInt::get(Ty, 1, Sign),
1247 "lsplit.add", PHTerminator);
1251 case ICmpInst::ICMP_SGE:
1252 case ICmpInst::ICMP_UGE:
1254 // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
1256 // is transformed into
1258 // for (i = LB; i < min(UB, AEV); ++i)
1260 // for (i = max(BSV, LB); i < UB; ++i)
1263 case ICmpInst::ICMP_SGT:
1264 case ICmpInst::ICMP_UGT:
1267 // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
1269 // is transformed into
1271 // BSV = AEV = SV + 1
1272 // for (i = LB; i < min(UB, AEV); ++i)
1274 // for (i = max(LB, BSV); i < UB; ++i)
1276 BSV = BinaryOperator::CreateAdd(SD.SplitValue,
1277 ConstantInt::get(Ty, 1, Sign),
1278 "lsplit.add", PHTerminator);
1283 assert (0 && "Unexpected split condition predicate");
1285 } // end switch (SP)
1288 case ICmpInst::ICMP_SLE:
1289 case ICmpInst::ICMP_ULE:
1292 case ICmpInst::ICMP_SLT:
1293 case ICmpInst::ICMP_ULT:
1295 // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
1297 // is transformed into
1300 // for (i = LB; i <= min(UB, AEV); ++i)
1302 // for (i = max(LB, BSV); i <= UB; ++i)
1304 AEV = BinaryOperator::CreateSub(SD.SplitValue,
1305 ConstantInt::get(Ty, 1, Sign),
1306 "lsplit.sub", PHTerminator);
1308 case ICmpInst::ICMP_SLE:
1309 case ICmpInst::ICMP_ULE:
1311 // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
1313 // is transformed into
1316 // for (i = LB; i <= min(UB, AEV); ++i)
1318 // for (i = max(LB, BSV); i <= UB; ++i)
1320 BSV = BinaryOperator::CreateAdd(SD.SplitValue,
1321 ConstantInt::get(Ty, 1, Sign),
1322 "lsplit.add", PHTerminator);
1324 case ICmpInst::ICMP_SGT:
1325 case ICmpInst::ICMP_UGT:
1327 // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
1329 // is transformed into
1332 // for (i = LB; i <= min(AEV, UB); ++i)
1334 // for (i = max(LB, BSV); i <= UB; ++i)
1336 BSV = BinaryOperator::CreateAdd(SD.SplitValue,
1337 ConstantInt::get(Ty, 1, Sign),
1338 "lsplit.add", PHTerminator);
1340 case ICmpInst::ICMP_SGE:
1341 case ICmpInst::ICMP_UGE:
1344 // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
1346 // is transformed into
1349 // for (i = LB; i <= min(AEV, UB); ++i)
1351 // for (i = max(LB, BSV); i <= UB; ++i)
1353 AEV = BinaryOperator::CreateSub(SD.SplitValue,
1354 ConstantInt::get(Ty, 1, Sign),
1355 "lsplit.sub", PHTerminator);
1358 assert (0 && "Unexpected split condition predicate");
1360 } // end switch (SP)
1365 // Calculate ALoop induction variable's new exiting value and
1366 // BLoop induction variable's new starting value. Calculuate these
1367 // values in original loop's preheader.
1368 // A_ExitValue = min(SplitValue, OrignalLoopExitValue)
1369 // B_StartValue = max(SplitValue, OriginalLoopStartValue)
1370 Instruction *InsertPt = L->getHeader()->getFirstNonPHI();
1372 // If ExitValue operand is also defined in Loop header then
1373 // insert new ExitValue after this operand definition.
1374 if (Instruction *EVN =
1375 dyn_cast<Instruction>(ExitCondition->getOperand(ExitValueNum))) {
1376 if (!isa<PHINode>(EVN))
1377 if (InsertPt->getParent() == EVN->getParent()) {
1378 BasicBlock::iterator LHBI = L->getHeader()->begin();
1379 BasicBlock::iterator LHBE = L->getHeader()->end();
1380 for(;LHBI != LHBE; ++LHBI) {
1381 Instruction *I = LHBI;
1388 Value *C1 = new ICmpInst(Sign ?
1389 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1391 ExitCondition->getOperand(ExitValueNum),
1392 "lsplit.ev", InsertPt);
1394 SD.A_ExitValue = SelectInst::Create(C1, AEV,
1395 ExitCondition->getOperand(ExitValueNum),
1396 "lsplit.ev", InsertPt);
1398 Value *C2 = new ICmpInst(Sign ?
1399 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
1400 BSV, StartValue, "lsplit.sv",
1402 SD.B_StartValue = SelectInst::Create(C2, StartValue, BSV,
1403 "lsplit.sv", PHTerminator);
1406 /// splitLoop - Split current loop L in two loops using split information
1407 /// SD. Update dominator information. Maintain LCSSA form.
1408 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
1410 if (!safeSplitCondition(SD))
1413 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
1415 // Unable to handle triangle loops at the moment.
1416 // In triangle loop, split condition is in header and one of the
1417 // the split destination is loop latch. If split condition is EQ
1418 // then such loops are already handle in processOneIterationLoop().
1419 BasicBlock *Latch = L->getLoopLatch();
1420 BranchInst *SplitTerminator =
1421 cast<BranchInst>(SplitCondBlock->getTerminator());
1422 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
1423 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
1424 if (L->getHeader() == SplitCondBlock
1425 && (Latch == Succ0 || Latch == Succ1))
1428 // If split condition branches heads do not have single predecessor,
1429 // SplitCondBlock, then is not possible to remove inactive branch.
1430 if (!Succ0->getSinglePredecessor() || !Succ1->getSinglePredecessor())
1433 // If Exiting block includes loop variant instructions then this
1434 // loop may not be split safely.
1435 if (!safeExitingBlock(SD, ExitCondition->getParent()))
1438 // After loop is cloned there are two loops.
1440 // First loop, referred as ALoop, executes first part of loop's iteration
1441 // space split. Second loop, referred as BLoop, executes remaining
1442 // part of loop's iteration space.
1444 // ALoop's exit edge enters BLoop's header through a forwarding block which
1445 // acts as a BLoop's preheader.
1446 BasicBlock *Preheader = L->getLoopPreheader();
1448 // Calculate ALoop induction variable's new exiting value and
1449 // BLoop induction variable's new starting value.
1450 calculateLoopBounds(SD);
1453 DenseMap<const Value *, Value *> ValueMap;
1454 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
1456 BasicBlock *B_Header = BLoop->getHeader();
1458 //[*] ALoop's exiting edge BLoop's header.
1459 // ALoop's original exit block becomes BLoop's exit block.
1460 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1461 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1462 BranchInst *A_ExitInsn =
1463 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1464 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1465 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1466 if (L->contains(B_ExitBlock)) {
1467 B_ExitBlock = A_ExitInsn->getSuccessor(0);
1468 A_ExitInsn->setSuccessor(0, B_Header);
1470 A_ExitInsn->setSuccessor(1, B_Header);
1472 //[*] Update ALoop's exit value using new exit value.
1473 ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
1475 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1476 // original loop's preheader. Add incoming PHINode values from
1477 // ALoop's exiting block. Update BLoop header's domiantor info.
1479 // Collect inverse map of Header PHINodes.
1480 DenseMap<Value *, Value *> InverseMap;
1481 for (BasicBlock::iterator BI = L->getHeader()->begin(),
1482 BE = L->getHeader()->end(); BI != BE; ++BI) {
1483 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1484 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1485 InverseMap[PNClone] = PN;
1490 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1492 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1493 // Remove incoming value from original preheader.
1494 PN->removeIncomingValue(Preheader);
1496 // Add incoming value from A_ExitingBlock.
1498 PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
1500 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
1502 // If loop header is also loop exiting block then
1503 // OrigPN is incoming value for B loop header.
1504 if (A_ExitingBlock == L->getHeader())
1507 V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1508 PN->addIncoming(V2, A_ExitingBlock);
1513 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1514 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
1516 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1517 // block. Remove incoming PHINode values from ALoop's exiting block.
1518 // Add new incoming values from BLoop's incoming exiting value.
1519 // Update BLoop exit block's dominator info..
1520 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1521 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
1523 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1524 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1526 PN->removeIncomingValue(A_ExitingBlock);
1531 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1532 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
1534 //[*] Split ALoop's exit edge. This creates a new block which
1535 // serves two purposes. First one is to hold PHINode defnitions
1536 // to ensure that ALoop's LCSSA form. Second use it to act
1537 // as a preheader for BLoop.
1538 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
1540 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1541 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1542 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1544 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1545 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
1546 PHINode *newPHI = PHINode::Create(PN->getType(), PN->getName());
1547 newPHI->addIncoming(V1, A_ExitingBlock);
1548 A_ExitBlock->getInstList().push_front(newPHI);
1549 PN->removeIncomingValue(A_ExitBlock);
1550 PN->addIncoming(newPHI, A_ExitBlock);
1555 //[*] Eliminate split condition's inactive branch from ALoop.
1556 BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1557 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
1558 BasicBlock *A_InactiveBranch = NULL;
1559 BasicBlock *A_ActiveBranch = NULL;
1560 if (SD.UseTrueBranchFirst) {
1561 A_ActiveBranch = A_BR->getSuccessor(0);
1562 A_InactiveBranch = A_BR->getSuccessor(1);
1564 A_ActiveBranch = A_BR->getSuccessor(1);
1565 A_InactiveBranch = A_BR->getSuccessor(0);
1567 A_BR->setUnconditionalDest(A_ActiveBranch);
1568 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1570 //[*] Eliminate split condition's inactive branch in from BLoop.
1571 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1572 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
1573 BasicBlock *B_InactiveBranch = NULL;
1574 BasicBlock *B_ActiveBranch = NULL;
1575 if (SD.UseTrueBranchFirst) {
1576 B_ActiveBranch = B_BR->getSuccessor(1);
1577 B_InactiveBranch = B_BR->getSuccessor(0);
1579 B_ActiveBranch = B_BR->getSuccessor(0);
1580 B_InactiveBranch = B_BR->getSuccessor(1);
1582 B_BR->setUnconditionalDest(B_ActiveBranch);
1583 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
1585 BasicBlock *A_Header = L->getHeader();
1586 if (A_ExitingBlock == A_Header)
1589 //[*] Move exit condition into split condition block to avoid
1590 // executing dead loop iteration.
1591 ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
1592 Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
1593 ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
1595 moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
1596 cast<ICmpInst>(SD.SplitCondition), IndVar, IndVarIncrement,
1599 moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
1600 B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
1605 // moveExitCondition - Move exit condition EC into split condition block CondBB.
1606 void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
1607 BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
1608 PHINode *IV, Instruction *IVAdd, Loop *LP) {
1610 BasicBlock *ExitingBB = EC->getParent();
1611 Instruction *CurrentBR = CondBB->getTerminator();
1613 // Move exit condition into split condition block.
1614 EC->moveBefore(CurrentBR);
1615 EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
1617 // Move exiting block's branch into split condition block. Update its branch
1619 BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
1620 ExitingBR->moveBefore(CurrentBR);
1621 BasicBlock *OrigDestBB = NULL;
1622 if (ExitingBR->getSuccessor(0) == ExitBB) {
1623 OrigDestBB = ExitingBR->getSuccessor(1);
1624 ExitingBR->setSuccessor(1, ActiveBB);
1627 OrigDestBB = ExitingBR->getSuccessor(0);
1628 ExitingBR->setSuccessor(0, ActiveBB);
1631 // Remove split condition and current split condition branch.
1632 SC->eraseFromParent();
1633 CurrentBR->eraseFromParent();
1635 // Connect exiting block to original destination.
1636 BranchInst::Create(OrigDestBB, ExitingBB);
1639 updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd, LP);
1641 // Fix dominator info.
1642 // ExitBB is now dominated by CondBB
1643 DT->changeImmediateDominator(ExitBB, CondBB);
1644 DF->changeImmediateDominator(ExitBB, CondBB, DT);
1646 // Basicblocks dominated by ActiveBB may have ExitingBB or
1647 // a basic block outside the loop in their DF list. If so,
1648 // replace it with CondBB.
1649 DomTreeNode *Node = DT->getNode(ActiveBB);
1650 for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
1652 BasicBlock *BB = DI->getBlock();
1653 DominanceFrontier::iterator BBDF = DF->find(BB);
1654 DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
1655 DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
1656 while (DomSetI != DomSetE) {
1657 DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
1659 BasicBlock *DFBB = *CurrentItr;
1660 if (DFBB == ExitingBB || !L->contains(DFBB)) {
1661 BBDF->second.erase(DFBB);
1662 BBDF->second.insert(CondBB);
1668 /// updatePHINodes - CFG has been changed.
1670 /// - ExitBB's single predecessor was Latch
1671 /// - Latch's second successor was Header
1673 /// - ExitBB's single predecessor is Header
1674 /// - Latch's one and only successor is Header
1676 /// Update ExitBB PHINodes' to reflect this change.
1677 void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
1679 PHINode *IV, Instruction *IVIncrement,
1682 for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
1684 PHINode *PN = dyn_cast<PHINode>(BI);
1689 Value *V = PN->getIncomingValueForBlock(Latch);
1690 if (PHINode *PHV = dyn_cast<PHINode>(V)) {
1691 // PHV is in Latch. PHV has one use is in ExitBB PHINode. And one use
1692 // in Header which is new incoming value for PN.
1694 for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
1696 if (PHINode *U = dyn_cast<PHINode>(*UI))
1697 if (LP->contains(U->getParent())) {
1702 // Add incoming value from header only if PN has any use inside the loop.
1704 PN->addIncoming(NewV, Header);
1706 } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
1707 // If this instruction is IVIncrement then IV is new incoming value
1708 // from header otherwise this instruction must be incoming value from
1709 // header because loop is in LCSSA form.
1710 if (PHI == IVIncrement)
1711 PN->addIncoming(IV, Header);
1713 PN->addIncoming(V, Header);
1715 // Otherwise this is an incoming value from header because loop is in
1717 PN->addIncoming(V, Header);
1719 // Remove incoming value from Latch.
1720 PN->removeIncomingValue(Latch);