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) {}
62 // Induction variable's range is split at this value.
65 // This compare instruction compares IndVar against SplitValue.
66 ICmpInst *SplitCondition;
71 SplitCondition = NULL;
77 /// Find condition inside a loop that is suitable candidate for index split.
78 void findSplitCondition();
80 /// Find loop's exit condition.
81 void findLoopConditionals();
83 /// Return induction variable associated with value V.
84 void findIndVar(Value *V, Loop *L);
86 /// processOneIterationLoop - Current loop L contains compare instruction
87 /// that compares induction variable, IndVar, agains loop invariant. If
88 /// entire (i.e. meaningful) loop body is dominated by this compare
89 /// instruction then loop body is executed only for one iteration. In
90 /// such case eliminate loop structure surrounding this loop body. For
91 bool processOneIterationLoop(SplitInfo &SD);
93 /// If loop header includes loop variant instruction operands then
94 /// this loop may not be eliminated.
95 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
97 /// If Exiting block includes loop variant instructions then this
98 /// loop may not be eliminated.
99 bool safeExitingBlock(SplitInfo &SD, BasicBlock *BB);
101 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
102 /// This routine is used to remove split condition's dead branch, dominated by
103 /// DeadBB. LiveBB dominates split conidition's other branch.
104 void removeBlocks(BasicBlock *DeadBB, Loop *LP, BasicBlock *LiveBB);
106 /// Find cost of spliting loop L.
107 unsigned findSplitCost(Loop *L, SplitInfo &SD);
109 /// safeSplitCondition - Return true if it is possible to
110 /// split loop using given split condition.
111 bool safeSplitCondition(SplitInfo &SD);
113 /// splitLoop - Split current loop L in two loops using split information
114 /// SD. Update dominator information. Maintain LCSSA form.
115 bool splitLoop(SplitInfo &SD);
119 IndVarIncrement = NULL;
120 ExitCondition = NULL;
134 DominanceFrontier *DF;
135 SmallVector<SplitInfo, 4> SplitData;
137 // Induction variable whose range is being split by this transformation.
139 Instruction *IndVarIncrement;
141 // Loop exit condition.
142 ICmpInst *ExitCondition;
144 // Induction variable's initial value.
147 // Induction variable's final loop exit value operand number in exit condition..
148 unsigned ExitValueNum;
151 char LoopIndexSplit::ID = 0;
152 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
155 LoopPass *llvm::createLoopIndexSplitPass() {
156 return new LoopIndexSplit();
159 // Index split Loop L. Return true if loop is split.
160 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
161 bool Changed = false;
165 // FIXME - Nested loops make dominator info updates tricky.
166 if (!L->getSubLoops().empty())
169 SE = &getAnalysis<ScalarEvolution>();
170 DT = &getAnalysis<DominatorTree>();
171 LI = &getAnalysis<LoopInfo>();
172 DF = &getAnalysis<DominanceFrontier>();
176 findLoopConditionals();
181 findSplitCondition();
183 if (SplitData.empty())
186 // First see if it is possible to eliminate loop itself or not.
187 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
188 E = SplitData.end(); SI != E;) {
190 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
191 Changed = processOneIterationLoop(SD);
194 // If is loop is eliminated then nothing else to do here.
197 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
199 SplitData.erase(Delete_SI);
205 unsigned MaxCost = 99;
207 unsigned MostProfitableSDIndex = 0;
208 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
209 E = SplitData.end(); SI != E; ++SI, ++Index) {
212 // ICM_EQs are already handled above.
213 assert (SD.SplitCondition->getPredicate() != ICmpInst::ICMP_EQ &&
214 "Unexpected split condition predicate");
216 unsigned Cost = findSplitCost(L, SD);
218 MostProfitableSDIndex = Index;
221 // Split most profitiable condition.
222 if (!SplitData.empty())
223 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
231 /// Return true if V is a induction variable or induction variable's
232 /// increment for loop L.
233 void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
235 Instruction *I = dyn_cast<Instruction>(V);
239 // Check if I is a phi node from loop header or not.
240 if (PHINode *PN = dyn_cast<PHINode>(V)) {
241 if (PN->getParent() == L->getHeader()) {
247 // Check if I is a add instruction whose one operand is
248 // phi node from loop header and second operand is constant.
249 if (I->getOpcode() != Instruction::Add)
252 Value *Op0 = I->getOperand(0);
253 Value *Op1 = I->getOperand(1);
255 if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
256 if (PN->getParent() == L->getHeader()
257 && isa<ConstantInt>(Op1)) {
264 if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
265 if (PN->getParent() == L->getHeader()
266 && isa<ConstantInt>(Op0)) {
276 // Find loop's exit condition and associated induction variable.
277 void LoopIndexSplit::findLoopConditionals() {
279 BasicBlock *ExitingBlock = NULL;
281 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
284 if (!L->isLoopExit(BB))
294 // If exit block's terminator is conditional branch inst then we have found
296 BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
297 if (!BR || BR->isUnconditional())
300 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
306 // Exit condition's one operand is loop invariant exit value and second
307 // operand is SCEVAddRecExpr based on induction variable.
308 Value *V0 = CI->getOperand(0);
309 Value *V1 = CI->getOperand(1);
311 SCEVHandle SH0 = SE->getSCEV(V0);
312 SCEVHandle SH1 = SE->getSCEV(V1);
314 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
318 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
324 ExitCondition = NULL;
326 BasicBlock *Preheader = L->getLoopPreheader();
327 StartValue = IndVar->getIncomingValueForBlock(Preheader);
331 /// Find condition inside a loop that is suitable candidate for index split.
332 void LoopIndexSplit::findSplitCondition() {
335 // Check all basic block's terminators.
337 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
341 // If this basic block does not terminate in a conditional branch
342 // then terminator is not a suitable split condition.
343 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
347 if (BR->isUnconditional())
350 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
351 if (!CI || CI == ExitCondition)
354 // If one operand is loop invariant and second operand is SCEVAddRecExpr
355 // based on induction variable then CI is a candidate split condition.
356 Value *V0 = CI->getOperand(0);
357 Value *V1 = CI->getOperand(1);
359 SCEVHandle SH0 = SE->getSCEV(V0);
360 SCEVHandle SH1 = SE->getSCEV(V1);
362 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
364 SD.SplitCondition = CI;
365 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
367 SplitData.push_back(SD);
369 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
370 if (IndVarIncrement && IndVarIncrement == Insn)
371 SplitData.push_back(SD);
374 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
376 SD.SplitCondition = CI;
377 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
379 SplitData.push_back(SD);
381 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
382 if (IndVarIncrement && IndVarIncrement == Insn)
383 SplitData.push_back(SD);
389 /// processOneIterationLoop - Current loop L contains compare instruction
390 /// that compares induction variable, IndVar, against loop invariant. If
391 /// entire (i.e. meaningful) loop body is dominated by this compare
392 /// instruction then loop body is executed only once. In such case eliminate
393 /// loop structure surrounding this loop body. For example,
394 /// for (int i = start; i < end; ++i) {
395 /// if ( i == somevalue) {
399 /// can be transformed into
400 /// if (somevalue >= start && somevalue < end) {
404 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
406 BasicBlock *Header = L->getHeader();
408 // First of all, check if SplitCondition dominates entire loop body
411 // If SplitCondition is not in loop header then this loop is not suitable
412 // for this transformation.
413 if (SD.SplitCondition->getParent() != Header)
416 // If loop header includes loop variant instruction operands then
417 // this loop may not be eliminated.
418 if (!safeHeader(SD, Header))
421 // If Exiting block includes loop variant instructions then this
422 // loop may not be eliminated.
423 if (!safeExitingBlock(SD, ExitCondition->getParent()))
428 // Replace index variable with split value in loop body. Loop body is executed
429 // only when index variable is equal to split value.
430 IndVar->replaceAllUsesWith(SD.SplitValue);
432 // Remove Latch to Header edge.
433 BasicBlock *Latch = L->getLoopLatch();
434 BasicBlock *LatchSucc = NULL;
435 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
438 Header->removePredecessor(Latch);
439 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
444 BR->setUnconditionalDest(LatchSucc);
446 Instruction *Terminator = Header->getTerminator();
447 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
449 // Replace split condition in header.
451 // SplitCondition : icmp eq i32 IndVar, SplitValue
453 // c1 = icmp uge i32 SplitValue, StartValue
454 // c2 = icmp ult i32 vSplitValue, ExitValue
456 bool SignedPredicate = ExitCondition->isSignedPredicate();
457 Instruction *C1 = new ICmpInst(SignedPredicate ?
458 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
459 SD.SplitValue, StartValue, "lisplit",
461 Instruction *C2 = new ICmpInst(SignedPredicate ?
462 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
463 SD.SplitValue, ExitValue, "lisplit",
465 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
467 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
468 SD.SplitCondition->eraseFromParent();
470 // Now, clear latch block. Remove instructions that are responsible
471 // to increment induction variable.
472 Instruction *LTerminator = Latch->getTerminator();
473 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
477 if (isa<PHINode>(I) || I == LTerminator)
480 if (I == IndVarIncrement)
481 I->replaceAllUsesWith(ExitValue);
483 I->replaceAllUsesWith(UndefValue::get(I->getType()));
484 I->eraseFromParent();
487 LPM->deleteLoopFromQueue(L);
489 // Update Dominator Info.
490 // Only CFG change done is to remove Latch to Header edge. This
491 // does not change dominator tree because Latch did not dominate
494 DominanceFrontier::iterator HeaderDF = DF->find(Header);
495 if (HeaderDF != DF->end())
496 DF->removeFromFrontier(HeaderDF, Header);
498 DominanceFrontier::iterator LatchDF = DF->find(Latch);
499 if (LatchDF != DF->end())
500 DF->removeFromFrontier(LatchDF, Header);
505 // If loop header includes loop variant instruction operands then
506 // this loop can not be eliminated. This is used by processOneIterationLoop().
507 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
509 Instruction *Terminator = Header->getTerminator();
510 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
518 // SplitCondition itself is OK.
519 if (I == SD.SplitCondition)
522 // Induction variable is OK.
526 // Induction variable increment is OK.
527 if (I == IndVarIncrement)
530 // Terminator is also harmless.
534 // Otherwise we have a instruction that may not be safe.
541 // If Exiting block includes loop variant instructions then this
542 // loop may not be eliminated. This is used by processOneIterationLoop().
543 bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD,
544 BasicBlock *ExitingBlock) {
546 for (BasicBlock::iterator BI = ExitingBlock->begin(),
547 BE = ExitingBlock->end(); BI != BE; ++BI) {
554 // Induction variable increment is OK.
555 if (IndVarIncrement && IndVarIncrement == I)
558 // Check if I is induction variable increment instruction.
559 if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
561 Value *Op0 = I->getOperand(0);
562 Value *Op1 = I->getOperand(1);
564 ConstantInt *CI = NULL;
566 if ((PN = dyn_cast<PHINode>(Op0))) {
567 if ((CI = dyn_cast<ConstantInt>(Op1)))
570 if ((PN = dyn_cast<PHINode>(Op1))) {
571 if ((CI = dyn_cast<ConstantInt>(Op0)))
575 if (IndVarIncrement && PN == IndVar && CI->isOne())
579 // I is an Exit condition if next instruction is block terminator.
580 // Exit condition is OK if it compares loop invariant exit value,
581 // which is checked below.
582 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
583 if (EC == ExitCondition)
587 if (I == ExitingBlock->getTerminator())
590 // Otherwise we have instruction that may not be safe.
594 // We could not find any reason to consider ExitingBlock unsafe.
598 /// Find cost of spliting loop L. Cost is measured in terms of size growth.
599 /// Size is growth is calculated based on amount of code duplicated in second
601 unsigned LoopIndexSplit::findSplitCost(Loop *L, SplitInfo &SD) {
604 BasicBlock *SDBlock = SD.SplitCondition->getParent();
605 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
608 // If a block is not dominated by split condition block then
609 // it must be duplicated in both loops.
610 if (!DT->dominates(SDBlock, BB))
617 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
618 /// This routine is used to remove split condition's dead branch, dominated by
619 /// DeadBB. LiveBB dominates split conidition's other branch.
620 void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
621 BasicBlock *LiveBB) {
623 // First update DeadBB's dominance frontier.
624 SmallVector<BasicBlock *, 8> FrontierBBs;
625 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
626 if (DeadBBDF != DF->end()) {
627 SmallVector<BasicBlock *, 8> PredBlocks;
629 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
630 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
631 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
632 BasicBlock *FrontierBB = *DeadBBSetI;
633 FrontierBBs.push_back(FrontierBB);
635 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
637 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
640 if (P == DeadBB || DT->dominates(DeadBB, P))
641 PredBlocks.push_back(P);
644 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
646 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
647 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
648 PE = PredBlocks.end(); PI != PE; ++PI) {
650 PN->removeIncomingValue(P);
659 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
660 SmallVector<BasicBlock *, 32> WorkList;
661 DomTreeNode *DN = DT->getNode(DeadBB);
662 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
663 E = df_end(DN); DI != E; ++DI) {
664 BasicBlock *BB = DI->getBlock();
665 WorkList.push_back(BB);
666 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
669 while (!WorkList.empty()) {
670 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
671 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
673 Instruction *I = BBI;
674 I->replaceAllUsesWith(UndefValue::get(I->getType()));
675 I->eraseFromParent();
677 LPM->deleteSimpleAnalysisValue(BB, LP);
681 BB->eraseFromParent();
684 // Update Frontier BBs' dominator info.
685 while (!FrontierBBs.empty()) {
686 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
687 BasicBlock *NewDominator = FBB->getSinglePredecessor();
689 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
692 if (NewDominator != LiveBB) {
693 for(; PI != PE; ++PI) {
696 NewDominator = LiveBB;
699 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
703 assert (NewDominator && "Unable to fix dominator info.");
704 DT->changeImmediateDominator(FBB, NewDominator);
705 DF->changeImmediateDominator(FBB, NewDominator, DT);
710 /// safeSplitCondition - Return true if it is possible to
711 /// split loop using given split condition.
712 bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
714 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
716 // Unable to handle triange loops at the moment.
717 // In triangle loop, split condition is in header and one of the
718 // the split destination is loop latch. If split condition is EQ
719 // then such loops are already handle in processOneIterationLoop().
720 BasicBlock *Latch = L->getLoopLatch();
721 BranchInst *SplitTerminator =
722 cast<BranchInst>(SplitCondBlock->getTerminator());
723 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
724 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
725 if (L->getHeader() == SplitCondBlock
726 && (Latch == Succ0 || Latch == Succ1))
729 // If one of the split condition branch is post dominating other then loop
730 // index split is not appropriate.
731 if (DT->dominates(Succ0, Latch) || DT->dominates(Succ1, Latch))
734 // If one of the split condition branch is a predecessor of the other
735 // split condition branch head then do not split loop on this condition.
736 for(pred_iterator PI = pred_begin(Succ0), PE = pred_end(Succ0);
740 for(pred_iterator PI = pred_begin(Succ1), PE = pred_end(Succ1);
748 /// splitLoop - Split current loop L in two loops using split information
749 /// SD. Update dominator information. Maintain LCSSA form.
750 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
752 if (!safeSplitCondition(SD))
755 // After loop is cloned there are two loops.
757 // First loop, referred as ALoop, executes first part of loop's iteration
758 // space split. Second loop, referred as BLoop, executes remaining
759 // part of loop's iteration space.
761 // ALoop's exit edge enters BLoop's header through a forwarding block which
762 // acts as a BLoop's preheader.
764 //[*] Calculate ALoop induction variable's new exiting value and
765 // BLoop induction variable's new starting value. Calculuate these
766 // values in original loop's preheader.
767 // A_ExitValue = min(SplitValue, OrignalLoopExitValue)
768 // B_StartValue = max(SplitValue, OriginalLoopStartValue)
769 Value *A_ExitValue = NULL;
770 Value *B_StartValue = NULL;
771 if (isa<ConstantInt>(SD.SplitValue)) {
772 A_ExitValue = SD.SplitValue;
773 B_StartValue = SD.SplitValue;
776 BasicBlock *Preheader = L->getLoopPreheader();
777 Instruction *PHTerminator = Preheader->getTerminator();
778 bool SignedPredicate = ExitCondition->isSignedPredicate();
779 Value *C1 = new ICmpInst(SignedPredicate ?
780 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
782 ExitCondition->getOperand(ExitValueNum),
783 "lsplit.ev", PHTerminator);
784 A_ExitValue = new SelectInst(C1, SD.SplitValue,
785 ExitCondition->getOperand(ExitValueNum),
786 "lsplit.ev", PHTerminator);
788 Value *C2 = new ICmpInst(SignedPredicate ?
789 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
790 SD.SplitValue, StartValue, "lsplit.sv",
792 B_StartValue = new SelectInst(C2, StartValue, SD.SplitValue,
793 "lsplit.sv", PHTerminator);
797 DenseMap<const Value *, Value *> ValueMap;
798 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
799 BasicBlock *B_Header = BLoop->getHeader();
801 //[*] ALoop's exiting edge BLoop's header.
802 // ALoop's original exit block becomes BLoop's exit block.
803 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
804 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
805 BranchInst *A_ExitInsn =
806 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
807 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
808 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
809 if (L->contains(B_ExitBlock)) {
810 B_ExitBlock = A_ExitInsn->getSuccessor(0);
811 A_ExitInsn->setSuccessor(0, B_Header);
813 A_ExitInsn->setSuccessor(1, B_Header);
815 //[*] Update ALoop's exit value using new exit value.
816 ExitCondition->setOperand(ExitValueNum, A_ExitValue);
818 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
819 // original loop's preheader. Add incoming PHINode values from
820 // ALoop's exiting block. Update BLoop header's domiantor info.
822 // Collect inverse map of Header PHINodes.
823 DenseMap<Value *, Value *> InverseMap;
824 for (BasicBlock::iterator BI = L->getHeader()->begin(),
825 BE = L->getHeader()->end(); BI != BE; ++BI) {
826 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
827 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
828 InverseMap[PNClone] = PN;
832 BasicBlock *Preheader = L->getLoopPreheader();
833 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
835 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
836 // Remove incoming value from original preheader.
837 PN->removeIncomingValue(Preheader);
839 // Add incoming value from A_ExitingBlock.
841 PN->addIncoming(B_StartValue, A_ExitingBlock);
843 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
844 Value *V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
845 PN->addIncoming(V2, A_ExitingBlock);
850 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
851 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
853 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
854 // block. Remove incoming PHINode values from ALoop's exiting block.
855 // Add new incoming values from BLoop's incoming exiting value.
856 // Update BLoop exit block's dominator info..
857 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
858 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
860 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
861 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
863 PN->removeIncomingValue(A_ExitingBlock);
868 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
869 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
871 //[*] Split ALoop's exit edge. This creates a new block which
872 // serves two purposes. First one is to hold PHINode defnitions
873 // to ensure that ALoop's LCSSA form. Second use it to act
874 // as a preheader for BLoop.
875 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
877 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
878 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
879 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
881 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
882 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
883 PHINode *newPHI = new PHINode(PN->getType(), PN->getName());
884 newPHI->addIncoming(V1, A_ExitingBlock);
885 A_ExitBlock->getInstList().push_front(newPHI);
886 PN->removeIncomingValue(A_ExitBlock);
887 PN->addIncoming(newPHI, A_ExitBlock);
892 //[*] Eliminate split condition's inactive branch from ALoop.
893 BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
894 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
895 BasicBlock *A_InactiveBranch = A_BR->getSuccessor(1);
896 BasicBlock *A_ActiveBranch = A_BR->getSuccessor(0);
897 A_BR->setUnconditionalDest(A_BR->getSuccessor(0));
898 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
900 //[*] Eliminate split condition's inactive branch in from BLoop.
901 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
902 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
903 BasicBlock *B_InactiveBranch = B_BR->getSuccessor(0);
904 BasicBlock *B_ActiveBranch = B_BR->getSuccessor(1);
905 B_BR->setUnconditionalDest(B_BR->getSuccessor(1));
906 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);