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() : IndVar(NULL), SplitValue(NULL), ExitValue(NULL),
57 SplitCondition(NULL), ExitCondition(NULL) {}
58 // Induction variable whose range is being split by this transformation.
61 // Induction variable's range is split at this value.
64 // Induction variable's final loop exit value.
67 // This compare instruction compares IndVar against SplitValue.
68 ICmpInst *SplitCondition;
70 // Loop exit condition.
71 ICmpInst *ExitCondition;
78 SplitCondition = NULL;
84 /// Find condition inside a loop that is suitable candidate for index split.
85 void findSplitCondition();
87 /// processOneIterationLoop - Current loop L contains compare instruction
88 /// that compares induction variable, IndVar, agains loop invariant. If
89 /// entire (i.e. meaningful) loop body is dominated by this compare
90 /// instruction then loop body is executed only for one iteration. In
91 /// such case eliminate loop structure surrounding this loop body. For
92 bool processOneIterationLoop(SplitInfo &SD, LPPassManager &LPM);
94 /// If loop header includes loop variant instruction operands then
95 /// this loop may not be eliminated.
96 bool safeHeader(SplitInfo &SD, BasicBlock *BB);
98 /// If Exit block includes loop variant instructions then this
99 /// loop may not be eliminated.
100 bool safeExitBlock(SplitInfo &SD, BasicBlock *BB);
102 /// Find cost of spliting loop L.
103 unsigned findSplitCost(Loop *L, SplitInfo &SD);
104 bool splitLoop(SplitInfo &SD);
112 SmallVector<SplitInfo, 4> SplitData;
115 char LoopIndexSplit::ID = 0;
116 RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
119 LoopPass *llvm::createLoopIndexSplitPass() {
120 return new LoopIndexSplit();
123 // Index split Loop L. Return true if loop is split.
124 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM) {
125 bool Changed = false;
128 SE = &getAnalysis<ScalarEvolution>();
129 DT = &getAnalysis<DominatorTree>();
131 findSplitCondition();
133 if (SplitData.empty())
136 // First see if it is possible to eliminate loop itself or not.
137 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
138 E = SplitData.end(); SI != E; ++SI) {
140 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
141 Changed = processOneIterationLoop(SD,LPM);
144 // If is loop is eliminated then nothing else to do here.
150 unsigned MaxCost = 99;
152 unsigned MostProfitableSDIndex = 0;
153 for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
154 E = SplitData.end(); SI != E; ++SI, ++Index) {
157 // ICM_EQs are already handled above.
158 if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ)
161 unsigned Cost = findSplitCost(L, SD);
163 MostProfitableSDIndex = Index;
166 // Split most profitiable condition.
167 Changed = splitLoop(SplitData[MostProfitableSDIndex]);
175 /// Find condition inside a loop that is suitable candidate for index split.
176 void LoopIndexSplit::findSplitCondition() {
179 BasicBlock *Header = L->getHeader();
181 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
182 PHINode *PN = cast<PHINode>(I);
184 if (!PN->getType()->isInteger())
187 SCEVHandle SCEV = SE->getSCEV(PN);
188 if (!isa<SCEVAddRecExpr>(SCEV))
191 // If this phi node is used in a compare instruction then it is a
192 // split condition candidate.
193 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
195 if (ICmpInst *CI = dyn_cast<ICmpInst>(*UI)) {
196 SD.SplitCondition = CI;
201 // Valid SplitCondition's one operand is phi node and the other operand
202 // is loop invariant.
203 if (SD.SplitCondition) {
204 if (SD.SplitCondition->getOperand(0) != PN)
205 SD.SplitValue = SD.SplitCondition->getOperand(0);
207 SD.SplitValue = SD.SplitCondition->getOperand(1);
208 SCEVHandle ValueSCEV = SE->getSCEV(SD.SplitValue);
210 // If SplitValue is not invariant then SplitCondition is not appropriate.
211 if (!ValueSCEV->isLoopInvariant(L))
212 SD.SplitCondition = NULL;
215 // We are looking for only one split condition.
216 if (SD.SplitCondition) {
218 SplitData.push_back(SD);
219 // Before reusing SD for next split condition clear its content.
225 /// processOneIterationLoop - Current loop L contains compare instruction
226 /// that compares induction variable, IndVar, against loop invariant. If
227 /// entire (i.e. meaningful) loop body is dominated by this compare
228 /// instruction then loop body is executed only once. In such case eliminate
229 /// loop structure surrounding this loop body. For example,
230 /// for (int i = start; i < end; ++i) {
231 /// if ( i == somevalue) {
235 /// can be transformed into
236 /// if (somevalue >= start && somevalue < end) {
240 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD, LPPassManager &LPM) {
242 BasicBlock *Header = L->getHeader();
244 // First of all, check if SplitCondition dominates entire loop body
247 // If SplitCondition is not in loop header then this loop is not suitable
248 // for this transformation.
249 if (SD.SplitCondition->getParent() != Header)
252 // If one of the Header block's successor is not an exit block then this
253 // loop is not a suitable candidate.
254 BasicBlock *ExitBlock = NULL;
255 for (succ_iterator SI = succ_begin(Header), E = succ_end(Header); SI != E; ++SI) {
256 if (L->isLoopExit(*SI)) {
265 // If loop header includes loop variant instruction operands then
266 // this loop may not be eliminated.
267 if (!safeHeader(SD, Header))
270 // If Exit block includes loop variant instructions then this
271 // loop may not be eliminated.
272 if (!safeExitBlock(SD, ExitBlock))
277 // As a first step to break this loop, remove Latch to Header edge.
278 BasicBlock *Latch = L->getLoopLatch();
279 BasicBlock *LatchSucc = NULL;
280 BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
283 Header->removePredecessor(Latch);
284 for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
289 BR->setUnconditionalDest(LatchSucc);
291 BasicBlock *Preheader = L->getLoopPreheader();
292 Instruction *Terminator = Header->getTerminator();
293 Value *StartValue = SD.IndVar->getIncomingValueForBlock(Preheader);
295 // Replace split condition in header.
297 // SplitCondition : icmp eq i32 IndVar, SplitValue
299 // c1 = icmp uge i32 SplitValue, StartValue
300 // c2 = icmp ult i32 vSplitValue, ExitValue
302 bool SignedPredicate = SD.ExitCondition->isSignedPredicate();
303 Instruction *C1 = new ICmpInst(SignedPredicate ?
304 ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
305 SD.SplitValue, StartValue, "lisplit",
307 Instruction *C2 = new ICmpInst(SignedPredicate ?
308 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
309 SD.SplitValue, SD.ExitValue, "lisplit",
311 Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit",
313 SD.SplitCondition->replaceAllUsesWith(NSplitCond);
314 SD.SplitCondition->eraseFromParent();
316 // Now, clear latch block. Remove instructions that are responsible
317 // to increment induction variable.
318 Instruction *LTerminator = Latch->getTerminator();
319 for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
323 if (isa<PHINode>(I) || I == LTerminator)
326 I->replaceAllUsesWith(UndefValue::get(I->getType()));
327 I->eraseFromParent();
330 LPM.deleteLoopFromQueue(L);
332 // Update Dominator Info.
333 // Only CFG change done is to remove Latch to Header edge. This
334 // does not change dominator tree because Latch did not dominate
336 if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
337 DominanceFrontier::iterator HeaderDF = DF->find(Header);
338 if (HeaderDF != DF->end())
339 DF->removeFromFrontier(HeaderDF, Header);
341 DominanceFrontier::iterator LatchDF = DF->find(Latch);
342 if (LatchDF != DF->end())
343 DF->removeFromFrontier(LatchDF, Header);
348 // If loop header includes loop variant instruction operands then
349 // this loop can not be eliminated. This is used by processOneIterationLoop().
350 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
352 Instruction *Terminator = Header->getTerminator();
353 for(BasicBlock::iterator BI = Header->begin(), BE = Header->end();
357 // PHI Nodes are OK. FIXME : Handle last value assignments.
361 // SplitCondition itself is OK.
362 if (I == SD.SplitCondition)
365 // Terminator is also harmless.
369 // Otherwise we have a instruction that may not be safe.
376 // If Exit block includes loop variant instructions then this
377 // loop may not be eliminated. This is used by processOneIterationLoop().
378 bool LoopIndexSplit::safeExitBlock(SplitInfo &SD, BasicBlock *ExitBlock) {
380 Instruction *IndVarIncrement = NULL;
382 for (BasicBlock::iterator BI = ExitBlock->begin(), BE = ExitBlock->end();
386 // PHI Nodes are OK. FIXME : Handle last value assignments.
390 // Check if I is induction variable increment instruction.
391 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(I)) {
392 if (BOp->getOpcode() != Instruction::Add)
395 Value *Op0 = BOp->getOperand(0);
396 Value *Op1 = BOp->getOperand(1);
398 ConstantInt *CI = NULL;
400 if ((PN = dyn_cast<PHINode>(Op0))) {
401 if ((CI = dyn_cast<ConstantInt>(Op1)))
404 if ((PN = dyn_cast<PHINode>(Op1))) {
405 if ((CI = dyn_cast<ConstantInt>(Op0)))
409 if (IndVarIncrement && PN == SD.IndVar && CI->isOne())
413 // I is an Exit condition if next instruction is block terminator.
414 // Exit condition is OK if it compares loop invariant exit value,
415 // which is checked below.
416 else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
419 if (N == ExitBlock->getTerminator()) {
420 SD.ExitCondition = EC;
425 // Otherwise we have instruction that may not be safe.
429 // Check if Exit condition is comparing induction variable against
430 // loop invariant value. If one operand is induction variable and
431 // the other operand is loop invaraint then Exit condition is safe.
432 if (SD.ExitCondition) {
433 Value *Op0 = SD.ExitCondition->getOperand(0);
434 Value *Op1 = SD.ExitCondition->getOperand(1);
436 Instruction *Insn0 = dyn_cast<Instruction>(Op0);
437 Instruction *Insn1 = dyn_cast<Instruction>(Op1);
439 if (Insn0 && Insn0 == IndVarIncrement)
441 else if (Insn1 && Insn1 == IndVarIncrement)
444 SCEVHandle ValueSCEV = SE->getSCEV(SD.ExitValue);
445 if (!ValueSCEV->isLoopInvariant(L))
449 // We could not find any reason to consider ExitBlock unsafe.
453 /// Find cost of spliting loop L. Cost is measured in terms of size growth.
454 /// Size is growth is calculated based on amount of code duplicated in second
456 unsigned LoopIndexSplit::findSplitCost(Loop *L, SplitInfo &SD) {
459 BasicBlock *SDBlock = SD.SplitCondition->getParent();
460 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
463 // If a block is not dominated by split condition block then
464 // it must be duplicated in both loops.
465 if (!DT->dominates(SDBlock, BB))
472 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {