+
+/// calculateLoopBounds - ALoop exit value and BLoop start values are calculated
+/// based on split value.
+void LoopIndexSplit::calculateLoopBounds(SplitInfo &SD) {
+
+ ICmpInst *SC = cast<ICmpInst>(SD.SplitCondition);
+ ICmpInst::Predicate SP = SC->getPredicate();
+ const Type *Ty = SD.SplitValue->getType();
+ bool Sign = ExitCondition->isSignedPredicate();
+ BasicBlock *Preheader = L->getLoopPreheader();
+ Instruction *PHTerminator = Preheader->getTerminator();
+
+ // Initially use split value as upper loop bound for first loop and lower loop
+ // bound for second loop.
+ Value *AEV = SD.SplitValue;
+ Value *BSV = SD.SplitValue;
+
+ if (ExitCondition->getPredicate() == ICmpInst::ICMP_SGT
+ || ExitCondition->getPredicate() == ICmpInst::ICMP_UGT
+ || ExitCondition->getPredicate() == ICmpInst::ICMP_SGE
+ || ExitCondition->getPredicate() == ICmpInst::ICMP_UGE) {
+ ExitCondition->swapOperands();
+ if (ExitValueNum)
+ ExitValueNum = 0;
+ else
+ ExitValueNum = 1;
+ }
+
+ switch (ExitCondition->getPredicate()) {
+ case ICmpInst::ICMP_SGT:
+ case ICmpInst::ICMP_UGT:
+ case ICmpInst::ICMP_SGE:
+ case ICmpInst::ICMP_UGE:
+ default:
+ assert (0 && "Unexpected exit condition predicate");
+
+ case ICmpInst::ICMP_SLT:
+ case ICmpInst::ICMP_ULT:
+ {
+ switch (SP) {
+ case ICmpInst::ICMP_SLT:
+ case ICmpInst::ICMP_ULT:
+ //
+ // for (i = LB; i < UB; ++i) { if (i < SV) A; else B; }
+ //
+ // is transformed into
+ // AEV = BSV = SV
+ // for (i = LB; i < min(UB, AEV); ++i)
+ // A;
+ // for (i = max(LB, BSV); i < UB; ++i);
+ // B;
+ break;
+ case ICmpInst::ICMP_SLE:
+ case ICmpInst::ICMP_ULE:
+ {
+ //
+ // for (i = LB; i < UB; ++i) { if (i <= SV) A; else B; }
+ //
+ // is transformed into
+ //
+ // AEV = SV + 1
+ // BSV = SV + 1
+ // for (i = LB; i < min(UB, AEV); ++i)
+ // A;
+ // for (i = max(LB, BSV); i < UB; ++i)
+ // B;
+ BSV = BinaryOperator::CreateAdd(SD.SplitValue,
+ ConstantInt::get(Ty, 1, Sign),
+ "lsplit.add", PHTerminator);
+ AEV = BSV;
+ }
+ break;
+ case ICmpInst::ICMP_SGE:
+ case ICmpInst::ICMP_UGE:
+ //
+ // for (i = LB; i < UB; ++i) { if (i >= SV) A; else B; }
+ //
+ // is transformed into
+ // AEV = BSV = SV
+ // for (i = LB; i < min(UB, AEV); ++i)
+ // B;
+ // for (i = max(BSV, LB); i < UB; ++i)
+ // A;
+ break;
+ case ICmpInst::ICMP_SGT:
+ case ICmpInst::ICMP_UGT:
+ {
+ //
+ // for (i = LB; i < UB; ++i) { if (i > SV) A; else B; }
+ //
+ // is transformed into
+ //
+ // BSV = AEV = SV + 1
+ // for (i = LB; i < min(UB, AEV); ++i)
+ // B;
+ // for (i = max(LB, BSV); i < UB; ++i)
+ // A;
+ BSV = BinaryOperator::CreateAdd(SD.SplitValue,
+ ConstantInt::get(Ty, 1, Sign),
+ "lsplit.add", PHTerminator);
+ AEV = BSV;
+ }
+ break;
+ default:
+ assert (0 && "Unexpected split condition predicate");
+ break;
+ } // end switch (SP)
+ }
+ break;
+ case ICmpInst::ICMP_SLE:
+ case ICmpInst::ICMP_ULE:
+ {
+ switch (SP) {
+ case ICmpInst::ICMP_SLT:
+ case ICmpInst::ICMP_ULT:
+ //
+ // for (i = LB; i <= UB; ++i) { if (i < SV) A; else B; }
+ //
+ // is transformed into
+ // AEV = SV - 1;
+ // BSV = SV;
+ // for (i = LB; i <= min(UB, AEV); ++i)
+ // A;
+ // for (i = max(LB, BSV); i <= UB; ++i)
+ // B;
+ AEV = BinaryOperator::CreateSub(SD.SplitValue,
+ ConstantInt::get(Ty, 1, Sign),
+ "lsplit.sub", PHTerminator);
+ break;
+ case ICmpInst::ICMP_SLE:
+ case ICmpInst::ICMP_ULE:
+ //
+ // for (i = LB; i <= UB; ++i) { if (i <= SV) A; else B; }
+ //
+ // is transformed into
+ // AEV = SV;
+ // BSV = SV + 1;
+ // for (i = LB; i <= min(UB, AEV); ++i)
+ // A;
+ // for (i = max(LB, BSV); i <= UB; ++i)
+ // B;
+ BSV = BinaryOperator::CreateAdd(SD.SplitValue,
+ ConstantInt::get(Ty, 1, Sign),
+ "lsplit.add", PHTerminator);
+ break;
+ case ICmpInst::ICMP_SGT:
+ case ICmpInst::ICMP_UGT:
+ //
+ // for (i = LB; i <= UB; ++i) { if (i > SV) A; else B; }
+ //
+ // is transformed into
+ // AEV = SV;
+ // BSV = SV + 1;
+ // for (i = LB; i <= min(AEV, UB); ++i)
+ // B;
+ // for (i = max(LB, BSV); i <= UB; ++i)
+ // A;
+ BSV = BinaryOperator::CreateAdd(SD.SplitValue,
+ ConstantInt::get(Ty, 1, Sign),
+ "lsplit.add", PHTerminator);
+ break;
+ case ICmpInst::ICMP_SGE:
+ case ICmpInst::ICMP_UGE:
+ // ** TODO **
+ //
+ // for (i = LB; i <= UB; ++i) { if (i >= SV) A; else B; }
+ //
+ // is transformed into
+ // AEV = SV - 1;
+ // BSV = SV;
+ // for (i = LB; i <= min(AEV, UB); ++i)
+ // B;
+ // for (i = max(LB, BSV); i <= UB; ++i)
+ // A;
+ AEV = BinaryOperator::CreateSub(SD.SplitValue,
+ ConstantInt::get(Ty, 1, Sign),
+ "lsplit.sub", PHTerminator);
+ break;
+ default:
+ assert (0 && "Unexpected split condition predicate");
+ break;
+ } // end switch (SP)
+ }
+ break;
+ }
+
+ // Calculate ALoop induction variable's new exiting value and
+ // BLoop induction variable's new starting value. Calculuate these
+ // values in original loop's preheader.
+ // A_ExitValue = min(SplitValue, OrignalLoopExitValue)
+ // B_StartValue = max(SplitValue, OriginalLoopStartValue)
+ Instruction *InsertPt = L->getHeader()->getFirstNonPHI();
+
+ // If ExitValue operand is also defined in Loop header then
+ // insert new ExitValue after this operand definition.
+ if (Instruction *EVN =
+ dyn_cast<Instruction>(ExitCondition->getOperand(ExitValueNum))) {
+ if (!isa<PHINode>(EVN))
+ if (InsertPt->getParent() == EVN->getParent()) {
+ BasicBlock::iterator LHBI = L->getHeader()->begin();
+ BasicBlock::iterator LHBE = L->getHeader()->end();
+ for(;LHBI != LHBE; ++LHBI) {
+ Instruction *I = LHBI;
+ if (I == EVN)
+ break;
+ }
+ InsertPt = ++LHBI;
+ }
+ }
+ Value *C1 = new ICmpInst(Sign ?
+ ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
+ AEV,
+ ExitCondition->getOperand(ExitValueNum),
+ "lsplit.ev", InsertPt);
+
+ SD.A_ExitValue = SelectInst::Create(C1, AEV,
+ ExitCondition->getOperand(ExitValueNum),
+ "lsplit.ev", InsertPt);
+
+ Value *C2 = new ICmpInst(Sign ?
+ ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
+ BSV, StartValue, "lsplit.sv",
+ PHTerminator);
+ SD.B_StartValue = SelectInst::Create(C2, StartValue, BSV,
+ "lsplit.sv", PHTerminator);
+}
+
+/// splitLoop - Split current loop L in two loops using split information
+/// SD. Update dominator information. Maintain LCSSA form.
+bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
+
+ if (!safeSplitCondition(SD))
+ return false;
+
+ BasicBlock *SplitCondBlock = SD.SplitCondition->getParent();
+
+ // Unable to handle triange loops at the moment.
+ // In triangle loop, split condition is in header and one of the
+ // the split destination is loop latch. If split condition is EQ
+ // then such loops are already handle in processOneIterationLoop().
+ BasicBlock *Latch = L->getLoopLatch();
+ BranchInst *SplitTerminator =
+ cast<BranchInst>(SplitCondBlock->getTerminator());
+ BasicBlock *Succ0 = SplitTerminator->getSuccessor(0);
+ BasicBlock *Succ1 = SplitTerminator->getSuccessor(1);
+ if (L->getHeader() == SplitCondBlock
+ && (Latch == Succ0 || Latch == Succ1))
+ return false;
+
+ // If split condition branches heads do not have single predecessor,
+ // SplitCondBlock, then is not possible to remove inactive branch.
+ if (!Succ0->getSinglePredecessor() || !Succ1->getSinglePredecessor())
+ return false;
+
+ // If Exiting block includes loop variant instructions then this
+ // loop may not be split safely.
+ if (!safeExitingBlock(SD, ExitCondition->getParent()))
+ return false;
+
+ // After loop is cloned there are two loops.
+ //
+ // First loop, referred as ALoop, executes first part of loop's iteration
+ // space split. Second loop, referred as BLoop, executes remaining
+ // part of loop's iteration space.
+ //
+ // ALoop's exit edge enters BLoop's header through a forwarding block which
+ // acts as a BLoop's preheader.
+ BasicBlock *Preheader = L->getLoopPreheader();
+
+ // Calculate ALoop induction variable's new exiting value and
+ // BLoop induction variable's new starting value.
+ calculateLoopBounds(SD);
+
+ //[*] Clone loop.
+ DenseMap<const Value *, Value *> ValueMap;
+ Loop *BLoop = CloneLoop(L, LPM, LI, ValueMap, this);
+ Loop *ALoop = L;
+ BasicBlock *B_Header = BLoop->getHeader();
+
+ //[*] ALoop's exiting edge BLoop's header.
+ // ALoop's original exit block becomes BLoop's exit block.
+ PHINode *B_IndVar = cast<PHINode>(ValueMap[IndVar]);
+ BasicBlock *A_ExitingBlock = ExitCondition->getParent();
+ BranchInst *A_ExitInsn =
+ dyn_cast<BranchInst>(A_ExitingBlock->getTerminator());
+ assert (A_ExitInsn && "Unable to find suitable loop exit branch");
+ BasicBlock *B_ExitBlock = A_ExitInsn->getSuccessor(1);
+ if (L->contains(B_ExitBlock)) {
+ B_ExitBlock = A_ExitInsn->getSuccessor(0);
+ A_ExitInsn->setSuccessor(0, B_Header);
+ } else
+ A_ExitInsn->setSuccessor(1, B_Header);
+
+ //[*] Update ALoop's exit value using new exit value.
+ ExitCondition->setOperand(ExitValueNum, SD.A_ExitValue);
+
+ // [*] Update BLoop's header phi nodes. Remove incoming PHINode's from
+ // original loop's preheader. Add incoming PHINode values from
+ // ALoop's exiting block. Update BLoop header's domiantor info.
+
+ // Collect inverse map of Header PHINodes.
+ DenseMap<Value *, Value *> InverseMap;
+ for (BasicBlock::iterator BI = L->getHeader()->begin(),
+ BE = L->getHeader()->end(); BI != BE; ++BI) {
+ if (PHINode *PN = dyn_cast<PHINode>(BI)) {
+ PHINode *PNClone = cast<PHINode>(ValueMap[PN]);
+ InverseMap[PNClone] = PN;
+ } else
+ break;
+ }
+
+ for (BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
+ BI != BE; ++BI) {
+ if (PHINode *PN = dyn_cast<PHINode>(BI)) {
+ // Remove incoming value from original preheader.
+ PN->removeIncomingValue(Preheader);
+
+ // Add incoming value from A_ExitingBlock.
+ if (PN == B_IndVar)
+ PN->addIncoming(SD.B_StartValue, A_ExitingBlock);
+ else {
+ PHINode *OrigPN = cast<PHINode>(InverseMap[PN]);
+ Value *V2 = NULL;
+ // If loop header is also loop exiting block then
+ // OrigPN is incoming value for B loop header.
+ if (A_ExitingBlock == L->getHeader())
+ V2 = OrigPN;
+ else
+ V2 = OrigPN->getIncomingValueForBlock(A_ExitingBlock);
+ PN->addIncoming(V2, A_ExitingBlock);
+ }
+ } else
+ break;
+ }
+ DT->changeImmediateDominator(B_Header, A_ExitingBlock);
+ DF->changeImmediateDominator(B_Header, A_ExitingBlock, DT);
+
+ // [*] Update BLoop's exit block. Its new predecessor is BLoop's exit
+ // block. Remove incoming PHINode values from ALoop's exiting block.
+ // Add new incoming values from BLoop's incoming exiting value.
+ // Update BLoop exit block's dominator info..
+ BasicBlock *B_ExitingBlock = cast<BasicBlock>(ValueMap[A_ExitingBlock]);
+ for (BasicBlock::iterator BI = B_ExitBlock->begin(), BE = B_ExitBlock->end();
+ BI != BE; ++BI) {
+ if (PHINode *PN = dyn_cast<PHINode>(BI)) {
+ PN->addIncoming(ValueMap[PN->getIncomingValueForBlock(A_ExitingBlock)],
+ B_ExitingBlock);
+ PN->removeIncomingValue(A_ExitingBlock);
+ } else
+ break;
+ }
+
+ DT->changeImmediateDominator(B_ExitBlock, B_ExitingBlock);
+ DF->changeImmediateDominator(B_ExitBlock, B_ExitingBlock, DT);
+
+ //[*] Split ALoop's exit edge. This creates a new block which
+ // serves two purposes. First one is to hold PHINode defnitions
+ // to ensure that ALoop's LCSSA form. Second use it to act
+ // as a preheader for BLoop.
+ BasicBlock *A_ExitBlock = SplitEdge(A_ExitingBlock, B_Header, this);
+
+ //[*] Preserve ALoop's LCSSA form. Create new forwarding PHINodes
+ // in A_ExitBlock to redefine outgoing PHI definitions from ALoop.
+ for(BasicBlock::iterator BI = B_Header->begin(), BE = B_Header->end();
+ BI != BE; ++BI) {
+ if (PHINode *PN = dyn_cast<PHINode>(BI)) {
+ Value *V1 = PN->getIncomingValueForBlock(A_ExitBlock);
+ PHINode *newPHI = PHINode::Create(PN->getType(), PN->getName());
+ newPHI->addIncoming(V1, A_ExitingBlock);
+ A_ExitBlock->getInstList().push_front(newPHI);
+ PN->removeIncomingValue(A_ExitBlock);
+ PN->addIncoming(newPHI, A_ExitBlock);
+ } else
+ break;
+ }
+
+ //[*] Eliminate split condition's inactive branch from ALoop.
+ BasicBlock *A_SplitCondBlock = SD.SplitCondition->getParent();
+ BranchInst *A_BR = cast<BranchInst>(A_SplitCondBlock->getTerminator());
+ BasicBlock *A_InactiveBranch = NULL;
+ BasicBlock *A_ActiveBranch = NULL;
+ if (SD.UseTrueBranchFirst) {
+ A_ActiveBranch = A_BR->getSuccessor(0);
+ A_InactiveBranch = A_BR->getSuccessor(1);
+ } else {
+ A_ActiveBranch = A_BR->getSuccessor(1);
+ A_InactiveBranch = A_BR->getSuccessor(0);
+ }
+ A_BR->setUnconditionalDest(A_ActiveBranch);
+ removeBlocks(A_InactiveBranch, L, A_ActiveBranch);
+
+ //[*] Eliminate split condition's inactive branch in from BLoop.
+ BasicBlock *B_SplitCondBlock = cast<BasicBlock>(ValueMap[A_SplitCondBlock]);
+ BranchInst *B_BR = cast<BranchInst>(B_SplitCondBlock->getTerminator());
+ BasicBlock *B_InactiveBranch = NULL;
+ BasicBlock *B_ActiveBranch = NULL;
+ if (SD.UseTrueBranchFirst) {
+ B_ActiveBranch = B_BR->getSuccessor(1);
+ B_InactiveBranch = B_BR->getSuccessor(0);
+ } else {
+ B_ActiveBranch = B_BR->getSuccessor(0);
+ B_InactiveBranch = B_BR->getSuccessor(1);
+ }
+ B_BR->setUnconditionalDest(B_ActiveBranch);
+ removeBlocks(B_InactiveBranch, BLoop, B_ActiveBranch);
+
+ BasicBlock *A_Header = L->getHeader();
+ if (A_ExitingBlock == A_Header)
+ return true;
+
+ //[*] Move exit condition into split condition block to avoid
+ // executing dead loop iteration.
+ ICmpInst *B_ExitCondition = cast<ICmpInst>(ValueMap[ExitCondition]);
+ Instruction *B_IndVarIncrement = cast<Instruction>(ValueMap[IndVarIncrement]);
+ ICmpInst *B_SplitCondition = cast<ICmpInst>(ValueMap[SD.SplitCondition]);
+
+ moveExitCondition(A_SplitCondBlock, A_ActiveBranch, A_ExitBlock, ExitCondition,
+ cast<ICmpInst>(SD.SplitCondition), IndVar, IndVarIncrement,
+ ALoop);
+
+ moveExitCondition(B_SplitCondBlock, B_ActiveBranch, B_ExitBlock, B_ExitCondition,
+ B_SplitCondition, B_IndVar, B_IndVarIncrement, BLoop);
+
+ return true;
+}
+
+// moveExitCondition - Move exit condition EC into split condition block CondBB.
+void LoopIndexSplit::moveExitCondition(BasicBlock *CondBB, BasicBlock *ActiveBB,
+ BasicBlock *ExitBB, ICmpInst *EC, ICmpInst *SC,
+ PHINode *IV, Instruction *IVAdd, Loop *LP) {
+
+ BasicBlock *ExitingBB = EC->getParent();
+ Instruction *CurrentBR = CondBB->getTerminator();
+
+ // Move exit condition into split condition block.
+ EC->moveBefore(CurrentBR);
+ EC->setOperand(ExitValueNum == 0 ? 1 : 0, IV);
+
+ // Move exiting block's branch into split condition block. Update its branch
+ // destination.
+ BranchInst *ExitingBR = cast<BranchInst>(ExitingBB->getTerminator());
+ ExitingBR->moveBefore(CurrentBR);
+ BasicBlock *OrigDestBB = NULL;
+ if (ExitingBR->getSuccessor(0) == ExitBB) {
+ OrigDestBB = ExitingBR->getSuccessor(1);
+ ExitingBR->setSuccessor(1, ActiveBB);
+ }
+ else {
+ OrigDestBB = ExitingBR->getSuccessor(0);
+ ExitingBR->setSuccessor(0, ActiveBB);
+ }
+
+ // Remove split condition and current split condition branch.
+ SC->eraseFromParent();
+ CurrentBR->eraseFromParent();
+
+ // Connect exiting block to original destination.
+ BranchInst::Create(OrigDestBB, ExitingBB);
+
+ // Update PHINodes
+ updatePHINodes(ExitBB, ExitingBB, CondBB, IV, IVAdd, LP);
+
+ // Fix dominator info.
+ // ExitBB is now dominated by CondBB
+ DT->changeImmediateDominator(ExitBB, CondBB);
+ DF->changeImmediateDominator(ExitBB, CondBB, DT);
+
+ // Basicblocks dominated by ActiveBB may have ExitingBB or
+ // a basic block outside the loop in their DF list. If so,
+ // replace it with CondBB.
+ DomTreeNode *Node = DT->getNode(ActiveBB);
+ for (df_iterator<DomTreeNode *> DI = df_begin(Node), DE = df_end(Node);
+ DI != DE; ++DI) {
+ BasicBlock *BB = DI->getBlock();
+ DominanceFrontier::iterator BBDF = DF->find(BB);
+ DominanceFrontier::DomSetType::iterator DomSetI = BBDF->second.begin();
+ DominanceFrontier::DomSetType::iterator DomSetE = BBDF->second.end();
+ while (DomSetI != DomSetE) {
+ DominanceFrontier::DomSetType::iterator CurrentItr = DomSetI;
+ ++DomSetI;
+ BasicBlock *DFBB = *CurrentItr;
+ if (DFBB == ExitingBB || !L->contains(DFBB)) {
+ BBDF->second.erase(DFBB);
+ BBDF->second.insert(CondBB);
+ }
+ }
+ }
+}
+
+/// updatePHINodes - CFG has been changed.
+/// Before
+/// - ExitBB's single predecessor was Latch
+/// - Latch's second successor was Header
+/// Now
+/// - ExitBB's single predecessor is Header
+/// - Latch's one and only successor is Header
+///
+/// Update ExitBB PHINodes' to reflect this change.
+void LoopIndexSplit::updatePHINodes(BasicBlock *ExitBB, BasicBlock *Latch,
+ BasicBlock *Header,
+ PHINode *IV, Instruction *IVIncrement,
+ Loop *LP) {
+
+ for (BasicBlock::iterator BI = ExitBB->begin(), BE = ExitBB->end();
+ BI != BE; ) {
+ PHINode *PN = dyn_cast<PHINode>(BI);
+ ++BI;
+ if (!PN)
+ break;
+
+ Value *V = PN->getIncomingValueForBlock(Latch);
+ if (PHINode *PHV = dyn_cast<PHINode>(V)) {
+ // PHV is in Latch. PHV has one use is in ExitBB PHINode. And one use
+ // in Header which is new incoming value for PN.
+ Value *NewV = NULL;
+ for (Value::use_iterator UI = PHV->use_begin(), E = PHV->use_end();
+ UI != E; ++UI)
+ if (PHINode *U = dyn_cast<PHINode>(*UI))
+ if (LP->contains(U->getParent())) {
+ NewV = U;
+ break;
+ }
+
+ // Add incoming value from header only if PN has any use inside the loop.
+ if (NewV)
+ PN->addIncoming(NewV, Header);
+
+ } else if (Instruction *PHI = dyn_cast<Instruction>(V)) {
+ // If this instruction is IVIncrement then IV is new incoming value
+ // from header otherwise this instruction must be incoming value from
+ // header because loop is in LCSSA form.
+ if (PHI == IVIncrement)
+ PN->addIncoming(IV, Header);
+ else
+ PN->addIncoming(V, Header);
+ } else
+ // Otherwise this is an incoming value from header because loop is in
+ // LCSSA form.
+ PN->addIncoming(V, Header);
+
+ // Remove incoming value from Latch.
+ PN->removeIncomingValue(Latch);
+ }
+}