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 /// safeSplitCondition - Return true if it is possible to
107 /// split loop using given split condition.
108 bool safeSplitCondition(SplitInfo &SD);
110 /// splitLoop - Split current loop L in two loops using split information
111 /// SD. Update dominator information. Maintain LCSSA form.
112 bool splitLoop(SplitInfo &SD);
116 IndVarIncrement = NULL;
117 ExitCondition = NULL;
131 DominanceFrontier *DF;
132 SmallVector<SplitInfo, 4> SplitData;
134 // Induction variable whose range is being split by this transformation.
136 Instruction *IndVarIncrement;
138 // Loop exit condition.
139 ICmpInst *ExitCondition;
141 // Induction variable's initial value.
144 // Induction variable's final loop exit value operand number in exit condition..
145 unsigned ExitValueNum;
148 char LoopIndexSplit::ID = 0;
149 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
152 LoopPass *llvm::createLoopIndexSplitPass() {
153 return new LoopIndexSplit();
156 // Index split Loop L. Return true if loop is split.
157 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
158 bool Changed = false;
162 // FIXME - Nested loops make dominator info updates tricky.
163 if (!L->getSubLoops().empty())
166 SE = &getAnalysis<ScalarEvolution>();
167 DT = &getAnalysis<DominatorTree>();
168 LI = &getAnalysis<LoopInfo>();
169 DF = &getAnalysis<DominanceFrontier>();
173 findLoopConditionals();
178 findSplitCondition();
180 if (SplitData.empty())
183 // First see if it is possible to eliminate loop itself or not.
184 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
185 E = SplitData.end(); SI != E;) {
187 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
188 Changed = processOneIterationLoop(SD);
191 // If is loop is eliminated then nothing else to do here.
194 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
196 SplitData.erase(Delete_SI);
202 // Split most profitiable condition.
203 // FIXME : Implement cost analysis.
204 unsigned MostProfitableSDIndex = 0;
205 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
213 /// Return true if V is a induction variable or induction variable's
214 /// increment for loop L.
215 void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
217 Instruction *I = dyn_cast<Instruction>(V);
221 // Check if I is a phi node from loop header or not.
222 if (PHINode *PN = dyn_cast<PHINode>(V)) {
223 if (PN->getParent() == L->getHeader()) {
229 // Check if I is a add instruction whose one operand is
230 // phi node from loop header and second operand is constant.
231 if (I->getOpcode() != Instruction::Add)
234 Value *Op0 = I->getOperand(0);
235 Value *Op1 = I->getOperand(1);
237 if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
238 if (PN->getParent() == L->getHeader()
239 && isa<ConstantInt>(Op1)) {
246 if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
247 if (PN->getParent() == L->getHeader()
248 && isa<ConstantInt>(Op0)) {
258 // Find loop's exit condition and associated induction variable.
259 void LoopIndexSplit::findLoopConditionals() {
261 BasicBlock *ExitingBlock = NULL;
263 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
266 if (!L->isLoopExit(BB))
276 // If exiting block is neither loop header nor loop latch then this loop is
278 if (ExitingBlock != L->getHeader() && ExitingBlock != L->getLoopLatch())
281 // If exit block's terminator is conditional branch inst then we have found
283 BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
284 if (!BR || BR->isUnconditional())
287 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
293 // Exit condition's one operand is loop invariant exit value and second
294 // operand is SCEVAddRecExpr based on induction variable.
295 Value *V0 = CI->getOperand(0);
296 Value *V1 = CI->getOperand(1);
298 SCEVHandle SH0 = SE->getSCEV(V0);
299 SCEVHandle SH1 = SE->getSCEV(V1);
301 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
305 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
311 ExitCondition = NULL;
313 BasicBlock *Preheader = L->getLoopPreheader();
314 StartValue = IndVar->getIncomingValueForBlock(Preheader);
318 /// Find condition inside a loop that is suitable candidate for index split.
319 void LoopIndexSplit::findSplitCondition() {
322 // Check all basic block's terminators.
324 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
328 // If this basic block does not terminate in a conditional branch
329 // then terminator is not a suitable split condition.
330 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
334 if (BR->isUnconditional())
337 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
338 if (!CI || CI == ExitCondition)
341 // If one operand is loop invariant and second operand is SCEVAddRecExpr
342 // based on induction variable then CI is a candidate split condition.
343 Value *V0 = CI->getOperand(0);
344 Value *V1 = CI->getOperand(1);
346 SCEVHandle SH0 = SE->getSCEV(V0);
347 SCEVHandle SH1 = SE->getSCEV(V1);
349 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
351 SD.SplitCondition = CI;
352 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
354 SplitData.push_back(SD);
356 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
357 if (IndVarIncrement && IndVarIncrement == Insn)
358 SplitData.push_back(SD);
361 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
363 SD.SplitCondition = CI;
364 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
366 SplitData.push_back(SD);
368 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
369 if (IndVarIncrement && IndVarIncrement == Insn)
370 SplitData.push_back(SD);
376 /// processOneIterationLoop - Current loop L contains compare instruction
377 /// that compares induction variable, IndVar, against loop invariant. If
378 /// entire (i.e. meaningful) loop body is dominated by this compare
379 /// instruction then loop body is executed only once. In such case eliminate
380 /// loop structure surrounding this loop body. For example,
381 /// for (int i = start; i < end; ++i) {
382 /// if ( i == somevalue) {
386 /// can be transformed into
387 /// if (somevalue >= start && somevalue < end) {
391 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
393 BasicBlock *Header = L->getHeader();
395 // First of all, check if SplitCondition dominates entire loop body
398 // If SplitCondition is not in loop header then this loop is not suitable
399 // for this transformation.
400 if (SD.SplitCondition->getParent() != Header)
403 // If loop header includes loop variant instruction operands then
404 // this loop may not be eliminated.
405 if (!safeHeader(SD, Header))
408 // If Exiting block includes loop variant instructions then this
409 // loop may not be eliminated.
410 if (!safeExitingBlock(SD, ExitCondition->getParent()))
415 // Replace index variable with split value in loop body. Loop body is executed
416 // only when index variable is equal to split value.
417 IndVar->replaceAllUsesWith(SD.SplitValue);
419 // Remove Latch to Header edge.
420 BasicBlock *Latch = L->getLoopLatch();
421 BasicBlock *LatchSucc = NULL;
422 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
425 Header->removePredecessor(Latch);
426 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
431 BR->setUnconditionalDest(LatchSucc);
433 Instruction *Terminator = Header->getTerminator();
434 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
436 // Replace split condition in header.
438 // SplitCondition : icmp eq i32 IndVar, SplitValue
440 // c1 = icmp uge i32 SplitValue, StartValue
441 // c2 = icmp ult i32 vSplitValue, ExitValue
443 bool SignedPredicate = ExitCondition->isSignedPredicate();
444 Instruction *C1 = new ICmpInst(SignedPredicate ?
445 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
446 SD.SplitValue, StartValue, "lisplit",
448 Instruction *C2 = new ICmpInst(SignedPredicate ?
449 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
450 SD.SplitValue, ExitValue, "lisplit",
452 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
454 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
455 SD.SplitCondition->eraseFromParent();
457 // Now, clear latch block. Remove instructions that are responsible
458 // to increment induction variable.
459 Instruction *LTerminator = Latch->getTerminator();
460 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
464 if (isa<PHINode>(I) || I == LTerminator)
467 if (I == IndVarIncrement)
468 I->replaceAllUsesWith(ExitValue);
470 I->replaceAllUsesWith(UndefValue::get(I->getType()));
471 I->eraseFromParent();
474 LPM->deleteLoopFromQueue(L);
476 // Update Dominator Info.
477 // Only CFG change done is to remove Latch to Header edge. This
478 // does not change dominator tree because Latch did not dominate
481 DominanceFrontier::iterator HeaderDF = DF->find(Header);
482 if (HeaderDF != DF->end())
483 DF->removeFromFrontier(HeaderDF, Header);
485 DominanceFrontier::iterator LatchDF = DF->find(Latch);
486 if (LatchDF != DF->end())
487 DF->removeFromFrontier(LatchDF, Header);
492 // If loop header includes loop variant instruction operands then
493 // this loop can not be eliminated. This is used by processOneIterationLoop().
494 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
496 Instruction *Terminator = Header->getTerminator();
497 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
505 // SplitCondition itself is OK.
506 if (I == SD.SplitCondition)
509 // Induction variable is OK.
513 // Induction variable increment is OK.
514 if (I == IndVarIncrement)
517 // Terminator is also harmless.
521 // Otherwise we have a instruction that may not be safe.
528 // If Exiting block includes loop variant instructions then this
529 // loop may not be eliminated. This is used by processOneIterationLoop().
530 bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD,
531 BasicBlock *ExitingBlock) {
533 for (BasicBlock::iterator BI = ExitingBlock->begin(),
534 BE = ExitingBlock->end(); BI != BE; ++BI) {
541 // Induction variable increment is OK.
542 if (IndVarIncrement && IndVarIncrement == I)
545 // Check if I is induction variable increment instruction.
546 if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
548 Value *Op0 = I->getOperand(0);
549 Value *Op1 = I->getOperand(1);
551 ConstantInt *CI = NULL;
553 if ((PN = dyn_cast<PHINode>(Op0))) {
554 if ((CI = dyn_cast<ConstantInt>(Op1)))
557 if ((PN = dyn_cast<PHINode>(Op1))) {
558 if ((CI = dyn_cast<ConstantInt>(Op0)))
562 if (IndVarIncrement && PN == IndVar && CI->isOne())
566 // I is an Exit condition if next instruction is block terminator.
567 // Exit condition is OK if it compares loop invariant exit value,
568 // which is checked below.
569 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
570 if (EC == ExitCondition)
574 if (I == ExitingBlock->getTerminator())
577 // Otherwise we have instruction that may not be safe.
581 // We could not find any reason to consider ExitingBlock unsafe.
585 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
586 /// This routine is used to remove split condition's dead branch, dominated by
587 /// DeadBB. LiveBB dominates split conidition's other branch.
588 void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
589 BasicBlock *LiveBB) {
591 // First update DeadBB's dominance frontier.
592 SmallVector<BasicBlock *, 8> FrontierBBs;
593 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
594 if (DeadBBDF != DF->end()) {
595 SmallVector<BasicBlock *, 8> PredBlocks;
597 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
598 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
599 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
600 BasicBlock *FrontierBB = *DeadBBSetI;
601 FrontierBBs.push_back(FrontierBB);
603 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
605 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
608 if (P == DeadBB || DT->dominates(DeadBB, P))
609 PredBlocks.push_back(P);
612 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
614 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
615 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
616 PE = PredBlocks.end(); PI != PE; ++PI) {
618 PN->removeIncomingValue(P);
627 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
628 SmallVector<BasicBlock *, 32> WorkList;
629 DomTreeNode *DN = DT->getNode(DeadBB);
630 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
631 E = df_end(DN); DI != E; ++DI) {
632 BasicBlock *BB = DI->getBlock();
633 WorkList.push_back(BB);
634 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
637 while (!WorkList.empty()) {
638 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
639 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
641 Instruction *I = BBI;
642 I->replaceAllUsesWith(UndefValue::get(I->getType()));
643 I->eraseFromParent();
645 LPM->deleteSimpleAnalysisValue(BB, LP);
649 BB->eraseFromParent();
652 // Update Frontier BBs' dominator info.
653 while (!FrontierBBs.empty()) {
654 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
655 BasicBlock *NewDominator = FBB->getSinglePredecessor();
657 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
660 if (NewDominator != LiveBB) {
661 for(; PI != PE; ++PI) {
664 NewDominator = LiveBB;
667 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
671 assert (NewDominator && "Unable to fix dominator info.");
672 DT->changeImmediateDominator(FBB, NewDominator);
673 DF->changeImmediateDominator(FBB, NewDominator, DT);
678 /// safeSplitCondition - Return true if it is possible to
679 /// split loop using given split condition.
680 bool LoopIndexSplit::safeSplitCondition(SplitInfo &SD) {
682 BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
684 // Unable to handle triange loops at the moment.
685 // In triangle loop, split condition is in header and one of the
686 // the split destination is loop latch. If split condition is EQ
687 // then such loops are already handle in processOneIterationLoop().
688 BasicBlock *Latch = L->getLoopLatch();
689 BranchInst *SplitTerminator =
690 cast<BranchInst>(SplitCondBlock->getTerminator());
691 BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
692 BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
693 if (L->getHeader() == SplitCondBlock
694 && (Latch == Succ0 || Latch == Succ1))
697 // If one of the split condition branch is post dominating other then loop
698 // index split is not appropriate.
699 if (DT->dominates(Succ0, Latch) || DT->dominates(Succ1, Latch))
702 // If one of the split condition branch is a predecessor of the other
703 // split condition branch head then do not split loop on this condition.
704 for(pred_iterator PI = pred_begin(Succ0), PE = pred_end(Succ0);
708 for(pred_iterator PI = pred_begin(Succ1), PE = pred_end(Succ1);
713 // Finally this split condition is safe only if merge point for
714 // split condition branch is loop latch. This check along with previous
715 // check, to ensure that exit condition is in either loop latch or header,
716 // filters all loops with non-empty loop body between merge point
717 // and exit condition.
718 DominanceFrontier::iterator Succ0DF = DF->find(Succ0);
719 assert (Succ0DF != DF->end() && "Unable to find Succ0 dominance frontier");
720 if (Succ0DF->second.count(Latch))
723 DominanceFrontier::iterator Succ1DF = DF->find(Succ1);
724 assert (Succ1DF != DF->end() && "Unable to find Succ1 dominance frontier");
725 if (Succ1DF->second.count(Latch))
731 /// splitLoop - Split current loop L in two loops using split information
732 /// SD. Update dominator information. Maintain LCSSA form.
733 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
735 if (!safeSplitCondition(SD))
738 // After loop is cloned there are two loops.
740 // First loop, referred as ALoop, executes first part of loop's iteration
741 // space split. Second loop, referred as BLoop, executes remaining
742 // part of loop's iteration space.
744 // ALoop's exit edge enters BLoop's header through a forwarding block which
745 // acts as a BLoop's preheader.
747 //[*] Calculate ALoop induction variable's new exiting value and
748 // BLoop induction variable's new starting value. Calculuate these
749 // values in original loop's preheader.
750 // A_ExitValue = min(SplitValue, OrignalLoopExitValue)
751 // B_StartValue = max(SplitValue, OriginalLoopStartValue)
752 Value *A_ExitValue = NULL;
753 Value *B_StartValue = NULL;
754 if (isa<ConstantInt>(SD.SplitValue)) {
755 A_ExitValue = SD.SplitValue;
756 B_StartValue = SD.SplitValue;
759 BasicBlock *Preheader = L->getLoopPreheader();
760 Instruction *PHTerminator = Preheader->getTerminator();
761 bool SignedPredicate = ExitCondition->isSignedPredicate();
762 Value *C1 = new ICmpInst(SignedPredicate ?
763 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
765 ExitCondition->getOperand(ExitValueNum),
766 "lsplit.ev", PHTerminator);
767 A_ExitValue = new SelectInst(C1, SD.SplitValue,
768 ExitCondition->getOperand(ExitValueNum),
769 "lsplit.ev", PHTerminator);
771 Value *C2 = new ICmpInst(SignedPredicate ?
772 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
773 SD.SplitValue, StartValue, "lsplit.sv",
775 B_StartValue = new SelectInst(C2, StartValue, SD.SplitValue,
776 "lsplit.sv", PHTerminator);
780 DenseMap<const Value *, Value *> ValueMap;
781 Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
782 BasicBlock *B_Header = BLoop->getHeader();
784 //[*] ALoop's exiting edge BLoop's header.
785 // ALoop's original exit block becomes BLoop's exit block.
786 PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
787 BasicBlock *A_ExitingBlock = ExitCondition->getParent();
788 BranchInst *A_ExitInsn =
789 dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
790 assert (A_ExitInsn && "Unable to find suitable loop exit branch");
791 BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
792 if (L->contains(B_ExitBlock)) {
793 B_ExitBlock = A_ExitInsn->getSuccessor(0);
794 A_ExitInsn->setSuccessor(0, B_Header);
796 A_ExitInsn->setSuccessor(1, B_Header);
798 //[*] Update ALoop's exit value using new exit value.
799 ExitCondition->setOperand(ExitValueNum, A_ExitValue);
801 // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
802 // original loop's preheader. Add incoming PHINode values from
803 // ALoop's exiting block. Update BLoop header's domiantor info.
805 // Collect inverse map of Header PHINodes.
806 DenseMap<Value *, Value *> InverseMap;
807 for (BasicBlock::iterator BI = L->getHeader()->begin(),
808 BE = L->getHeader()->end(); BI != BE; ++BI) {
809 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
810 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
811 InverseMap[PNClone] = PN;
815 BasicBlock *Preheader = L->getLoopPreheader();
816 for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
818 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
819 // Remove incoming value from original preheader.
820 PN->removeIncomingValue(Preheader);
822 // Add incoming value from A_ExitingBlock.
824 PN->addIncoming(B_StartValue, A_ExitingBlock);
826 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
827 Value *V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
828 PN->addIncoming(V2, A_ExitingBlock);
833 DT->changeImmediateDominator(B_Header, A_ExitingBlock);
834 DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
836 // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
837 // block. Remove incoming PHINode values from ALoop's exiting block.
838 // Add new incoming values from BLoop's incoming exiting value.
839 // Update BLoop exit block's dominator info..
840 BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
841 for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
843 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
844 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
846 PN->removeIncomingValue(A_ExitingBlock);
851 DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
852 DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
854 //[*] Split ALoop's exit edge. This creates a new block which
855 // serves two purposes. First one is to hold PHINode defnitions
856 // to ensure that ALoop's LCSSA form. Second use it to act
857 // as a preheader for BLoop.
858 BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
860 //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
861 // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
862 for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
864 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
865 Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
866 PHINode *newPHI = new PHINode(PN->getType(), PN->getName());
867 newPHI->addIncoming(V1, A_ExitingBlock);
868 A_ExitBlock->getInstList().push_front(newPHI);
869 PN->removeIncomingValue(A_ExitBlock);
870 PN->addIncoming(newPHI, A_ExitBlock);
875 //[*] Eliminate split condition's inactive branch from ALoop.
876 BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
877 BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
878 BasicBlock *A_InactiveBranch = A_BR->getSuccessor(1);
879 BasicBlock *A_ActiveBranch = A_BR->getSuccessor(0);
880 A_BR->setUnconditionalDest(A_BR->getSuccessor(0));
881 removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
883 //[*] Eliminate split condition's inactive branch in from BLoop.
884 BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
885 BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
886 BasicBlock *B_InactiveBranch = B_BR->getSuccessor(0);
887 BasicBlock *B_ActiveBranch = B_BR->getSuccessor(1);
888 B_BR->setUnconditionalDest(B_BR->getSuccessor(1));
889 removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);