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/Support/Compiler.h"
22 #include "llvm/ADT/Statistic.h"
26 STATISTIC(NumIndexSplit, "Number of loops index split");
30 class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
33 static char ID; // Pass ID, replacement for typeid
34 LoopIndexSplit() : LoopPass((intptr_t)&ID) {}
36 // Index split Loop L. Return true if loop is split.
37 bool runOnLoop(Loop *L, LPPassManager &LPM);
39 void getAnalysisUsage(AnalysisUsage &AU) const {
40 AU.addRequired<ScalarEvolution>();
41 AU.addPreserved<ScalarEvolution>();
42 AU.addRequiredID(LCSSAID);
43 AU.addPreservedID(LCSSAID);
44 AU.addPreserved<LoopInfo>();
45 AU.addRequiredID(LoopSimplifyID);
46 AU.addPreservedID(LoopSimplifyID);
47 AU.addRequired<DominatorTree>();
48 AU.addPreserved<DominatorTree>();
49 AU.addPreserved<DominanceFrontier>();
56 SplitInfo() : SplitValue(NULL), SplitCondition(NULL) {}
58 // Induction variable's range is split at this value.
61 // This compare instruction compares IndVar against SplitValue.
62 ICmpInst *SplitCondition;
67 SplitCondition = NULL;
73 /// Find condition inside a loop that is suitable candidate for index split.
74 void findSplitCondition();
76 /// Find loop's exit condition.
77 void findLoopConditionals();
79 /// Return induction variable associated with value V.
80 void findIndVar(Value *V, Loop *L);
82 /// processOneIterationLoop - Current loop L contains compare instruction
83 /// that compares induction variable, IndVar, agains loop invariant. If
84 /// entire (i.e. meaningful) loop body is dominated by this compare
85 /// instruction then loop body is executed only for one iteration. In
86 /// such case eliminate loop structure surrounding this loop body. For
87 bool processOneIterationLoop(SplitInfo &SD, LPPassManager &LPM);
89 /// If loop header includes loop variant instruction operands then
90 /// this loop may not be eliminated.
91 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
93 /// If Exit block includes loop variant instructions then this
94 /// loop may not be eliminated.
95 bool safeExitBlock(SplitInfo &SD, BasicBlock *BB);
97 /// Find cost of spliting loop L.
98 unsigned findSplitCost(Loop *L, SplitInfo &SD);
99 bool splitLoop(SplitInfo &SD);
103 IndVarIncrement = NULL;
104 ExitCondition = NULL;
105 StartValue = ExitValue = NULL;
114 SmallVector<SplitInfo, 4> SplitData;
116 // Induction variable whose range is being split by this transformation.
118 Instruction *IndVarIncrement;
120 // Loop exit condition.
121 ICmpInst *ExitCondition;
123 // Induction variable's initial value.
126 // Induction variable's final loop exit value.
130 char LoopIndexSplit::ID = 0;
131 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
134 LoopPass *llvm::createLoopIndexSplitPass() {
135 return new LoopIndexSplit();
138 // Index split Loop L. Return true if loop is split.
139 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM) {
140 bool Changed = false;
143 SE = &getAnalysis<ScalarEvolution>();
144 DT = &getAnalysis<DominatorTree>();
148 findLoopConditionals();
153 findSplitCondition();
155 if (SplitData.empty())
158 // First see if it is possible to eliminate loop itself or not.
159 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
160 E = SplitData.end(); SI != E; ++SI) {
162 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
163 Changed = processOneIterationLoop(SD,LPM);
166 // If is loop is eliminated then nothing else to do here.
172 unsigned MaxCost = 99;
174 unsigned MostProfitableSDIndex = 0;
175 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
176 E = SplitData.end(); SI != E; ++SI, ++Index) {
179 // ICM_EQs are already handled above.
180 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ)
183 unsigned Cost = findSplitCost(L, SD);
185 MostProfitableSDIndex = Index;
188 // Split most profitiable condition.
189 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
197 /// Return true if V is a induction variable or induction variable's
198 /// increment for loop L.
199 void LoopIndexSplit::findIndVar(Value *V, Loop *L) {
201 Instruction *I = dyn_cast<Instruction>(V);
205 // Check if I is a phi node from loop header or not.
206 if (PHINode *PN = dyn_cast<PHINode>(V)) {
207 if (PN->getParent() == L->getHeader()) {
213 // Check if I is a add instruction whose one operand is
214 // phi node from loop header and second operand is constant.
215 if (I->getOpcode() != Instruction::Add)
218 Value *Op0 = I->getOperand(0);
219 Value *Op1 = I->getOperand(1);
221 if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
222 if (PN->getParent() == L->getHeader()
223 && isa<ConstantInt>(Op1)) {
230 if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
231 if (PN->getParent() == L->getHeader()
232 && isa<ConstantInt>(Op0)) {
242 // Find loop's exit condition and associated induction variable.
243 void LoopIndexSplit::findLoopConditionals() {
245 BasicBlock *ExitBlock = NULL;
247 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
250 if (!L->isLoopExit(BB))
260 // If exit block's terminator is conditional branch inst then we have found
262 BranchInst *BR = dyn_cast<BranchInst>(ExitBlock->getTerminator());
263 if (!BR || BR->isUnconditional())
266 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
272 // Exit condition's one operand is loop invariant exit value and second
273 // operand is SCEVAddRecExpr based on induction variable.
274 Value *V0 = CI->getOperand(0);
275 Value *V1 = CI->getOperand(1);
277 SCEVHandle SH0 = SE->getSCEV(V0);
278 SCEVHandle SH1 = SE->getSCEV(V1);
280 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
284 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
289 if (!ExitValue || !IndVar)
290 ExitCondition = NULL;
292 BasicBlock *Preheader = L->getLoopPreheader();
293 StartValue = IndVar->getIncomingValueForBlock(Preheader);
297 /// Find condition inside a loop that is suitable candidate for index split.
298 void LoopIndexSplit::findSplitCondition() {
301 // Check all basic block's terminators.
303 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
307 // If this basic block does not terminate in a conditional branch
308 // then terminator is not a suitable split condition.
309 BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
313 if (BR->isUnconditional())
316 ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
317 if (!CI || CI == ExitCondition)
320 // If one operand is loop invariant and second operand is SCEVAddRecExpr
321 // based on induction variable then CI is a candidate split condition.
322 Value *V0 = CI->getOperand(0);
323 Value *V1 = CI->getOperand(1);
325 SCEVHandle SH0 = SE->getSCEV(V0);
326 SCEVHandle SH1 = SE->getSCEV(V1);
328 if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
330 SD.SplitCondition = CI;
331 if (PHINode *PN = dyn_cast<PHINode>(V1)) {
333 SplitData.push_back(SD);
335 else if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
336 if (IndVarIncrement && IndVarIncrement == Insn)
337 SplitData.push_back(SD);
340 else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
342 SD.SplitCondition = CI;
343 if (PHINode *PN = dyn_cast<PHINode>(V0)) {
345 SplitData.push_back(SD);
347 else if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
348 if (IndVarIncrement && IndVarIncrement == Insn)
349 SplitData.push_back(SD);
355 /// processOneIterationLoop - Current loop L contains compare instruction
356 /// that compares induction variable, IndVar, against loop invariant. If
357 /// entire (i.e. meaningful) loop body is dominated by this compare
358 /// instruction then loop body is executed only once. In such case eliminate
359 /// loop structure surrounding this loop body. For example,
360 /// for (int i = start; i < end; ++i) {
361 /// if ( i == somevalue) {
365 /// can be transformed into
366 /// if (somevalue >= start && somevalue < end) {
370 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD, LPPassManager &LPM) {
372 BasicBlock *Header = L->getHeader();
374 // First of all, check if SplitCondition dominates entire loop body
377 // If SplitCondition is not in loop header then this loop is not suitable
378 // for this transformation.
379 if (SD.SplitCondition->getParent() != Header)
382 // If loop header includes loop variant instruction operands then
383 // this loop may not be eliminated.
384 if (!safeHeader(SD, Header))
387 // If Exit block includes loop variant instructions then this
388 // loop may not be eliminated.
389 if (!safeExitBlock(SD, ExitCondition->getParent()))
394 // As a first step to break this loop, remove Latch to Header edge.
395 BasicBlock *Latch = L->getLoopLatch();
396 BasicBlock *LatchSucc = NULL;
397 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
400 Header->removePredecessor(Latch);
401 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
406 BR->setUnconditionalDest(LatchSucc);
408 BasicBlock *Preheader = L->getLoopPreheader();
409 Instruction *Terminator = Header->getTerminator();
410 StartValue = IndVar->getIncomingValueForBlock(Preheader);
412 // Replace split condition in header.
414 // SplitCondition : icmp eq i32 IndVar, SplitValue
416 // c1 = icmp uge i32 SplitValue, StartValue
417 // c2 = icmp ult i32 vSplitValue, ExitValue
419 bool SignedPredicate = ExitCondition->isSignedPredicate();
420 Instruction *C1 = new ICmpInst(SignedPredicate ?
421 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
422 SD.SplitValue, StartValue, "lisplit",
424 Instruction *C2 = new ICmpInst(SignedPredicate ?
425 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
426 SD.SplitValue, ExitValue, "lisplit",
428 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
430 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
431 SD.SplitCondition->eraseFromParent();
433 // Now, clear latch block. Remove instructions that are responsible
434 // to increment induction variable.
435 Instruction *LTerminator = Latch->getTerminator();
436 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
440 if (isa<PHINode>(I) || I == LTerminator)
443 I->replaceAllUsesWith(UndefValue::get(I->getType()));
444 I->eraseFromParent();
447 LPM.deleteLoopFromQueue(L);
449 // Update Dominator Info.
450 // Only CFG change done is to remove Latch to Header edge. This
451 // does not change dominator tree because Latch did not dominate
453 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
454 DominanceFrontier::iterator HeaderDF = DF->find(Header);
455 if (HeaderDF != DF->end())
456 DF->removeFromFrontier(HeaderDF, Header);
458 DominanceFrontier::iterator LatchDF = DF->find(Latch);
459 if (LatchDF != DF->end())
460 DF->removeFromFrontier(LatchDF, Header);
465 // If loop header includes loop variant instruction operands then
466 // this loop can not be eliminated. This is used by processOneIterationLoop().
467 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
469 Instruction *Terminator = Header->getTerminator();
470 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
474 // PHI Nodes are OK. FIXME : Handle last value assignments.
478 // SplitCondition itself is OK.
479 if (I == SD.SplitCondition)
482 // Induction variable is OK.
486 // Induction variable increment is OK.
487 if (I == IndVarIncrement)
490 // Terminator is also harmless.
494 // Otherwise we have a instruction that may not be safe.
501 // If Exit block includes loop variant instructions then this
502 // loop may not be eliminated. This is used by processOneIterationLoop().
503 bool LoopIndexSplit::safeExitBlock(SplitInfo &SD, BasicBlock *ExitBlock) {
505 for (BasicBlock::iterator BI = ExitBlock->begin(), BE = ExitBlock->end();
509 // PHI Nodes are OK. FIXME : Handle last value assignments.
513 // Induction variable increment is OK.
514 if (IndVarIncrement && IndVarIncrement == I)
517 // Check if I is induction variable increment instruction.
518 if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
520 Value *Op0 = I->getOperand(0);
521 Value *Op1 = I->getOperand(1);
523 ConstantInt *CI = NULL;
525 if ((PN = dyn_cast<PHINode>(Op0))) {
526 if ((CI = dyn_cast<ConstantInt>(Op1)))
529 if ((PN = dyn_cast<PHINode>(Op1))) {
530 if ((CI = dyn_cast<ConstantInt>(Op0)))
534 if (IndVarIncrement && PN == IndVar && CI->isOne())
538 // I is an Exit condition if next instruction is block terminator.
539 // Exit condition is OK if it compares loop invariant exit value,
540 // which is checked below.
541 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
542 if (EC == ExitCondition)
546 if (I == ExitBlock->getTerminator())
549 // Otherwise we have instruction that may not be safe.
553 // We could not find any reason to consider ExitBlock unsafe.
557 /// Find cost of spliting loop L. Cost is measured in terms of size growth.
558 /// Size is growth is calculated based on amount of code duplicated in second
560 unsigned LoopIndexSplit::findSplitCost(Loop *L, SplitInfo &SD) {
563 BasicBlock *SDBlock = SD.SplitCondition->getParent();
564 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
567 // If a block is not dominated by split condition block then
568 // it must be duplicated in both loops.
569 if (!DT->dominates(SDBlock, BB))
576 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
578 BasicBlock *Preheader = L->getLoopPreheader();
580 // True loop is original loop. False loop is cloned loop.
582 bool SignedPredicate = ExitCondition->isSignedPredicate();
583 //[*] Calculate True loop's new Exit Value in loop preheader.
584 // TLExitValue = min(SplitValue, ExitValue)
585 //[*] Calculate False loop's new Start Value in loop preheader.
586 // FLStartValue = min(SplitValue, TrueLoop.StartValue)
587 Value *TLExitValue = NULL;
588 Value *FLStartValue = NULL;
589 if (isa<ConstantInt>(SD.SplitValue)) {
590 TLExitValue = SD.SplitValue;
591 FLStartValue = SD.SplitValue;
594 Value *C1 = new ICmpInst(SignedPredicate ?
595 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
596 SD.SplitValue, ExitValue, "lsplit.ev",
597 Preheader->getTerminator());
598 TLExitValue = new SelectInst(C1, SD.SplitValue, ExitValue,
599 "lsplit.ev", Preheader->getTerminator());
601 Value *C2 = new ICmpInst(SignedPredicate ?
602 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
603 SD.SplitValue, StartValue, "lsplit.sv",
604 Preheader->getTerminator());
605 FLStartValue = new SelectInst(C2, SD.SplitValue, StartValue,
606 "lsplit.sv", Preheader->getTerminator());
608 //[*] Split Exit Edge.
609 //[*] Clone loop. Avoid true destination of split condition and
610 // the blocks dominated by true destination.
611 //[*] True loops exit edge enters False loop.
612 //[*] Eliminate split condition's false branch from True loop.
613 // Update true loop dom info.
614 //[*] Update True loop's exit value using NewExitValue.
615 //[*] Update False loop's start value using NewStartValue.
616 //[*] Fix lack of true branch in False loop CFG.
617 // Update false loop dom info.
618 //[*] Update dom info in general.