17bae1e4e2582a54b15f3fc1f84ecdf158de1862
[oota-llvm.git] / lib / Transforms / Scalar / LoopIndexSplit.cpp
1 //===- LoopIndexSplit.cpp - Loop Index Splitting Pass ---------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements Loop Index Splitting Pass.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "loop-index-split"
15
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"
23
24 using namespace llvm;
25
26 STATISTIC(NumIndexSplit, "Number of loops index split");
27
28 namespace {
29
30   class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
31
32   public:
33     static char ID; // Pass ID, replacement for typeid
34     LoopIndexSplit() : LoopPass((intptr_t)&ID) {}
35
36     // Index split Loop L. Return true if loop is split.
37     bool runOnLoop(Loop *L, LPPassManager &LPM);
38
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>();
50     }
51
52   private:
53
54     class SplitInfo {
55     public:
56       SplitInfo() : IndVar(NULL), SplitValue(NULL), ExitValue(NULL),
57                     SplitCondition(NULL), ExitCondition(NULL), 
58                     IndVarIncrement(NULL) {}
59
60       // Induction variable whose range is being split by this transformation.
61       PHINode *IndVar;
62       
63       // Induction variable's range is split at this value.
64       Value *SplitValue;
65       
66       // Induction variable's final loop exit value.
67       Value *ExitValue;
68       
69       // This compare instruction compares IndVar against SplitValue.
70       ICmpInst *SplitCondition;
71
72       // Loop exit condition.
73       ICmpInst *ExitCondition;
74
75       Instruction *IndVarIncrement;
76
77       // Clear split info.
78       void clear() {
79         IndVar = NULL;
80         SplitValue = NULL;
81         ExitValue = NULL;
82         SplitCondition = NULL;
83         ExitCondition = NULL;
84         IndVarIncrement = NULL;
85       }
86
87       /// Return true if V is a induction variable or induction variable's
88       /// increment for loop L.
89       bool findIndVar(Value *V, Loop *L);
90     };
91
92   private:
93     /// Find condition inside a loop that is suitable candidate for index split.
94     void findSplitCondition();
95
96     /// processOneIterationLoop - Current loop L contains compare instruction
97     /// that compares induction variable, IndVar, agains loop invariant. If
98     /// entire (i.e. meaningful) loop body is dominated by this compare
99     /// instruction then loop body is executed only for one iteration. In
100     /// such case eliminate loop structure surrounding this loop body. For
101     bool processOneIterationLoop(SplitInfo &SD, LPPassManager &LPM);
102     
103     /// If loop header includes loop variant instruction operands then
104     /// this loop may not be eliminated.
105     bool safeHeader(SplitInfo &SD,  BasicBlock *BB);
106
107     /// If Exit block includes loop variant instructions then this
108     /// loop may not be eliminated.
109     bool safeExitBlock(SplitInfo &SD, BasicBlock *BB);
110
111     /// Find cost of spliting loop L.
112     unsigned findSplitCost(Loop *L, SplitInfo &SD);
113     bool splitLoop(SplitInfo &SD);
114
115   private:
116
117     // Current Loop.
118     Loop *L;
119     ScalarEvolution *SE;
120     DominatorTree *DT;
121     SmallVector<SplitInfo, 4> SplitData;
122   };
123
124   char LoopIndexSplit::ID = 0;
125   RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
126 }
127
128 LoopPass *llvm::createLoopIndexSplitPass() {
129   return new LoopIndexSplit();
130 }
131
132 // Index split Loop L. Return true if loop is split.
133 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM) {
134   bool Changed = false;
135   L = IncomingLoop;
136
137   SE = &getAnalysis<ScalarEvolution>();
138   DT = &getAnalysis<DominatorTree>();
139
140   findSplitCondition();
141
142   if (SplitData.empty())
143     return false;
144
145   // First see if it is possible to eliminate loop itself or not.
146   for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
147          E = SplitData.end(); SI != E; ++SI) {
148     SplitInfo &SD = *SI;
149     if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
150       Changed = processOneIterationLoop(SD,LPM);
151       if (Changed) {
152         ++NumIndexSplit;
153         // If is loop is eliminated then nothing else to do here.
154         return Changed;
155       }
156     }
157   }
158
159   unsigned MaxCost = 99;
160   unsigned Index = 0;
161   unsigned MostProfitableSDIndex = 0;
162   for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
163          E = SplitData.end(); SI != E; ++SI, ++Index) {
164     SplitInfo SD = *SI;
165
166     // ICM_EQs are already handled above.
167     if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ)
168       continue;
169     
170     unsigned Cost = findSplitCost(L, SD);
171     if (Cost < MaxCost)
172       MostProfitableSDIndex = Index;
173   }
174
175   // Split most profitiable condition.
176   Changed = splitLoop(SplitData[MostProfitableSDIndex]);
177
178   if (Changed)
179     ++NumIndexSplit;
180   
181   return Changed;
182 }
183
184 /// Return true if V is a induction variable or induction variable's
185 /// increment for loop L.
186 bool LoopIndexSplit::SplitInfo::findIndVar(Value *V, Loop *L) {
187   
188   Instruction *I = dyn_cast<Instruction>(V);
189   if (!I)
190     return false;
191
192   // Check if I is a phi node from loop header or not.
193   if (PHINode *PN = dyn_cast<PHINode>(V)) {
194     if (PN->getParent() == L->getHeader()) {
195             IndVar = PN;
196             return true;
197     }
198   }
199  
200   // Check if I is a add instruction whose one operand is
201   // phi node from loop header and second operand is constant.
202   if (I->getOpcode() != Instruction::Add)
203     return false;
204   
205   Value *Op0 = I->getOperand(0);
206   Value *Op1 = I->getOperand(1);
207   
208   if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
209     if (PN->getParent() == L->getHeader()
210         && isa<ConstantInt>(Op1)) {
211       IndVar = PN;
212       IndVarIncrement = I;
213       return true;
214     }
215   }
216   
217   if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
218     if (PN->getParent() == L->getHeader()
219         && isa<ConstantInt>(Op0)) {
220       IndVar = PN;
221       IndVarIncrement = I;
222       return true;
223     }
224   }
225   
226   return false;
227 }
228
229 /// Find condition inside a loop that is suitable candidate for index split.
230 void LoopIndexSplit::findSplitCondition() {
231
232   SplitInfo SD;
233   // Check all basic block's terminators.
234
235   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
236        I != E; ++I) {
237     BasicBlock *BB = *I;
238
239     // If this basic block does not terminate in a conditional branch
240     // then terminator is not a suitable split condition.
241     BranchInst *BR = dyn_cast<BranchInst>(BB->getTerminator());
242     if (!BR)
243       continue;
244     
245     if (BR->isUnconditional())
246       continue;
247
248     ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
249     if (!CI)
250       return;
251
252     // If one operand is loop invariant and second operand is SCEVAddRecExpr
253     // based on induction variable then CI is a candidate split condition.
254     Value *V0 = CI->getOperand(0);
255     Value *V1 = CI->getOperand(1);
256
257     SCEVHandle SH0 = SE->getSCEV(V0);
258     SCEVHandle SH1 = SE->getSCEV(V1);
259
260     if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
261       SD.SplitValue = V0;
262       SD.SplitCondition = CI;
263       if (SD.findIndVar(V1, L))
264         SplitData.push_back(SD);
265     }
266     else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
267       SD.SplitValue =  V1;
268       SD.SplitCondition = CI;
269       if (SD.findIndVar(V0, L))
270         SplitData.push_back(SD);
271     }
272   }
273 }
274
275 /// processOneIterationLoop - Current loop L contains compare instruction
276 /// that compares induction variable, IndVar, against loop invariant. If
277 /// entire (i.e. meaningful) loop body is dominated by this compare
278 /// instruction then loop body is executed only once. In such case eliminate 
279 /// loop structure surrounding this loop body. For example,
280 ///     for (int i = start; i < end; ++i) {
281 ///         if ( i == somevalue) {
282 ///           loop_body
283 ///         }
284 ///     }
285 /// can be transformed into
286 ///     if (somevalue >= start && somevalue < end) {
287 ///        i = somevalue;
288 ///        loop_body
289 ///     }
290 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD, LPPassManager &LPM) {
291
292   BasicBlock *Header = L->getHeader();
293
294   // First of all, check if SplitCondition dominates entire loop body
295   // or not.
296   
297   // If SplitCondition is not in loop header then this loop is not suitable
298   // for this transformation.
299   if (SD.SplitCondition->getParent() != Header)
300     return false;
301   
302   // If one of the Header block's successor is not an exit block then this
303   // loop is not a suitable candidate.
304   BasicBlock *ExitBlock = NULL;
305   for (succ_iterator SI = succ_begin(Header), E = succ_end(Header); SI != E; ++SI) {
306     if (L->isLoopExit(*SI)) {
307       ExitBlock = *SI;
308       break;
309     }
310   }
311
312   if (!ExitBlock)
313     return false;
314
315   // If loop header includes loop variant instruction operands then
316   // this loop may not be eliminated.
317   if (!safeHeader(SD, Header)) 
318     return false;
319
320   // If Exit block includes loop variant instructions then this
321   // loop may not be eliminated.
322   if (!safeExitBlock(SD, ExitBlock)) 
323     return false;
324
325   // Update CFG.
326
327   // As a first step to break this loop, remove Latch to Header edge.
328   BasicBlock *Latch = L->getLoopLatch();
329   BasicBlock *LatchSucc = NULL;
330   BranchInst *BR = dyn_cast<BranchInst>(Latch->getTerminator());
331   if (!BR)
332     return false;
333   Header->removePredecessor(Latch);
334   for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
335        SI != E; ++SI) {
336     if (Header != *SI)
337       LatchSucc = *SI;
338   }
339   BR->setUnconditionalDest(LatchSucc);
340
341   BasicBlock *Preheader = L->getLoopPreheader();
342   Instruction *Terminator = Header->getTerminator();
343   Value *StartValue = SD.IndVar->getIncomingValueForBlock(Preheader);
344
345   // Replace split condition in header.
346   // Transform 
347   //      SplitCondition : icmp eq i32 IndVar, SplitValue
348   // into
349   //      c1 = icmp uge i32 SplitValue, StartValue
350   //      c2 = icmp ult i32 vSplitValue, ExitValue
351   //      and i32 c1, c2 
352   bool SignedPredicate = SD.ExitCondition->isSignedPredicate();
353   Instruction *C1 = new ICmpInst(SignedPredicate ? 
354                                  ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
355                                  SD.SplitValue, StartValue, "lisplit", 
356                                  Terminator);
357   Instruction *C2 = new ICmpInst(SignedPredicate ? 
358                                  ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
359                                  SD.SplitValue, SD.ExitValue, "lisplit", 
360                                  Terminator);
361   Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit", 
362                                                       Terminator);
363   SD.SplitCondition->replaceAllUsesWith(NSplitCond);
364   SD.SplitCondition->eraseFromParent();
365
366   // Now, clear latch block. Remove instructions that are responsible
367   // to increment induction variable. 
368   Instruction *LTerminator = Latch->getTerminator();
369   for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
370        LB != LE; ) {
371     Instruction *I = LB;
372     ++LB;
373     if (isa<PHINode>(I) || I == LTerminator)
374       continue;
375
376     I->replaceAllUsesWith(UndefValue::get(I->getType()));
377     I->eraseFromParent();
378   }
379
380   LPM.deleteLoopFromQueue(L);
381
382   // Update Dominator Info.
383   // Only CFG change done is to remove Latch to Header edge. This
384   // does not change dominator tree because Latch did not dominate
385   // Header.
386   if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
387     DominanceFrontier::iterator HeaderDF = DF->find(Header);
388     if (HeaderDF != DF->end()) 
389       DF->removeFromFrontier(HeaderDF, Header);
390
391     DominanceFrontier::iterator LatchDF = DF->find(Latch);
392     if (LatchDF != DF->end()) 
393       DF->removeFromFrontier(LatchDF, Header);
394   }
395   return true;
396 }
397
398 // If loop header includes loop variant instruction operands then
399 // this loop can not be eliminated. This is used by processOneIterationLoop().
400 bool LoopIndexSplit::safeHeader(SplitInfo &SD, BasicBlock *Header) {
401
402   Instruction *Terminator = Header->getTerminator();
403   for(BasicBlock::iterator BI = Header->begin(), BE = Header->end(); 
404       BI != BE; ++BI) {
405     Instruction *I = BI;
406
407     // PHI Nodes are OK. FIXME : Handle last value assignments.
408     if (isa<PHINode>(I))
409       continue;
410
411     // SplitCondition itself is OK.
412     if (I == SD.SplitCondition)
413       continue;
414
415     // Induction variable is OK.
416     if (I == SD.IndVar)
417       continue;
418
419     // Induction variable increment is OK.
420     if (I == SD.IndVarIncrement)
421       continue;
422
423     // Terminator is also harmless.
424     if (I == Terminator)
425       continue;
426
427     // Otherwise we have a instruction that may not be safe.
428     return false;
429   }
430   
431   return true;
432 }
433
434 // If Exit block includes loop variant instructions then this
435 // loop may not be eliminated. This is used by processOneIterationLoop().
436 bool LoopIndexSplit::safeExitBlock(SplitInfo &SD, BasicBlock *ExitBlock) {
437
438   for (BasicBlock::iterator BI = ExitBlock->begin(), BE = ExitBlock->end();
439        BI != BE; ++BI) {
440     Instruction *I = BI;
441
442     // PHI Nodes are OK. FIXME : Handle last value assignments.
443     if (isa<PHINode>(I))
444       continue;
445
446     // Induction variable increment is OK.
447     if (SD.IndVarIncrement && SD.IndVarIncrement == I)
448       continue;
449
450     // Check if I is induction variable increment instruction.
451     if (!SD.IndVarIncrement && I->getOpcode() == Instruction::Add) {
452
453       Value *Op0 = I->getOperand(0);
454       Value *Op1 = I->getOperand(1);
455       PHINode *PN = NULL;
456       ConstantInt *CI = NULL;
457
458       if ((PN = dyn_cast<PHINode>(Op0))) {
459         if ((CI = dyn_cast<ConstantInt>(Op1)))
460           SD.IndVarIncrement = I;
461       } else 
462         if ((PN = dyn_cast<PHINode>(Op1))) {
463           if ((CI = dyn_cast<ConstantInt>(Op0)))
464             SD.IndVarIncrement = I;
465       }
466           
467       if (SD.IndVarIncrement && PN == SD.IndVar && CI->isOne())
468         continue;
469     }
470
471     // I is an Exit condition if next instruction is block terminator.
472     // Exit condition is OK if it compares loop invariant exit value,
473     // which is checked below.
474     else if (ICmpInst *EC = dyn_cast<ICmpInst>(I)) {
475       ++BI;
476       Instruction *N = BI;
477       if (N == ExitBlock->getTerminator()) {
478         SD.ExitCondition = EC;
479         continue;
480       }
481     }
482
483     // Otherwise we have instruction that may not be safe.
484     return false;
485   }
486
487   // Check if Exit condition is comparing induction variable against 
488   // loop invariant value. If one operand is induction variable and 
489   // the other operand is loop invaraint then Exit condition is safe.
490   if (SD.ExitCondition) {
491     Value *Op0 = SD.ExitCondition->getOperand(0);
492     Value *Op1 = SD.ExitCondition->getOperand(1);
493
494     Instruction *Insn0 = dyn_cast<Instruction>(Op0);
495     Instruction *Insn1 = dyn_cast<Instruction>(Op1);
496     
497     if (Insn0 && Insn0 == SD.IndVarIncrement)
498       SD.ExitValue = Op1;
499     else if (Insn1 && Insn1 == SD.IndVarIncrement)
500       SD.ExitValue = Op0;
501
502     SCEVHandle ValueSCEV = SE->getSCEV(SD.ExitValue);
503     if (!ValueSCEV->isLoopInvariant(L))
504       return false;
505   }
506
507   // We could not find any reason to consider ExitBlock unsafe.
508   return true;
509 }
510
511 /// Find cost of spliting loop L. Cost is measured in terms of size growth.
512 /// Size is growth is calculated based on amount of code duplicated in second
513 /// loop.
514 unsigned LoopIndexSplit::findSplitCost(Loop *L, SplitInfo &SD) {
515
516   unsigned Cost = 0;
517   BasicBlock *SDBlock = SD.SplitCondition->getParent();
518   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
519        I != E; ++I) {
520     BasicBlock *BB = *I;
521     // If a block is not dominated by split condition block then
522     // it must be duplicated in both loops.
523     if (!DT->dominates(SDBlock, BB))
524       Cost += BB->size();
525   }
526
527   return Cost;
528 }
529
530 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
531   // FIXME :)
532   return false;
533 }