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/Function.h"
18 #include "llvm/Analysis/LoopPass.h"
19 #include "llvm/Analysis/ScalarEvolutionExpander.h"
20 #include "llvm/Analysis/Dominators.h"
21 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
22 #include "llvm/Transforms/Utils/Cloning.h"
23 #include "llvm/Support/Compiler.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.addPreserved<DominatorTree>();
52 AU.addPreserved<DominanceFrontier>();
59 SplitInfo() : SplitValue(NULL), SplitCondition(NULL) {}
61 // Induction variable's range is split at this value.
64 // This compare instruction compares IndVar against SplitValue.
65 ICmpInst *SplitCondition;
70 SplitCondition = NULL;
76 /// Find condition inside a loop that is suitable candidate for index split.
77 void findSplitCondition();
79 /// Find loop's exit condition.
80 void findLoopConditionals();
82 /// Return induction variable associated with value V.
83 void findIndVar(Value *V, Loop *L);
85 /// processOneIterationLoop - Current loop L contains compare instruction
86 /// that compares induction variable, IndVar, agains loop invariant. If
87 /// entire (i.e. meaningful) loop body is dominated by this compare
88 /// instruction then loop body is executed only for one iteration. In
89 /// such case eliminate loop structure surrounding this loop body. For
90 bool processOneIterationLoop(SplitInfo &SD);
92 /// If loop header includes loop variant instruction operands then
93 /// this loop may not be eliminated.
94 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
96 /// If Exit block includes loop variant instructions then this
97 /// loop may not be eliminated.
98 bool safeExitBlock(SplitInfo &SD, BasicBlock *BB);
100 /// Find cost of spliting loop L.
101 unsigned findSplitCost(Loop *L, SplitInfo &SD);
102 bool splitLoop(SplitInfo &SD);
106 IndVarIncrement = NULL;
107 ExitCondition = NULL;
108 StartValue = ExitValue = NULL;
119 SmallVector<SplitInfo, 4> SplitData;
121 // Induction variable whose range is being split by this transformation.
123 Instruction *IndVarIncrement;
125 // Loop exit condition.
126 ICmpInst *ExitCondition;
128 // Induction variable's initial value.
131 // Induction variable's final loop exit value.
135 char LoopIndexSplit::ID = 0;
136 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
139 LoopPass *llvm::createLoopIndexSplitPass() {
140 return new LoopIndexSplit();
143 // Index split Loop L. Return true if loop is split.
144 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
145 bool Changed = false;
149 SE = &getAnalysis<ScalarEvolution>();
150 DT = &getAnalysis<DominatorTree>();
151 LI = &getAnalysis<LoopInfo>();
155 findLoopConditionals();
160 findSplitCondition();
162 if (SplitData.empty())
165 // First see if it is possible to eliminate loop itself or not.
166 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
167 E = SplitData.end(); SI != E; ++SI) {
169 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
170 Changed = processOneIterationLoop(SD);
173 // If is loop is eliminated then nothing else to do here.
179 unsigned MaxCost = 99;
181 unsigned MostProfitableSDIndex = 0;
182 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
183 E = SplitData.end(); SI != E; ++SI, ++Index) {
186 // ICM_EQs are already handled above.
187 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ)
190 unsigned Cost = findSplitCost(L, SD);
192 MostProfitableSDIndex = Index;
195 // Split most profitiable condition.
196 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
204 /// Return true if V is a induction variable or induction variable's
205 /// increment for loop L.
206 void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
208 Instruction *I = dyn_cast<Instruction>(V);
212 // Check if I is a phi node from loop header or not.
213 if (PHINode *PN = dyn_cast<PHINode>(V)) {
214 if (PN->getParent() == L->getHeader()) {
220 // Check if I is a add instruction whose one operand is
221 // phi node from loop header and second operand is constant.
222 if (I->getOpcode() != Instruction::Add)
225 Value *Op0 = I->getOperand(0);
226 Value *Op1 = I->getOperand(1);
228 if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
229 if (PN->getParent() == L->getHeader()
230 && isa<ConstantInt>(Op1)) {
237 if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
238 if (PN->getParent() == L->getHeader()
239 && isa<ConstantInt>(Op0)) {
249 // Find loop's exit condition and associated induction variable.
250 void LoopIndexSplit::findLoopConditionals() {
252 BasicBlock *ExitBlock = NULL;
254 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
257 if (!L->isLoopExit(BB))
267 // If exit block's terminator is conditional branch inst then we have found
269 BranchInst *BR = dyn_cast<BranchInst>(ExitBlock->getTerminator());
270 if (!BR || BR->isUnconditional())
273 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
279 // Exit condition's one operand is loop invariant exit value and second
280 // operand is SCEVAddRecExpr based on induction variable.
281 Value *V0 = CI->getOperand(0);
282 Value *V1 = CI->getOperand(1);
284 SCEVHandle SH0 = SE->getSCEV(V0);
285 SCEVHandle SH1 = SE->getSCEV(V1);
287 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
291 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
296 if (!ExitValue || !IndVar)
297 ExitCondition = NULL;
299 BasicBlock *Preheader = L->getLoopPreheader();
300 StartValue = IndVar->getIncomingValueForBlock(Preheader);
304 /// Find condition inside a loop that is suitable candidate for index split.
305 void LoopIndexSplit::findSplitCondition() {
308 // Check all basic block's terminators.
310 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
314 // If this basic block does not terminate in a conditional branch
315 // then terminator is not a suitable split condition.
316 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
320 if (BR->isUnconditional())
323 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
324 if (!CI || CI == ExitCondition)
327 // If one operand is loop invariant and second operand is SCEVAddRecExpr
328 // based on induction variable then CI is a candidate split condition.
329 Value *V0 = CI->getOperand(0);
330 Value *V1 = CI->getOperand(1);
332 SCEVHandle SH0 = SE->getSCEV(V0);
333 SCEVHandle SH1 = SE->getSCEV(V1);
335 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
337 SD.SplitCondition = CI;
338 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
340 SplitData.push_back(SD);
342 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
343 if (IndVarIncrement && IndVarIncrement == Insn)
344 SplitData.push_back(SD);
347 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
349 SD.SplitCondition = CI;
350 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
352 SplitData.push_back(SD);
354 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
355 if (IndVarIncrement && IndVarIncrement == Insn)
356 SplitData.push_back(SD);
362 /// processOneIterationLoop - Current loop L contains compare instruction
363 /// that compares induction variable, IndVar, against loop invariant. If
364 /// entire (i.e. meaningful) loop body is dominated by this compare
365 /// instruction then loop body is executed only once. In such case eliminate
366 /// loop structure surrounding this loop body. For example,
367 /// for (int i = start; i < end; ++i) {
368 /// if ( i == somevalue) {
372 /// can be transformed into
373 /// if (somevalue >= start && somevalue < end) {
377 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
379 BasicBlock *Header = L->getHeader();
381 // First of all, check if SplitCondition dominates entire loop body
384 // If SplitCondition is not in loop header then this loop is not suitable
385 // for this transformation.
386 if (SD.SplitCondition->getParent() != Header)
389 // If loop header includes loop variant instruction operands then
390 // this loop may not be eliminated.
391 if (!safeHeader(SD, Header))
394 // If Exit block includes loop variant instructions then this
395 // loop may not be eliminated.
396 if (!safeExitBlock(SD, ExitCondition->getParent()))
401 // As a first step to break this loop, remove Latch to Header edge.
402 BasicBlock *Latch = L->getLoopLatch();
403 BasicBlock *LatchSucc = NULL;
404 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
407 Header->removePredecessor(Latch);
408 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
413 BR->setUnconditionalDest(LatchSucc);
415 BasicBlock *Preheader = L->getLoopPreheader();
416 Instruction *Terminator = Header->getTerminator();
417 StartValue = IndVar->getIncomingValueForBlock(Preheader);
419 // Replace split condition in header.
421 // SplitCondition : icmp eq i32 IndVar, SplitValue
423 // c1 = icmp uge i32 SplitValue, StartValue
424 // c2 = icmp ult i32 vSplitValue, ExitValue
426 bool SignedPredicate = ExitCondition->isSignedPredicate();
427 Instruction *C1 = new ICmpInst(SignedPredicate ?
428 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
429 SD.SplitValue, StartValue, "lisplit",
431 Instruction *C2 = new ICmpInst(SignedPredicate ?
432 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
433 SD.SplitValue, ExitValue, "lisplit",
435 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
437 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
438 SD.SplitCondition->eraseFromParent();
440 // Now, clear latch block. Remove instructions that are responsible
441 // to increment induction variable.
442 Instruction *LTerminator = Latch->getTerminator();
443 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
447 if (isa<PHINode>(I) || I == LTerminator)
450 I->replaceAllUsesWith(UndefValue::get(I->getType()));
451 I->eraseFromParent();
454 LPM->deleteLoopFromQueue(L);
456 // Update Dominator Info.
457 // Only CFG change done is to remove Latch to Header edge. This
458 // does not change dominator tree because Latch did not dominate
460 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
461 DominanceFrontier::iterator HeaderDF = DF->find(Header);
462 if (HeaderDF != DF->end())
463 DF->removeFromFrontier(HeaderDF, Header);
465 DominanceFrontier::iterator LatchDF = DF->find(Latch);
466 if (LatchDF != DF->end())
467 DF->removeFromFrontier(LatchDF, Header);
472 // If loop header includes loop variant instruction operands then
473 // this loop can not be eliminated. This is used by processOneIterationLoop().
474 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
476 Instruction *Terminator = Header->getTerminator();
477 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
481 // PHI Nodes are OK. FIXME : Handle last value assignments.
485 // SplitCondition itself is OK.
486 if (I == SD.SplitCondition)
489 // Induction variable is OK.
493 // Induction variable increment is OK.
494 if (I == IndVarIncrement)
497 // Terminator is also harmless.
501 // Otherwise we have a instruction that may not be safe.
508 // If Exit block includes loop variant instructions then this
509 // loop may not be eliminated. This is used by processOneIterationLoop().
510 bool LoopIndexSplit::safeExitBlock(SplitInfo &SD, BasicBlock *ExitBlock) {
512 for (BasicBlock::iterator BI = ExitBlock->begin(), BE = ExitBlock->end();
516 // PHI Nodes are OK. FIXME : Handle last value assignments.
520 // Induction variable increment is OK.
521 if (IndVarIncrement && IndVarIncrement == I)
524 // Check if I is induction variable increment instruction.
525 if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
527 Value *Op0 = I->getOperand(0);
528 Value *Op1 = I->getOperand(1);
530 ConstantInt *CI = NULL;
532 if ((PN = dyn_cast<PHINode>(Op0))) {
533 if ((CI = dyn_cast<ConstantInt>(Op1)))
536 if ((PN = dyn_cast<PHINode>(Op1))) {
537 if ((CI = dyn_cast<ConstantInt>(Op0)))
541 if (IndVarIncrement && PN == IndVar && CI->isOne())
545 // I is an Exit condition if next instruction is block terminator.
546 // Exit condition is OK if it compares loop invariant exit value,
547 // which is checked below.
548 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
549 if (EC == ExitCondition)
553 if (I == ExitBlock->getTerminator())
556 // Otherwise we have instruction that may not be safe.
560 // We could not find any reason to consider ExitBlock unsafe.
564 /// Find cost of spliting loop L. Cost is measured in terms of size growth.
565 /// Size is growth is calculated based on amount of code duplicated in second
567 unsigned LoopIndexSplit::findSplitCost(Loop *L, SplitInfo &SD) {
570 BasicBlock *SDBlock = SD.SplitCondition->getParent();
571 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
574 // If a block is not dominated by split condition block then
575 // it must be duplicated in both loops.
576 if (!DT->dominates(SDBlock, BB))
583 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
585 BasicBlock *Preheader = L->getLoopPreheader();
587 // True loop is original loop. False loop is cloned loop.
589 bool SignedPredicate = ExitCondition->isSignedPredicate();
590 //[*] Calculate True loop's new Exit Value in loop preheader.
591 // TLExitValue = min(SplitValue, ExitValue)
592 //[*] Calculate False loop's new Start Value in loop preheader.
593 // FLStartValue = min(SplitValue, TrueLoop.StartValue)
594 Value *TLExitValue = NULL;
595 Value *FLStartValue = NULL;
596 if (isa<ConstantInt>(SD.SplitValue)) {
597 TLExitValue = SD.SplitValue;
598 FLStartValue = SD.SplitValue;
601 Value *C1 = new ICmpInst(SignedPredicate ?
602 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
603 SD.SplitValue, ExitValue, "lsplit.ev",
604 Preheader->getTerminator());
605 TLExitValue = new SelectInst(C1, SD.SplitValue, ExitValue,
606 "lsplit.ev", Preheader->getTerminator());
608 Value *C2 = new ICmpInst(SignedPredicate ?
609 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
610 SD.SplitValue, StartValue, "lsplit.sv",
611 Preheader->getTerminator());
612 FLStartValue = new SelectInst(C2, SD.SplitValue, StartValue,
613 "lsplit.sv", Preheader->getTerminator());
616 //[*] Split Exit Edge.
617 BasicBlock *ExitBlock = ExitCondition->getParent();
618 BranchInst *ExitInsn = dyn_cast<BranchInst>(ExitBlock->getTerminator());
619 assert (ExitInsn && "Unable to find suitable loop exit branch");
620 BasicBlock *ExitDest = ExitInsn->getSuccessor(1);
621 if (L->contains(ExitDest))
622 ExitDest = ExitInsn->getSuccessor(0);
623 assert (!L->contains(ExitDest) && " Unable to find exit edge destination");
624 SplitEdge(ExitBlock, ExitDest, this);
626 //[*] Clone loop. Avoid true destination of split condition and
627 // the blocks dominated by true destination.
628 DenseMap<const Value *, Value *> ValueMap;
629 CloneLoop(L, LPM, LI, ValueMap, this);
631 //[*] True loops exit edge enters False loop.
632 //[*] Eliminate split condition's false branch from True loop.
633 // Update true loop dom info.
634 //[*] Update True loop's exit value using NewExitValue.
635 //[*] Update False loop's start value using NewStartValue.
636 //[*] Fix lack of true branch in False loop CFG.
637 // Update false loop dom info.
638 //[*] Update dom info in general.