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/Function.h"
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/Analysis/LoopPass.h"
19 #include "llvm/Analysis/ScalarEvolutionExpander.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/ADT/Statistic.h"
25 STATISTIC(NumIndexSplit, "Number of loops index split");
29 class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
32 static char ID; // Pass ID, replacement for typeid
33 LoopIndexSplit() : LoopPass((intptr_t)&ID) {}
35 // Index split Loop L. Return true if loop is split.
36 bool runOnLoop(Loop *L, LPPassManager &LPM);
38 void getAnalysisUsage(AnalysisUsage &AU) const {
39 AU.addRequired<ScalarEvolution>();
40 AU.addPreserved<ScalarEvolution>();
41 AU.addRequiredID(LCSSAID);
42 AU.addPreservedID(LCSSAID);
43 AU.addPreserved<LoopInfo>();
44 AU.addRequiredID(LoopSimplifyID);
45 AU.addPreservedID(LoopSimplifyID);
49 /// Find condition inside a loop that is suitable candidate for index split.
50 void findSplitCondition();
52 /// processOneIterationLoop - Current loop L contains compare instruction
53 /// that compares induction variable, IndVar, agains loop invariant. If
54 /// entire (i.e. meaningful) loop body is dominated by this compare
55 /// instruction then loop body is executed only for one iteration. In
56 /// such case eliminate loop structure surrounding this loop body. For
57 bool processOneIterationLoop(LPPassManager &LPM);
59 // If loop header includes loop variant instruction operands then
60 // this loop may not be eliminated.
61 bool safeHeader(BasicBlock *BB);
63 // If Exit block includes loop variant instructions then this
64 // loop may not be eliminated.
65 bool safeExitBlock(BasicBlock *BB);
75 // Induction variable whose range is being split by this transformation.
78 // Induction variable's range is split at this value.
81 // Induction variable's final loop exit value.
84 // This compare instruction compares IndVar against SplitValue.
85 ICmpInst *SplitCondition;
88 char LoopIndexSplit::ID = 0;
89 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
92 LoopPass *llvm::createLoopIndexSplitPass() {
93 return new LoopIndexSplit();
96 // Index split Loop L. Return true if loop is split.
97 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM) {
100 SplitCondition = NULL;
101 SE = &getAnalysis<ScalarEvolution>();
103 findSplitCondition();
108 if (SplitCondition->getPredicate() == ICmpInst::ICMP_EQ)
109 // If it is possible to eliminate loop then do so.
110 Changed = processOneIterationLoop(LPM);
112 Changed = splitLoop();
120 /// Find condition inside a loop that is suitable candidate for index split.
121 void LoopIndexSplit::findSplitCondition() {
123 BasicBlock *Header = L->getHeader();
125 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
126 PHINode *PN = cast<PHINode>(I);
128 if (!PN->getType()->isInteger())
131 SCEVHandle SCEV = SE->getSCEV(PN);
132 if (!isa<SCEVAddRecExpr>(SCEV))
135 // If this phi node is used in a compare instruction then it is a
136 // split condition candidate.
137 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
139 if (ICmpInst *CI = dyn_cast<ICmpInst>(*UI)) {
145 // Valid SplitCondition's one operand is phi node and the other operand
146 // is loop invariant.
147 if (SplitCondition) {
148 if (SplitCondition->getOperand(0) != PN)
149 SplitValue = SplitCondition->getOperand(0);
151 SplitValue = SplitCondition->getOperand(1);
152 SCEVHandle ValueSCEV = SE->getSCEV(SplitValue);
154 // If SplitValue is not invariant then SplitCondition is not appropriate.
155 if (!ValueSCEV->isLoopInvariant(L))
156 SplitCondition = NULL;
159 // We are looking for only one split condition.
160 if (SplitCondition) {
167 /// processOneIterationLoop - Current loop L contains compare instruction
168 /// that compares induction variable, IndVar, against loop invariant. If
169 /// entire (i.e. meaningful) loop body is dominated by this compare
170 /// instruction then loop body is executed only once. In such case eliminate
171 /// loop structure surrounding this loop body. For example,
172 /// for (int i = start; i < end; ++i) {
173 /// if ( i == somevalue) {
177 /// can be transformed into
178 /// if (somevalue >= start && somevalue < end) {
182 bool LoopIndexSplit::processOneIterationLoop(LPPassManager &LPM) {
184 BasicBlock *Header = L->getHeader();
186 // First of all, check if SplitCondition dominates entire loop body
189 // If SplitCondition is not in loop header then this loop is not suitable
190 // for this transformation.
191 if (SplitCondition->getParent() != Header)
194 // If one of the Header block's successor is not an exit block then this
195 // loop is not a suitable candidate.
196 BasicBlock *ExitBlock = NULL;
197 for (succ_iterator SI = succ_begin(Header), E = succ_end(Header); SI != E; ++SI) {
198 if (L->isLoopExit(*SI)) {
207 // If loop header includes loop variant instruction operands then
208 // this loop may not be eliminated.
209 if (!safeHeader(Header))
212 // If Exit block includes loop variant instructions then this
213 // loop may not be eliminated.
214 if (!safeExitBlock(ExitBlock))
217 BasicBlock *Latch = L->getLoopLatch();
218 BasicBlock *Preheader = L->getLoopPreheader();
219 Instruction *Terminator = Header->getTerminator();
220 Value *StartValue = IndVar->getIncomingValueForBlock(Preheader);
224 // Replace split condition in header.
226 // SplitCondition : icmp eq i32 IndVar, SplitValue
228 // c1 = icmp uge i32 SplitValue, StartValue
229 // c2 = icmp ult i32 vSplitValue, ExitValue
231 bool SignedPredicate = SplitCondition->isSignedPredicate();
232 Instruction *C1 = new ICmpInst(SignedPredicate ?
233 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
234 SplitValue, StartValue, "lisplit", Terminator);
235 Instruction *C2 = new ICmpInst(SignedPredicate ?
236 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
237 SplitValue, ExitValue, "lisplit", Terminator);
238 Instruction *NSplitCond = BinaryOperator::create(Instruction::And,
239 C1, C2, "lisplit", Terminator);
240 SplitCondition->replaceAllUsesWith(NSplitCond);
241 SplitCondition->eraseFromParent();
243 // As a first step to break this loop, remove Latch to Header edge.
244 BasicBlock *LatchSucc = NULL;
245 Header->removePredecessor(Latch);
246 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
251 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
252 BR->setUnconditionalDest(LatchSucc);
254 // Now, clear latch block. Remove instructions that are responsible
255 // to increment induction variable.
256 Instruction *LTerminator = Latch->getTerminator();
257 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
261 if (isa<PHINode>(I) || I == LTerminator)
264 I->replaceAllUsesWith(UndefValue::get(I->getType()));
265 I->eraseFromParent();
268 LPM.deleteLoopFromQueue(L);
272 // If loop header includes loop variant instruction operands then
273 // this loop can not be eliminated. This is used by processOneIterationLoop().
274 bool LoopIndexSplit::safeHeader(BasicBlock *Header) {
276 Instruction *Terminator = Header->getTerminator();
277 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
285 // SplitCondition itself is OK.
286 if (ICmpInst *CI = dyn_cast<ICmpInst>(I)) {
287 if (CI == SplitCondition)
291 // Terminator is also harmless.
295 // Otherwise we have a instruction that may not be safe.
302 // If Exit block includes loop variant instructions then this
303 // loop may not be eliminated. This is used by processOneIterationLoop().
304 bool LoopIndexSplit::safeExitBlock(BasicBlock *ExitBlock) {
306 Instruction *ExitCondition = NULL;
307 Instruction *IndVarIncrement = NULL;
309 for (BasicBlock::iterator BI = ExitBlock->begin(), BE = ExitBlock->end();
317 // Check if I is induction variable increment instruction.
318 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(I)) {
319 if (BOp->getOpcode() != Instruction::Add)
322 Value *Op0 = BOp->getOperand(0);
323 Value *Op1 = BOp->getOperand(1);
325 ConstantInt *CI = NULL;
327 if ((PN = dyn_cast<PHINode>(Op0))) {
328 if ((CI = dyn_cast<ConstantInt>(Op1)))
331 if ((PN = dyn_cast<PHINode>(Op1))) {
332 if ((CI = dyn_cast<ConstantInt>(Op0)))
336 if (IndVarIncrement && PN == IndVar && CI->isOne())
339 // I is an Exit condition if next instruction is block terminator.
340 // Exit condition is OK if it compares loop invariant exit value,
341 // which is checked below.
342 else if (isa<ICmpInst>(I)) {
345 if (N == ExitBlock->getTerminator()) {
351 // Otherwise we have instruction that may not be safe.
355 // Check if Exit condition is comparing induction variable against
356 // loop invariant value. If one operand is induction variable and
357 // the other operand is loop invaraint then Exit condition is safe.
359 Value *Op0 = ExitCondition->getOperand(0);
360 Value *Op1 = ExitCondition->getOperand(1);
362 Instruction *Insn0 = dyn_cast<Instruction>(Op0);
363 Instruction *Insn1 = dyn_cast<Instruction>(Op1);
365 if (Insn0 && Insn0 == IndVarIncrement)
367 else if (Insn1 && Insn1 == IndVarIncrement)
370 SCEVHandle ValueSCEV = SE->getSCEV(ExitValue);
371 if (!ValueSCEV->isLoopInvariant(L))
375 // We could not find any reason to consider ExitBlock unsafe.
379 bool LoopIndexSplit::splitLoop() {