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);
108 bool splitLoop(SplitInfo &SD);
112 IndVarIncrement = NULL;
113 ExitCondition = NULL;
127 DominanceFrontier *DF;
128 SmallVector<SplitInfo, 4> SplitData;
130 // Induction variable whose range is being split by this transformation.
132 Instruction *IndVarIncrement;
134 // Loop exit condition.
135 ICmpInst *ExitCondition;
137 // Induction variable's initial value.
140 // Induction variable's final loop exit value operand number in exit condition..
141 unsigned ExitValueNum;
144 char LoopIndexSplit::ID = 0;
145 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
148 LoopPass *llvm::createLoopIndexSplitPass() {
149 return new LoopIndexSplit();
152 // Index split Loop L. Return true if loop is split.
153 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
154 bool Changed = false;
158 // FIXME - Nested loops make dominator info updates tricky.
159 if (!L->getSubLoops().empty())
162 SE = &getAnalysis<ScalarEvolution>();
163 DT = &getAnalysis<DominatorTree>();
164 LI = &getAnalysis<LoopInfo>();
165 DF = &getAnalysis<DominanceFrontier>();
169 findLoopConditionals();
174 findSplitCondition();
176 if (SplitData.empty())
179 // First see if it is possible to eliminate loop itself or not.
180 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
181 E = SplitData.end(); SI != E;) {
183 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
184 Changed = processOneIterationLoop(SD);
187 // If is loop is eliminated then nothing else to do here.
190 SmallVector<SplitInfo, 4>::iterator Delete_SI = SI;
192 SplitData.erase(Delete_SI);
198 unsigned MaxCost = 99;
200 unsigned MostProfitableSDIndex = 0;
201 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
202 E = SplitData.end(); SI != E; ++SI, ++Index) {
205 // ICM_EQs are already handled above.
206 assert (SD.SplitCondition->getPredicate() != ICmpInst::ICMP_EQ &&
207 "Unexpected split condition predicate");
209 unsigned Cost = findSplitCost(L, SD);
211 MostProfitableSDIndex = Index;
214 // Split most profitiable condition.
215 if (!SplitData.empty())
216 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
224 /// Return true if V is a induction variable or induction variable's
225 /// increment for loop L.
226 void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
228 Instruction *I = dyn_cast<Instruction>(V);
232 // Check if I is a phi node from loop header or not.
233 if (PHINode *PN = dyn_cast<PHINode>(V)) {
234 if (PN->getParent() == L->getHeader()) {
240 // Check if I is a add instruction whose one operand is
241 // phi node from loop header and second operand is constant.
242 if (I->getOpcode() != Instruction::Add)
245 Value *Op0 = I->getOperand(0);
246 Value *Op1 = I->getOperand(1);
248 if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
249 if (PN->getParent() == L->getHeader()
250 && isa<ConstantInt>(Op1)) {
257 if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
258 if (PN->getParent() == L->getHeader()
259 && isa<ConstantInt>(Op0)) {
269 // Find loop's exit condition and associated induction variable.
270 void LoopIndexSplit::findLoopConditionals() {
272 BasicBlock *ExitingBlock = NULL;
274 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
277 if (!L->isLoopExit(BB))
287 // If exit block's terminator is conditional branch inst then we have found
289 BranchInst *BR = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
290 if (!BR || BR->isUnconditional())
293 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
299 // Exit condition's one operand is loop invariant exit value and second
300 // operand is SCEVAddRecExpr based on induction variable.
301 Value *V0 = CI->getOperand(0);
302 Value *V1 = CI->getOperand(1);
304 SCEVHandle SH0 = SE->getSCEV(V0);
305 SCEVHandle SH1 = SE->getSCEV(V1);
307 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
311 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
317 ExitCondition = NULL;
319 BasicBlock *Preheader = L->getLoopPreheader();
320 StartValue = IndVar->getIncomingValueForBlock(Preheader);
324 /// Find condition inside a loop that is suitable candidate for index split.
325 void LoopIndexSplit::findSplitCondition() {
328 // Check all basic block's terminators.
330 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
334 // If this basic block does not terminate in a conditional branch
335 // then terminator is not a suitable split condition.
336 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
340 if (BR->isUnconditional())
343 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
344 if (!CI || CI == ExitCondition)
347 // If one operand is loop invariant and second operand is SCEVAddRecExpr
348 // based on induction variable then CI is a candidate split condition.
349 Value *V0 = CI->getOperand(0);
350 Value *V1 = CI->getOperand(1);
352 SCEVHandle SH0 = SE->getSCEV(V0);
353 SCEVHandle SH1 = SE->getSCEV(V1);
355 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
357 SD.SplitCondition = CI;
358 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
360 SplitData.push_back(SD);
362 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
363 if (IndVarIncrement && IndVarIncrement == Insn)
364 SplitData.push_back(SD);
367 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
369 SD.SplitCondition = CI;
370 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
372 SplitData.push_back(SD);
374 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
375 if (IndVarIncrement && IndVarIncrement == Insn)
376 SplitData.push_back(SD);
382 /// processOneIterationLoop - Current loop L contains compare instruction
383 /// that compares induction variable, IndVar, against loop invariant. If
384 /// entire (i.e. meaningful) loop body is dominated by this compare
385 /// instruction then loop body is executed only once. In such case eliminate
386 /// loop structure surrounding this loop body. For example,
387 /// for (int i = start; i < end; ++i) {
388 /// if ( i == somevalue) {
392 /// can be transformed into
393 /// if (somevalue >= start && somevalue < end) {
397 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
399 BasicBlock *Header = L->getHeader();
401 // First of all, check if SplitCondition dominates entire loop body
404 // If SplitCondition is not in loop header then this loop is not suitable
405 // for this transformation.
406 if (SD.SplitCondition->getParent() != Header)
409 // If loop header includes loop variant instruction operands then
410 // this loop may not be eliminated.
411 if (!safeHeader(SD, Header))
414 // If Exiting block includes loop variant instructions then this
415 // loop may not be eliminated.
416 if (!safeExitingBlock(SD, ExitCondition->getParent()))
421 // Replace index variable with split value in loop body. Loop body is executed
422 // only when index variable is equal to split value.
423 IndVar->replaceAllUsesWith(SD.SplitValue);
425 // Remove Latch to Header edge.
426 BasicBlock *Latch = L->getLoopLatch();
427 BasicBlock *LatchSucc = NULL;
428 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
431 Header->removePredecessor(Latch);
432 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
437 BR->setUnconditionalDest(LatchSucc);
439 Instruction *Terminator = Header->getTerminator();
440 Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
442 // Replace split condition in header.
444 // SplitCondition : icmp eq i32 IndVar, SplitValue
446 // c1 = icmp uge i32 SplitValue, StartValue
447 // c2 = icmp ult i32 vSplitValue, ExitValue
449 bool SignedPredicate = ExitCondition->isSignedPredicate();
450 Instruction *C1 = new ICmpInst(SignedPredicate ?
451 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
452 SD.SplitValue, StartValue, "lisplit",
454 Instruction *C2 = new ICmpInst(SignedPredicate ?
455 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
456 SD.SplitValue, ExitValue, "lisplit",
458 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
460 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
461 SD.SplitCondition->eraseFromParent();
463 // Now, clear latch block. Remove instructions that are responsible
464 // to increment induction variable.
465 Instruction *LTerminator = Latch->getTerminator();
466 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
470 if (isa<PHINode>(I) || I == LTerminator)
473 if (I == IndVarIncrement)
474 I->replaceAllUsesWith(ExitValue);
476 I->replaceAllUsesWith(UndefValue::get(I->getType()));
477 I->eraseFromParent();
480 LPM->deleteLoopFromQueue(L);
482 // Update Dominator Info.
483 // Only CFG change done is to remove Latch to Header edge. This
484 // does not change dominator tree because Latch did not dominate
487 DominanceFrontier::iterator HeaderDF = DF->find(Header);
488 if (HeaderDF != DF->end())
489 DF->removeFromFrontier(HeaderDF, Header);
491 DominanceFrontier::iterator LatchDF = DF->find(Latch);
492 if (LatchDF != DF->end())
493 DF->removeFromFrontier(LatchDF, Header);
498 // If loop header includes loop variant instruction operands then
499 // this loop can not be eliminated. This is used by processOneIterationLoop().
500 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
502 Instruction *Terminator = Header->getTerminator();
503 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
511 // SplitCondition itself is OK.
512 if (I == SD.SplitCondition)
515 // Induction variable is OK.
519 // Induction variable increment is OK.
520 if (I == IndVarIncrement)
523 // Terminator is also harmless.
527 // Otherwise we have a instruction that may not be safe.
534 // If Exiting block includes loop variant instructions then this
535 // loop may not be eliminated. This is used by processOneIterationLoop().
536 bool LoopIndexSplit::safeExitingBlock(SplitInfo &SD,
537 BasicBlock *ExitingBlock) {
539 for (BasicBlock::iterator BI = ExitingBlock->begin(),
540 BE = ExitingBlock->end(); BI != BE; ++BI) {
547 // Induction variable increment is OK.
548 if (IndVarIncrement && IndVarIncrement == I)
551 // Check if I is induction variable increment instruction.
552 if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
554 Value *Op0 = I->getOperand(0);
555 Value *Op1 = I->getOperand(1);
557 ConstantInt *CI = NULL;
559 if ((PN = dyn_cast<PHINode>(Op0))) {
560 if ((CI = dyn_cast<ConstantInt>(Op1)))
563 if ((PN = dyn_cast<PHINode>(Op1))) {
564 if ((CI = dyn_cast<ConstantInt>(Op0)))
568 if (IndVarIncrement && PN == IndVar && CI->isOne())
572 // I is an Exit condition if next instruction is block terminator.
573 // Exit condition is OK if it compares loop invariant exit value,
574 // which is checked below.
575 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
576 if (EC == ExitCondition)
580 if (I == ExitingBlock->getTerminator())
583 // Otherwise we have instruction that may not be safe.
587 // We could not find any reason to consider ExitingBlock unsafe.
591 /// Find cost of spliting loop L. Cost is measured in terms of size growth.
592 /// Size is growth is calculated based on amount of code duplicated in second
594 unsigned LoopIndexSplit::findSplitCost(Loop *L, SplitInfo &SD) {
597 BasicBlock *SDBlock = SD.SplitCondition->getParent();
598 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
601 // If a block is not dominated by split condition block then
602 // it must be duplicated in both loops.
603 if (!DT->dominates(SDBlock, BB))
610 /// removeBlocks - Remove basic block DeadBB and all blocks dominated by DeadBB.
611 /// This routine is used to remove split condition's dead branch, dominated by
612 /// DeadBB. LiveBB dominates split conidition's other branch.
613 void LoopIndexSplit::removeBlocks(BasicBlock *DeadBB, Loop *LP,
614 BasicBlock *LiveBB) {
616 // First update DeadBB's dominance frontier.
617 SmallVector<BasicBlock *, 8> FrontierBBs;
618 DominanceFrontier::iterator DeadBBDF = DF->find(DeadBB);
619 if (DeadBBDF != DF->end()) {
620 SmallVector<BasicBlock *, 8> PredBlocks;
622 DominanceFrontier::DomSetType DeadBBSet = DeadBBDF->second;
623 for (DominanceFrontier::DomSetType::iterator DeadBBSetI = DeadBBSet.begin(),
624 DeadBBSetE = DeadBBSet.end(); DeadBBSetI != DeadBBSetE; ++DeadBBSetI) {
625 BasicBlock *FrontierBB = *DeadBBSetI;
626 FrontierBBs.push_back(FrontierBB);
628 // Rremove any PHI incoming edge from blocks dominated by DeadBB.
630 for(pred_iterator PI = pred_begin(FrontierBB), PE = pred_end(FrontierBB);
633 if (P == DeadBB || DT->dominates(DeadBB, P))
634 PredBlocks.push_back(P);
637 BasicBlock *NewDominator = NULL;
638 for(BasicBlock::iterator FBI = FrontierBB->begin(), FBE = FrontierBB->end();
640 if (PHINode *PN = dyn_cast<PHINode>(FBI)) {
641 for(SmallVector<BasicBlock *, 8>::iterator PI = PredBlocks.begin(),
642 PE = PredBlocks.end(); PI != PE; ++PI) {
644 PN->removeIncomingValue(P);
646 // If we have not identified new dominator then see if we can identify
647 // one based on remaining incoming PHINode values.
648 if (NewDominator == NULL && PN->getNumIncomingValues() == 1)
649 NewDominator = PN->getIncomingBlock(0);
657 // Now remove DeadBB and all nodes dominated by DeadBB in df order.
658 SmallVector<BasicBlock *, 32> WorkList;
659 DomTreeNode *DN = DT->getNode(DeadBB);
660 for (df_iterator<DomTreeNode*> DI = df_begin(DN),
661 E = df_end(DN); DI != E; ++DI) {
662 BasicBlock *BB = DI->getBlock();
663 WorkList.push_back(BB);
664 BB->replaceAllUsesWith(UndefValue::get(Type::LabelTy));
667 while (!WorkList.empty()) {
668 BasicBlock *BB = WorkList.back(); WorkList.pop_back();
669 for(BasicBlock::iterator BBI = BB->begin(), BBE = BB->end();
671 Instruction *I = BBI;
672 I->replaceAllUsesWith(UndefValue::get(I->getType()));
673 I->eraseFromParent();
675 LPM->deleteSimpleAnalysisValue(BB, LP);
679 BB->eraseFromParent();
682 // Update Frontier BBs' dominator info.
683 while (!FrontierBBs.empty()) {
684 BasicBlock *FBB = FrontierBBs.back(); FrontierBBs.pop_back();
685 BasicBlock *NewDominator = FBB->getSinglePredecessor();
687 pred_iterator PI = pred_begin(FBB), PE = pred_end(FBB);
690 if (NewDominator != LiveBB) {
691 for(; PI != PE; ++PI) {
694 NewDominator = LiveBB;
697 NewDominator = DT->findNearestCommonDominator(NewDominator, P);
701 assert (NewDominator && "Unable to fix dominator info.");
702 DT->changeImmediateDominator(FBB, NewDominator);
703 DF->changeImmediateDominator(FBB, NewDominator, DT);
708 /// splitLoop - Split current loop L in two loops using split information
709 /// SD. Update dominator information. Maintain LCSSA form.
710 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
712 // True loop is original loop. False loop is cloned loop.
714 BasicBlock *TL_Preheader = L->getLoopPreheader();
715 BasicBlock *TL_SplitCondBlock = SD.SplitCondition->getParent();
716 BasicBlock *TL_Latch = L->getLoopLatch();
717 BasicBlock *TL_Header = L->getHeader();
718 BranchInst *TL_SplitTerminator =
719 cast<BranchInst>(TL_SplitCondBlock->getTerminator());
721 // FIXME - Unable to handle triange loops at the moment.
722 // In triangle loop, split condition is in header and one of the
723 // the split destination is loop latch. If split condition is EQ
724 // then such loops are already handle in processOneIterationLoop().
725 BasicBlock *Succ0 = TL_SplitTerminator->getSuccessor(0);
726 BasicBlock *Succ1 = TL_SplitTerminator->getSuccessor(1);
727 if (TL_Header == TL_SplitCondBlock
728 && (TL_Latch == Succ0 || TL_Latch == Succ1))
731 // If one of the split condition branch is post dominating other then loop
732 // index split is not appropriate.
733 if (DT->dominates(Succ0, TL_Latch) || DT->dominates(Succ1, TL_Latch))
736 // If one of the split condition branch is a predecessor of the other
737 // split condition branch head then do not split loop on this condition.
738 for(pred_iterator PI = pred_begin(Succ0), PE = pred_end(Succ0);
742 for(pred_iterator PI = pred_begin(Succ1), PE = pred_end(Succ1);
747 bool SignedPredicate = ExitCondition->isSignedPredicate();
748 //[*] Calculate True loop's new Exit Value in loop preheader.
749 // TL_ExitValue = min(SplitValue, ExitValue)
750 //[*] Calculate False loop's new Start Value in loop preheader.
751 // FL_StartValue = max(SplitValue, TrueLoop.StartValue)
752 Value *TL_ExitValue = NULL;
753 Value *FL_StartValue = NULL;
754 if (isa<ConstantInt>(SD.SplitValue)) {
755 TL_ExitValue = SD.SplitValue;
756 FL_StartValue = SD.SplitValue;
759 Instruction *TL_PHTerminator = TL_Preheader->getTerminator();
760 Value *C1 = new ICmpInst(SignedPredicate ?
761 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
763 ExitCondition->getOperand(ExitValueNum),
764 "lsplit.ev", TL_PHTerminator);
765 TL_ExitValue = new SelectInst(C1, SD.SplitValue,
766 ExitCondition->getOperand(ExitValueNum),
767 "lsplit.ev", TL_PHTerminator);
769 Value *C2 = new ICmpInst(SignedPredicate ?
770 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
771 SD.SplitValue, StartValue, "lsplit.sv",
773 FL_StartValue = new SelectInst(C2, StartValue, SD.SplitValue,
774 "lsplit.sv", TL_PHTerminator);
777 //[*] Clone loop. Avoid true destination of split condition and
778 // the blocks dominated by true destination.
779 DenseMap<const Value *, Value *> ValueMap;
780 Loop *FalseLoop = CloneLoop(L, LPM, LI, ValueMap, this);
781 BasicBlock *FL_Header = FalseLoop->getHeader();
783 //[*] True loop's exit edge enters False loop.
784 PHINode *FL_IndVar = cast<PHINode>(ValueMap[IndVar]);
785 BasicBlock *TL_ExitingBlock = ExitCondition->getParent();
786 BranchInst *TL_ExitInsn =
787 dyn_cast<BranchInst>(TL_ExitingBlock->getTerminator());
788 assert (TL_ExitInsn && "Unable to find suitable loop exit branch");
789 BasicBlock *TL_ExitDest = TL_ExitInsn->getSuccessor(1);
791 if (L->contains(TL_ExitDest)) {
792 TL_ExitDest = TL_ExitInsn->getSuccessor(0);
793 TL_ExitInsn->setSuccessor(0, FL_Header);
795 TL_ExitInsn->setSuccessor(1, FL_Header);
797 // Collect inverse map of Header PHINodes.
798 DenseMap<Value *, Value *> InverseMap;
799 for (BasicBlock::iterator BI = L->getHeader()->begin(),
800 BE = L->getHeader()->end(); BI != BE; ++BI) {
801 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
802 PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
803 InverseMap[PNClone] = PN;
808 // Update False loop's header
809 for (BasicBlock::iterator BI = FL_Header->begin(), BE = FL_Header->end();
811 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
812 PN->removeIncomingValue(TL_Preheader);
814 PN->addIncoming(FL_StartValue, TL_ExitingBlock);
816 PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
817 Value *V2 = OrigPN->getIncomingValueForBlock(TL_ExitingBlock);
818 PN->addIncoming(V2, TL_ExitingBlock);
824 // Update TL_ExitDest. Now it's predecessor is False loop's exit block.
825 BasicBlock *FL_ExitingBlock = cast<BasicBlock>(ValueMap[TL_ExitingBlock]);
826 for (BasicBlock::iterator BI = TL_ExitDest->begin(), BE = TL_ExitDest->end();
828 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
829 PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(TL_ExitingBlock)],
831 PN->removeIncomingValue(TL_ExitingBlock);
837 DT->changeImmediateDominator(FL_Header, TL_ExitingBlock);
838 DT->changeImmediateDominator(TL_ExitDest,
839 cast<BasicBlock>(ValueMap[TL_ExitingBlock]));
842 assert (!L->contains(TL_ExitDest) && " Unable to find exit edge destination");
844 //[*] Split Exit Edge.
845 BasicBlock *TL_ExitBlock = SplitEdge(TL_ExitingBlock, FL_Header, this);
847 //[*] Eliminate split condition's false branch from True loop.
848 BranchInst *TL_BR = cast<BranchInst>(TL_SplitCondBlock->getTerminator());
849 BasicBlock *TL_FalseBlock = TL_BR->getSuccessor(1);
850 TL_BR->setUnconditionalDest(TL_BR->getSuccessor(0));
851 removeBlocks(TL_FalseBlock, L, TL_BR->getSuccessor(0));
853 //[*] Update True loop's exit value using new exit value.
854 ExitCondition->setOperand(ExitValueNum, TL_ExitValue);
856 //[*] Eliminate split condition's true branch in False loop CFG.
857 BasicBlock *FL_SplitCondBlock = cast<BasicBlock>(ValueMap[TL_SplitCondBlock]);
858 BranchInst *FL_BR = cast<BranchInst>(FL_SplitCondBlock->getTerminator());
859 BasicBlock *FL_TrueBlock = FL_BR->getSuccessor(0);
860 FL_BR->setUnconditionalDest(FL_BR->getSuccessor(1));
861 removeBlocks(FL_TrueBlock, FalseLoop,
862 cast<BasicBlock>(FL_BR->getSuccessor(0)));
865 for(BasicBlock::iterator BI = FL_Header->begin(), BE = FL_Header->end();
867 if (PHINode *PN = dyn_cast<PHINode>(BI)) {
868 Value *V1 = PN->getIncomingValueForBlock(TL_ExitBlock);
869 PHINode *newPHI = new PHINode(PN->getType(), PN->getName());
870 newPHI->addIncoming(V1, TL_ExitingBlock);
871 TL_ExitBlock->getInstList().push_front(newPHI);
872 PN->removeIncomingValue(TL_ExitBlock);
873 PN->addIncoming(newPHI, TL_ExitBlock);