1 //===- LoopIndexSplit.cpp - Loop Index Splitting Pass ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Devang Patel and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
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 compare instruction compares IndVar against SplitValue.
68 ICmpInst *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;
92 /// Find condition inside a loop that is suitable candidate for index split.
93 void findSplitCondition();
95 /// Find loop's exit condition.
96 void findLoopConditionals();
98 /// Return induction variable associated with value V.
99 void findIndVar(Value *V, Loop *L);
101 /// processOneIterationLoop - Current loop L contains compare instruction
102 /// that compares induction variable, IndVar, agains loop invariant. If
103 /// entire (i.e. meaningful) loop body is dominated by this compare
104 /// instruction then loop body is executed only for one iteration. In
105 /// such case eliminate loop structure surrounding this loop body. For
106 bool processOneIterationLoop(SplitInfo &SD);
108 /// If loop header includes loop variant instruction operands then
109 /// this loop may not be eliminated.
110 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
112 /// If Exiting block includes loop variant instructions then this
113 /// loop may not be eliminated.
114 bool safeExitingBlock(SplitInfo &SD, BasicBlock *BB);
116 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
117 /// This routine is used to remove split condition's dead branch, dominated by
118 /// DeadBB. LiveBB dominates split conidition's other branch.
119 void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
121 /// safeSplitCondition - Return true if it is possible to
122 /// split loop using given split condition.
123 bool safeSplitCondition(SplitInfo &SD);
125 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
126 /// based on split value.
127 void calculateLoopBounds(SplitInfo &SD);
129 /// splitLoop - Split current loop L in two loops using split information
130 /// SD. Update dominator information. Maintain LCSSA form.
131 bool splitLoop(SplitInfo &SD);
135 IndVarIncrement = NULL;
136 ExitCondition = NULL;
150 DominanceFrontier *DF;
151 SmallVector<SplitInfo, 4> SplitData;
153 // Induction variable whose range is being split by this transformation.
155 Instruction *IndVarIncrement;
157 // Loop exit condition.
158 ICmpInst *ExitCondition;
160 // Induction variable's initial value.
163 // Induction variable's final loop exit value operand number in exit condition..
164 unsigned ExitValueNum;
167 char LoopIndexSplit::ID = 0;
168 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
171 LoopPass *llvm::createLoopIndexSplitPass() {
172 return new LoopIndexSplit();
175 // Index split Loop L. Return true if loop is split.
176 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
177 bool Changed = false;
181 // FIXME - Nested loops make dominator info updates tricky.
182 if (!L->getSubLoops().empty())
185 SE = &getAnalysis<ScalarEvolution>();
186 DT = &getAnalysis<DominatorTree>();
187 LI = &getAnalysis<LoopInfo>();
188 DF = &getAnalysis<DominanceFrontier>();
192 findLoopConditionals();
197 findSplitCondition();
199 if (SplitData.empty())
202 // First see if it is possible to eliminate loop itself or not.
203 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
204 E = SplitData.end(); SI != E;) {
206 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
207 Changed = processOneIterationLoop(SD);
210 // If is loop is eliminated then nothing else to do here.
213 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
215 SplitData.erase(Delete_SI);
221 if (SplitData.empty())
224 // Split most profitiable condition.
225 // FIXME : Implement cost analysis.
226 unsigned MostProfitableSDIndex = 0;
227 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
235 /// Return true if V is a induction variable or induction variable's
236 /// increment for loop L.
237 void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
239 Instruction *I = dyn_cast<Instruction>(V);
243 // Check if I is a phi node from loop header or not.
244 if (PHINode *PN = dyn_cast<PHINode>(V)) {
245 if (PN->getParent() == L->getHeader()) {
251 // Check if I is a add instruction whose one operand is
252 // phi node from loop header and second operand is constant.
253 if (I->getOpcode() != Instruction::Add)
256 Value *Op0 = I->getOperand(0);
257 Value *Op1 = I->getOperand(1);
259 if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
260 if (PN->getParent() == L->getHeader()
261 && isa<ConstantInt>(Op1)) {
268 if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
269 if (PN->getParent() == L->getHeader()
270 && isa<ConstantInt>(Op0)) {
280 // Find loop's exit condition and associated induction variable.
281 void LoopIndexSplit::findLoopConditionals() {
283 BasicBlock *ExitingBlock = NULL;
285 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
288 if (!L->isLoopExit(BB))
298 // If exiting block is neither loop header nor loop latch then this loop is
300 if (ExitingBlock != L->getHeader() && ExitingBlock != L->getLoopLatch())
303 // If exit block's terminator is conditional branch inst then we have found
305 BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
306 if (!BR || BR->isUnconditional())
309 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
314 if (CI->getPredicate() == ICmpInst::ICMP_SGT
315 || CI->getPredicate() == ICmpInst::ICMP_UGT
316 || CI->getPredicate() == ICmpInst::ICMP_SGE
317 || CI->getPredicate() == ICmpInst::ICMP_UGE)
322 // Exit condition's one operand is loop invariant exit value and second
323 // operand is SCEVAddRecExpr based on induction variable.
324 Value *V0 = CI->getOperand(0);
325 Value *V1 = CI->getOperand(1);
327 SCEVHandle SH0 = SE->getSCEV(V0);
328 SCEVHandle SH1 = SE->getSCEV(V1);
330 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
334 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
340 ExitCondition = NULL;
342 BasicBlock *Preheader = L->getLoopPreheader();
343 StartValue = IndVar->getIncomingValueForBlock(Preheader);
347 /// Find condition inside a loop that is suitable candidate for index split.
348 void LoopIndexSplit::findSplitCondition() {
351 // Check all basic block's terminators.
353 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
357 // If this basic block does not terminate in a conditional branch
358 // then terminator is not a suitable split condition.
359 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
363 if (BR->isUnconditional())
366 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
367 if (!CI || CI == ExitCondition)
370 if (CI->getPredicate() == ICmpInst::ICMP_NE)
373 // If split condition predicate is GT or GE then first execute
374 // false branch of split condition.
375 if (CI->getPredicate() != ICmpInst::ICMP_ULT
376 && CI->getPredicate() != ICmpInst::ICMP_SLT
377 && CI->getPredicate() != ICmpInst::ICMP_ULE
378 && CI->getPredicate() != ICmpInst::ICMP_SLE)
379 SD.UseTrueBranchFirst = false;
381 // If one operand is loop invariant and second operand is SCEVAddRecExpr
382 // based on induction variable then CI is a candidate split condition.
383 Value *V0 = CI->getOperand(0);
384 Value *V1 = CI->getOperand(1);
386 SCEVHandle SH0 = SE->getSCEV(V0);
387 SCEVHandle SH1 = SE->getSCEV(V1);
389 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
391 SD.SplitCondition = CI;
392 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
394 SplitData.push_back(SD);
396 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
397 if (IndVarIncrement && IndVarIncrement == Insn)
398 SplitData.push_back(SD);
401 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
403 SD.SplitCondition = CI;
404 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
406 SplitData.push_back(SD);
408 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
409 if (IndVarIncrement && IndVarIncrement == Insn)
410 SplitData.push_back(SD);
416 /// processOneIterationLoop - Current loop L contains compare instruction
417 /// that compares induction variable, IndVar, against loop invariant. If
418 /// entire (i.e. meaningful) loop body is dominated by this compare
419 /// instruction then loop body is executed only once. In such case eliminate
420 /// loop structure surrounding this loop body. For example,
421 /// for (int i = start; i < end; ++i) {
422 /// if ( i == somevalue) {
426 /// can be transformed into
427 /// if (somevalue >= start && somevalue < end) {
431 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
433 BasicBlock *Header = L->getHeader();
435 // First of all, check if SplitCondition dominates entire loop body
438 // If SplitCondition is not in loop header then this loop is not suitable
439 // for this transformation.
440 if (SD.SplitCondition->getParent() != Header)
443 // If loop header includes loop variant instruction operands then
444 // this loop may not be eliminated.
445 if (!safeHeader(SD, Header))
448 // If Exiting block includes loop variant instructions then this
449 // loop may not be eliminated.
450 if (!safeExitingBlock(SD, ExitCondition->getParent()))
455 // Replace index variable with split value in loop body. Loop body is executed
456 // only when index variable is equal to split value.
457 IndVar->replaceAllUsesWith(SD.SplitValue);
459 // Remove Latch to Header edge.
460 BasicBlock *Latch = L->getLoopLatch();
461 BasicBlock *LatchSucc = NULL;
462 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
465 Header->removePredecessor(Latch);
466 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
471 BR->setUnconditionalDest(LatchSucc);
473 Instruction *Terminator = Header->getTerminator();
474 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
476 // Replace split condition in header.
478 // SplitCondition : icmp eq i32 IndVar, SplitValue
480 // c1 = icmp uge i32 SplitValue, StartValue
481 // c2 = icmp ult i32 vSplitValue, ExitValue
483 bool SignedPredicate = ExitCondition->isSignedPredicate();
484 Instruction *C1 = new ICmpInst(SignedPredicate ?
485 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
486 SD.SplitValue, StartValue, "lisplit",
488 Instruction *C2 = new ICmpInst(SignedPredicate ?
489 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
490 SD.SplitValue, ExitValue, "lisplit",
492 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
494 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
495 SD.SplitCondition->eraseFromParent();
497 // Now, clear latch block. Remove instructions that are responsible
498 // to increment induction variable.
499 Instruction *LTerminator = Latch->getTerminator();
500 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
504 if (isa<PHINode>(I) || I == LTerminator)
507 if (I == IndVarIncrement)
508 I->replaceAllUsesWith(ExitValue);
510 I->replaceAllUsesWith(UndefValue::get(I->getType()));
511 I->eraseFromParent();
514 LPM->deleteLoopFromQueue(L);
516 // Update Dominator Info.
517 // Only CFG change done is to remove Latch to Header edge. This
518 // does not change dominator tree because Latch did not dominate
521 DominanceFrontier::iterator HeaderDF = DF->find(Header);
522 if (HeaderDF != DF->end())
523 DF->removeFromFrontier(HeaderDF, Header);
525 DominanceFrontier::iterator LatchDF = DF->find(Latch);
526 if (LatchDF != DF->end())
527 DF->removeFromFrontier(LatchDF, Header);
532 // If loop header includes loop variant instruction operands then
533 // this loop can not be eliminated. This is used by processOneIterationLoop().
534 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
536 Instruction *Terminator = Header->getTerminator();
537 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
545 // SplitCondition itself is OK.
546 if (I == SD.SplitCondition)
549 // Induction variable is OK.
553 // Induction variable increment is OK.
554 if (I == IndVarIncrement)
557 // Terminator is also harmless.
561 // Otherwise we have a instruction that may not be safe.
568 // If Exiting block includes loop variant instructions then this
569 // loop may not be eliminated. This is used by processOneIterationLoop().
570 bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD,
571 BasicBlock *ExitingBlock) {
573 for (BasicBlock::iterator BI = ExitingBlock->begin(),
574 BE = ExitingBlock->end(); BI != BE; ++BI) {
581 // Induction variable increment is OK.
582 if (IndVarIncrement && IndVarIncrement == I)
585 // Check if I is induction variable increment instruction.
586 if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
588 Value *Op0 = I->getOperand(0);
589 Value *Op1 = I->getOperand(1);
591 ConstantInt *CI = NULL;
593 if ((PN = dyn_cast<PHINode>(Op0))) {
594 if ((CI = dyn_cast<ConstantInt>(Op1)))
597 if ((PN = dyn_cast<PHINode>(Op1))) {
598 if ((CI = dyn_cast<ConstantInt>(Op0)))
602 if (IndVarIncrement && PN == IndVar && CI->isOne())
606 // I is an Exit condition if next instruction is block terminator.
607 // Exit condition is OK if it compares loop invariant exit value,
608 // which is checked below.
609 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
610 if (EC == ExitCondition)
614 if (I == ExitingBlock->getTerminator())
617 // Otherwise we have instruction that may not be safe.
621 // We could not find any reason to consider ExitingBlock unsafe.
625 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
626 /// This routine is used to remove split condition's dead branch, dominated by
627 /// DeadBB. LiveBB dominates split conidition's other branch.
628 void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
629 BasicBlock *LiveBB) {
631 // First update DeadBB's dominance frontier.
632 SmallVector<BasicBlock *, 8> FrontierBBs;
633 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
634 if (DeadBBDF != DF->end()) {
635 SmallVector<BasicBlock *, 8> PredBlocks;
637 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
638 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
639 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
640 BasicBlock *FrontierBB = *DeadBBSetI;
641 FrontierBBs.push_back(FrontierBB);
643 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
645 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
648 if (P == DeadBB || DT->dominates(DeadBB, P))
649 PredBlocks.push_back(P);
652 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
654 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
655 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
656 PE = PredBlocks.end(); PI != PE; ++PI) {
658 PN->removeIncomingValue(P);
667 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
668 SmallVector<BasicBlock *, 32> WorkList;
669 DomTreeNode *DN = DT->getNode(DeadBB);
670 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
671 E = df_end(DN); DI != E; ++DI) {
672 BasicBlock *BB = DI->getBlock();
673 WorkList.push_back(BB);
674 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
677 while (!WorkList.empty()) {
678 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
679 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
681 Instruction *I = BBI;
682 I->replaceAllUsesWith(UndefValue::get(I->getType()));
683 I->eraseFromParent();
685 LPM->deleteSimpleAnalysisValue(BB, LP);
689 BB->eraseFromParent();
692 // Update Frontier BBs' dominator info.
693 while (!FrontierBBs.empty()) {
694 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
695 BasicBlock *NewDominator = FBB->getSinglePredecessor();
697 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
700 if (NewDominator != LiveBB) {
701 for(; PI != PE; ++PI) {
704 NewDominator = LiveBB;
707 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
711 assert (NewDominator && "Unable to fix dominator info.");
712 DT->changeImmediateDominator(FBB, NewDominator);
713 DF->changeImmediateDominator(FBB, NewDominator, DT);
718 /// safeSplitCondition - Return true if it is possible to
719 /// split loop using given split condition.
720 bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
722 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
724 // Unable to handle triange loops at the moment.
725 // In triangle loop, split condition is in header and one of the
726 // the split destination is loop latch. If split condition is EQ
727 // then such loops are already handle in processOneIterationLoop().
728 BasicBlock *Latch = L->getLoopLatch();
729 BranchInst *SplitTerminator =
730 cast<BranchInst>(SplitCondBlock->getTerminator());
731 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
732 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
733 if (L->getHeader() == SplitCondBlock
734 && (Latch == Succ0 || Latch == Succ1))
737 // If one of the split condition branch is post dominating other then loop
738 // index split is not appropriate.
739 if (DT->dominates(Succ0, Latch) || DT->dominates(Succ1, Latch))
742 // If one of the split condition branch is a predecessor of the other
743 // split condition branch head then do not split loop on this condition.
744 for(pred_iterator PI = pred_begin(Succ0), PE = pred_end(Succ0);
748 for(pred_iterator PI = pred_begin(Succ1), PE = pred_end(Succ1);
753 // Finally this split condition is safe only if merge point for
754 // split condition branch is loop latch. This check along with previous
755 // check, to ensure that exit condition is in either loop latch or header,
756 // filters all loops with non-empty loop body between merge point
757 // and exit condition.
758 DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
759 assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
760 if (Succ0DF->second.count(Latch))
763 DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
764 assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
765 if (Succ1DF->second.count(Latch))
771 /// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
772 /// based on split value.
773 void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
775 ICmpInst::Predicate SP = SD.SplitCondition->getPredicate();
776 const Type *Ty = SD.SplitValue->getType();
777 bool Sign = ExitCondition->isSignedPredicate();
778 BasicBlock *Preheader = L->getLoopPreheader();
779 Instruction *PHTerminator = Preheader->getTerminator();
781 // Initially use split value as upper loop bound for first loop and lower loop
782 // bound for second loop.
783 Value *AEV = SD.SplitValue;
784 Value *BSV = SD.SplitValue;
786 switch (ExitCondition->getPredicate()) {
787 case ICmpInst::ICMP_SGT:
788 case ICmpInst::ICMP_UGT:
789 case ICmpInst::ICMP_SGE:
790 case ICmpInst::ICMP_UGE:
792 assert (0 && "Unexpected exit condition predicate");
794 case ICmpInst::ICMP_SLT:
795 case ICmpInst::ICMP_ULT:
798 case ICmpInst::ICMP_SLT:
799 case ICmpInst::ICMP_ULT:
801 // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
803 // is transformed into
805 // for (i = LB; i < min(UB, AEV); ++i)
807 // for (i = max(LB, BSV); i < UB; ++i);
810 case ICmpInst::ICMP_SLE:
811 case ICmpInst::ICMP_ULE:
814 // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
816 // is transformed into
820 // for (i = LB; i < min(UB, AEV); ++i)
822 // for (i = max(LB, BSV); i < UB; ++i)
824 BSV = BinaryOperator::createAdd(SD.SplitValue,
825 ConstantInt::get(Ty, 1, Sign),
826 "lsplit.add", PHTerminator);
830 case ICmpInst::ICMP_SGE:
831 case ICmpInst::ICMP_UGE:
833 // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
835 // is transformed into
837 // for (i = LB; i < min(UB, AEV); ++i)
839 // for (i = max(BSV, LB); i < UB; ++i)
842 case ICmpInst::ICMP_SGT:
843 case ICmpInst::ICMP_UGT:
846 // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
848 // is transformed into
850 // BSV = AEV = SV + 1
851 // for (i = LB; i < min(UB, AEV); ++i)
853 // for (i = max(LB, BSV); i < UB; ++i)
855 BSV = BinaryOperator::createAdd(SD.SplitValue,
856 ConstantInt::get(Ty, 1, Sign),
857 "lsplit.add", PHTerminator);
862 assert (0 && "Unexpected split condition predicate");
867 case ICmpInst::ICMP_SLE:
868 case ICmpInst::ICMP_ULE:
871 case ICmpInst::ICMP_SLT:
872 case ICmpInst::ICMP_ULT:
874 // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
876 // is transformed into
879 // for (i = LB; i <= min(UB, AEV); ++i)
881 // for (i = max(LB, BSV); i <= UB; ++i)
883 AEV = BinaryOperator::createSub(SD.SplitValue,
884 ConstantInt::get(Ty, 1, Sign),
885 "lsplit.sub", PHTerminator);
887 case ICmpInst::ICMP_SLE:
888 case ICmpInst::ICMP_ULE:
890 // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
892 // is transformed into
895 // for (i = LB; i <= min(UB, AEV); ++i)
897 // for (i = max(LB, BSV); i <= UB; ++i)
899 BSV = BinaryOperator::createAdd(SD.SplitValue,
900 ConstantInt::get(Ty, 1, Sign),
901 "lsplit.add", PHTerminator);
903 case ICmpInst::ICMP_SGT:
904 case ICmpInst::ICMP_UGT:
906 // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
908 // is transformed into
911 // for (i = LB; i <= min(AEV, UB); ++i)
913 // for (i = max(LB, BSV); i <= UB; ++i)
915 BSV = BinaryOperator::createAdd(SD.SplitValue,
916 ConstantInt::get(Ty, 1, Sign),
917 "lsplit.add", PHTerminator);
919 case ICmpInst::ICMP_SGE:
920 case ICmpInst::ICMP_UGE:
923 // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
925 // is transformed into
928 // for (i = LB; i <= min(AEV, UB); ++i)
930 // for (i = max(LB, BSV); i <= UB; ++i)
932 AEV = BinaryOperator::createSub(SD.SplitValue,
933 ConstantInt::get(Ty, 1, Sign),
934 "lsplit.sub", PHTerminator);
937 assert (0 && "Unexpected split condition predicate");
944 // Calculate ALoop induction variable's new exiting value and
945 // BLoop induction variable's new starting value. Calculuate these
946 // values in original loop's preheader.
947 // A_ExitValue = min(SplitValue, OrignalLoopExitValue)
948 // B_StartValue = max(SplitValue, OriginalLoopStartValue)
949 if (isa<ConstantInt>(SD.SplitValue)) {
950 SD.A_ExitValue = AEV;
951 SD.B_StartValue = BSV;
955 Value *C1 = new ICmpInst(Sign ?
956 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
958 ExitCondition->getOperand(ExitValueNum),
959 "lsplit.ev", PHTerminator);
960 SD.A_ExitValue = new SelectInst(C1, AEV,
961 ExitCondition->getOperand(ExitValueNum),
962 "lsplit.ev", PHTerminator);
964 Value *C2 = new ICmpInst(Sign ?
965 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
966 BSV, StartValue, "lsplit.sv",
968 SD.B_StartValue = new SelectInst(C2, StartValue, BSV,
969 "lsplit.sv", PHTerminator);
972 /// splitLoop - Split current loop L in two loops using split information
973 /// SD. Update dominator information. Maintain LCSSA form.
974 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
976 if (!safeSplitCondition(SD))
979 // After loop is cloned there are two loops.
981 // First loop, referred as ALoop, executes first part of loop's iteration
982 // space split. Second loop, referred as BLoop, executes remaining
983 // part of loop's iteration space.
985 // ALoop's exit edge enters BLoop's header through a forwarding block which
986 // acts as a BLoop's preheader.
987 BasicBlock *Preheader = L->getLoopPreheader();
989 // Calculate ALoop induction variable's new exiting value and
990 // BLoop induction variable's new starting value.
991 calculateLoopBounds(SD);
994 DenseMap<const Value *, Value *> ValueMap;
995 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
996 BasicBlock *B_Header = BLoop->getHeader();
998 //[*] ALoop's exiting edge BLoop's header.
999 // ALoop's original exit block becomes BLoop's exit block.
1000 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
1001 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
1002 BranchInst *A_ExitInsn =
1003 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
1004 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
1005 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
1006 if (L->contains(B_ExitBlock)) {
1007 B_ExitBlock = A_ExitInsn->getSuccessor(0);
1008 A_ExitInsn->setSuccessor(0, B_Header);
1010 A_ExitInsn->setSuccessor(1, B_Header);
1012 //[*] Update ALoop's exit value using new exit value.
1013 ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
1015 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
1016 // original loop's preheader. Add incoming PHINode values from
1017 // ALoop's exiting block. Update BLoop header's domiantor info.
1019 // Collect inverse map of Header PHINodes.
1020 DenseMap<Value *, Value *> InverseMap;
1021 for (BasicBlock::iterator BI = L->getHeader()->begin(),
1022 BE = L->getHeader()->end(); BI != BE; ++BI) {
1023 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1024 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
1025 InverseMap[PNClone] = PN;
1030 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1032 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1033 // Remove incoming value from original preheader.
1034 PN->removeIncomingValue(Preheader);
1036 // Add incoming value from A_ExitingBlock.
1038 PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
1040 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
1041 Value *V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
1042 PN->addIncoming(V2, A_ExitingBlock);
1047 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
1048 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
1050 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
1051 // block. Remove incoming PHINode values from ALoop's exiting block.
1052 // Add new incoming values from BLoop's incoming exiting value.
1053 // Update BLoop exit block's dominator info..
1054 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
1055 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
1057 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1058 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
1060 PN->removeIncomingValue(A_ExitingBlock);
1065 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
1066 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
1068 //[*] Split ALoop's exit edge. This creates a new block which
1069 // serves two purposes. First one is to hold PHINode defnitions
1070 // to ensure that ALoop's LCSSA form. Second use it to act
1071 // as a preheader for BLoop.
1072 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
1074 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
1075 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
1076 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
1078 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
1079 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
1080 PHINode *newPHI = new PHINode(PN->getType(), PN->getName());
1081 newPHI->addIncoming(V1, A_ExitingBlock);
1082 A_ExitBlock->getInstList().push_front(newPHI);
1083 PN->removeIncomingValue(A_ExitBlock);
1084 PN->addIncoming(newPHI, A_ExitBlock);
1089 //[*] Eliminate split condition's inactive branch from ALoop.
1090 BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
1091 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
1092 BasicBlock *A_InactiveBranch = NULL;
1093 BasicBlock *A_ActiveBranch = NULL;
1094 if (SD.UseTrueBranchFirst) {
1095 A_ActiveBranch = A_BR->getSuccessor(0);
1096 A_InactiveBranch = A_BR->getSuccessor(1);
1098 A_ActiveBranch = A_BR->getSuccessor(1);
1099 A_InactiveBranch = A_BR->getSuccessor(0);
1101 A_BR->setUnconditionalDest(A_ActiveBranch);
1102 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
1104 //[*] Eliminate split condition's inactive branch in from BLoop.
1105 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
1106 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
1107 BasicBlock *B_InactiveBranch = NULL;
1108 BasicBlock *B_ActiveBranch = NULL;
1109 if (SD.UseTrueBranchFirst) {
1110 B_ActiveBranch = B_BR->getSuccessor(1);
1111 B_InactiveBranch = B_BR->getSuccessor(0);
1113 B_ActiveBranch = B_BR->getSuccessor(0);
1114 B_InactiveBranch = B_BR->getSuccessor(1);
1116 B_BR->setUnconditionalDest(B_ActiveBranch);
1117 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);