Remove unused variables.
[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/Transforms/Utils/BasicBlockUtils.h"
22 #include "llvm/Transforms/Utils/Cloning.h"
23 #include "llvm/Support/Compiler.h"
24 #include "llvm/ADT/Statistic.h"
25
26 using namespace llvm;
27
28 STATISTIC(NumIndexSplit, "Number of loops index split");
29
30 namespace {
31
32   class VISIBILITY_HIDDEN LoopIndexSplit : public LoopPass {
33
34   public:
35     static char ID; // Pass ID, replacement for typeid
36     LoopIndexSplit() : LoopPass((intptr_t)&ID) {}
37
38     // Index split Loop L. Return true if loop is split.
39     bool runOnLoop(Loop *L, LPPassManager &LPM);
40
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>();
53     }
54
55   private:
56
57     class SplitInfo {
58     public:
59       SplitInfo() : SplitValue(NULL), SplitCondition(NULL) {}
60
61       // Induction variable's range is split at this value.
62       Value *SplitValue;
63       
64       // This compare instruction compares IndVar against SplitValue.
65       ICmpInst *SplitCondition;
66
67       // Clear split info.
68       void clear() {
69         SplitValue = NULL;
70         SplitCondition = NULL;
71       }
72
73     };
74     
75   private:
76     /// Find condition inside a loop that is suitable candidate for index split.
77     void findSplitCondition();
78
79     /// Find loop's exit condition.
80     void findLoopConditionals();
81
82     /// Return induction variable associated with value V.
83     void findIndVar(Value *V, Loop *L);
84
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);
91     
92     /// If loop header includes loop variant instruction operands then
93     /// this loop may not be eliminated.
94     bool safeHeader(SplitInfo &SD,  BasicBlock *BB);
95
96     /// If Exit block includes loop variant instructions then this
97     /// loop may not be eliminated.
98     bool safeExitBlock(SplitInfo &SD, BasicBlock *BB);
99
100     /// Find cost of spliting loop L.
101     unsigned findSplitCost(Loop *L, SplitInfo &SD);
102     bool splitLoop(SplitInfo &SD);
103
104     void initialize() {
105       IndVar = NULL; 
106       IndVarIncrement = NULL;
107       ExitCondition = NULL;
108       StartValue = ExitValue = NULL;
109     }
110
111   private:
112
113     // Current Loop.
114     Loop *L;
115     LPPassManager *LPM;
116     LoopInfo *LI;
117     ScalarEvolution *SE;
118     DominatorTree *DT;
119     SmallVector<SplitInfo, 4> SplitData;
120
121     // Induction variable whose range is being split by this transformation.
122     PHINode *IndVar;
123     Instruction *IndVarIncrement;
124       
125     // Loop exit condition.
126     ICmpInst *ExitCondition;
127
128     // Induction variable's initial value.
129     Value *StartValue;
130
131     // Induction variable's final loop exit value.
132     Value *ExitValue;
133   };
134
135   char LoopIndexSplit::ID = 0;
136   RegisterPass<LoopIndexSplit> X ("loop-index-split", "Index Split Loops");
137 }
138
139 LoopPass *llvm::createLoopIndexSplitPass() {
140   return new LoopIndexSplit();
141 }
142
143 // Index split Loop L. Return true if loop is split.
144 bool LoopIndexSplit::runOnLoop(Loop *IncomingLoop, LPPassManager &LPM_Ref) {
145   bool Changed = false;
146   L = IncomingLoop;
147   LPM = &LPM_Ref;
148
149   SE = &getAnalysis<ScalarEvolution>();
150   DT = &getAnalysis<DominatorTree>();
151   LI = &getAnalysis<LoopInfo>();
152
153   initialize();
154
155   findLoopConditionals();
156
157   if (!ExitCondition)
158     return false;
159
160   findSplitCondition();
161
162   if (SplitData.empty())
163     return false;
164
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) {
168     SplitInfo &SD = *SI;
169     if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ) {
170       Changed = processOneIterationLoop(SD);
171       if (Changed) {
172         ++NumIndexSplit;
173         // If is loop is eliminated then nothing else to do here.
174         return Changed;
175       }
176     }
177   }
178
179   unsigned MaxCost = 99;
180   unsigned Index = 0;
181   unsigned MostProfitableSDIndex = 0;
182   for (SmallVector<SplitInfo, 4>::iterator SI = SplitData.begin(),
183          E = SplitData.end(); SI != E; ++SI, ++Index) {
184     SplitInfo SD = *SI;
185
186     // ICM_EQs are already handled above.
187     if (SD.SplitCondition->getPredicate() == ICmpInst::ICMP_EQ)
188       continue;
189     
190     unsigned Cost = findSplitCost(L, SD);
191     if (Cost < MaxCost)
192       MostProfitableSDIndex = Index;
193   }
194
195   // Split most profitiable condition.
196   Changed = splitLoop(SplitData[MostProfitableSDIndex]);
197
198   if (Changed)
199     ++NumIndexSplit;
200   
201   return Changed;
202 }
203
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) {
207   
208   Instruction *I = dyn_cast<Instruction>(V);
209   if (!I)
210     return;
211
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()) {
215       IndVar = PN;
216       return;
217     }
218   }
219  
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)
223     return;
224   
225   Value *Op0 = I->getOperand(0);
226   Value *Op1 = I->getOperand(1);
227   
228   if (PHINode *PN = dyn_cast<PHINode>(Op0)) {
229     if (PN->getParent() == L->getHeader()
230         && isa<ConstantInt>(Op1)) {
231       IndVar = PN;
232       IndVarIncrement = I;
233       return;
234     }
235   }
236   
237   if (PHINode *PN = dyn_cast<PHINode>(Op1)) {
238     if (PN->getParent() == L->getHeader()
239         && isa<ConstantInt>(Op0)) {
240       IndVar = PN;
241       IndVarIncrement = I;
242       return;
243     }
244   }
245   
246   return;
247 }
248
249 // Find loop's exit condition and associated induction variable.
250 void LoopIndexSplit::findLoopConditionals() {
251
252   BasicBlock *ExitBlock = NULL;
253
254   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
255        I != E; ++I) {
256     BasicBlock *BB = *I;
257     if (!L->isLoopExit(BB))
258       continue;
259     if (ExitBlock)
260       return;
261     ExitBlock = BB;
262   }
263
264   if (!ExitBlock)
265     return;
266   
267   // If exit block's terminator is conditional branch inst then we have found
268   // exit condition.
269   BranchInst *BR = dyn_cast<BranchInst>(ExitBlock->getTerminator());
270   if (!BR || BR->isUnconditional())
271     return;
272   
273   ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
274   if (!CI)
275     return;
276   
277   ExitCondition = CI;
278
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);
283   
284   SCEVHandle SH0 = SE->getSCEV(V0);
285   SCEVHandle SH1 = SE->getSCEV(V1);
286   
287   if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
288     ExitValue = V0;
289     findIndVar(V1, L);
290   }
291   else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
292     ExitValue =  V1;
293     findIndVar(V0, L);
294   }
295
296   if (!ExitValue || !IndVar)
297     ExitCondition = NULL;
298   else if (IndVar) {
299     BasicBlock *Preheader = L->getLoopPreheader();
300     StartValue = IndVar->getIncomingValueForBlock(Preheader);
301   }
302 }
303
304 /// Find condition inside a loop that is suitable candidate for index split.
305 void LoopIndexSplit::findSplitCondition() {
306
307   SplitInfo SD;
308   // Check all basic block's terminators.
309
310   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
311        I != E; ++I) {
312     BasicBlock *BB = *I;
313
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());
317     if (!BR)
318       continue;
319     
320     if (BR->isUnconditional())
321       continue;
322
323     ICmpInst *CI = dyn_cast<ICmpInst>(BR->getCondition());
324     if (!CI || CI == ExitCondition)
325       return;
326
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);
331
332     SCEVHandle SH0 = SE->getSCEV(V0);
333     SCEVHandle SH1 = SE->getSCEV(V1);
334
335     if (SH0->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH1)) {
336       SD.SplitValue = V0;
337       SD.SplitCondition = CI;
338       if (PHINode *PN = dyn_cast<PHINode>(V1)) {
339         if (PN == IndVar)
340           SplitData.push_back(SD);
341       }
342       else  if (Instruction *Insn = dyn_cast<Instruction>(V1)) {
343         if (IndVarIncrement && IndVarIncrement == Insn)
344           SplitData.push_back(SD);
345       }
346     }
347     else if (SH1->isLoopInvariant(L) && isa<SCEVAddRecExpr>(SH0)) {
348       SD.SplitValue =  V1;
349       SD.SplitCondition = CI;
350       if (PHINode *PN = dyn_cast<PHINode>(V0)) {
351         if (PN == IndVar)
352           SplitData.push_back(SD);
353       }
354       else  if (Instruction *Insn = dyn_cast<Instruction>(V0)) {
355         if (IndVarIncrement && IndVarIncrement == Insn)
356           SplitData.push_back(SD);
357       }
358     }
359   }
360 }
361
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) {
369 ///           loop_body
370 ///         }
371 ///     }
372 /// can be transformed into
373 ///     if (somevalue >= start && somevalue < end) {
374 ///        i = somevalue;
375 ///        loop_body
376 ///     }
377 bool LoopIndexSplit::processOneIterationLoop(SplitInfo &SD) {
378
379   BasicBlock *Header = L->getHeader();
380
381   // First of all, check if SplitCondition dominates entire loop body
382   // or not.
383   
384   // If SplitCondition is not in loop header then this loop is not suitable
385   // for this transformation.
386   if (SD.SplitCondition->getParent() != Header)
387     return false;
388   
389   // If loop header includes loop variant instruction operands then
390   // this loop may not be eliminated.
391   if (!safeHeader(SD, Header)) 
392     return false;
393
394   // If Exit block includes loop variant instructions then this
395   // loop may not be eliminated.
396   if (!safeExitBlock(SD, ExitCondition->getParent())) 
397     return false;
398
399   // Update CFG.
400
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());
405   if (!BR)
406     return false;
407   Header->removePredecessor(Latch);
408   for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
409        SI != E; ++SI) {
410     if (Header != *SI)
411       LatchSucc = *SI;
412   }
413   BR->setUnconditionalDest(LatchSucc);
414
415   BasicBlock *Preheader = L->getLoopPreheader();
416   Instruction *Terminator = Header->getTerminator();
417   StartValue = IndVar->getIncomingValueForBlock(Preheader);
418
419   // Replace split condition in header.
420   // Transform 
421   //      SplitCondition : icmp eq i32 IndVar, SplitValue
422   // into
423   //      c1 = icmp uge i32 SplitValue, StartValue
424   //      c2 = icmp ult i32 vSplitValue, ExitValue
425   //      and i32 c1, c2 
426   bool SignedPredicate = ExitCondition->isSignedPredicate();
427   Instruction *C1 = new ICmpInst(SignedPredicate ? 
428                                  ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
429                                  SD.SplitValue, StartValue, "lisplit", 
430                                  Terminator);
431   Instruction *C2 = new ICmpInst(SignedPredicate ? 
432                                  ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
433                                  SD.SplitValue, ExitValue, "lisplit", 
434                                  Terminator);
435   Instruction *NSplitCond = BinaryOperator::createAnd(C1, C2, "lisplit", 
436                                                       Terminator);
437   SD.SplitCondition->replaceAllUsesWith(NSplitCond);
438   SD.SplitCondition->eraseFromParent();
439
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();
444        LB != LE; ) {
445     Instruction *I = LB;
446     ++LB;
447     if (isa<PHINode>(I) || I == LTerminator)
448       continue;
449
450     I->replaceAllUsesWith(UndefValue::get(I->getType()));
451     I->eraseFromParent();
452   }
453
454   LPM->deleteLoopFromQueue(L);
455
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
459   // Header.
460   if (DominanceFrontier *DF = getAnalysisToUpdate<DominanceFrontier>()) {
461     DominanceFrontier::iterator HeaderDF = DF->find(Header);
462     if (HeaderDF != DF->end()) 
463       DF->removeFromFrontier(HeaderDF, Header);
464
465     DominanceFrontier::iterator LatchDF = DF->find(Latch);
466     if (LatchDF != DF->end()) 
467       DF->removeFromFrontier(LatchDF, Header);
468   }
469   return true;
470 }
471
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) {
475
476   Instruction *Terminator = Header->getTerminator();
477   for(BasicBlock::iterator BI = Header->begin(), BE = Header->end(); 
478       BI != BE; ++BI) {
479     Instruction *I = BI;
480
481     // PHI Nodes are OK. FIXME : Handle last value assignments.
482     if (isa<PHINode>(I))
483       continue;
484
485     // SplitCondition itself is OK.
486     if (I == SD.SplitCondition)
487       continue;
488
489     // Induction variable is OK.
490     if (I == IndVar)
491       continue;
492
493     // Induction variable increment is OK.
494     if (I == IndVarIncrement)
495       continue;
496
497     // Terminator is also harmless.
498     if (I == Terminator)
499       continue;
500
501     // Otherwise we have a instruction that may not be safe.
502     return false;
503   }
504   
505   return true;
506 }
507
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) {
511
512   for (BasicBlock::iterator BI = ExitBlock->begin(), BE = ExitBlock->end();
513        BI != BE; ++BI) {
514     Instruction *I = BI;
515
516     // PHI Nodes are OK. FIXME : Handle last value assignments.
517     if (isa<PHINode>(I))
518       continue;
519
520     // Induction variable increment is OK.
521     if (IndVarIncrement && IndVarIncrement == I)
522       continue;
523
524     // Check if I is induction variable increment instruction.
525     if (!IndVarIncrement && I->getOpcode() == Instruction::Add) {
526
527       Value *Op0 = I->getOperand(0);
528       Value *Op1 = I->getOperand(1);
529       PHINode *PN = NULL;
530       ConstantInt *CI = NULL;
531
532       if ((PN = dyn_cast<PHINode>(Op0))) {
533         if ((CI = dyn_cast<ConstantInt>(Op1)))
534           IndVarIncrement = I;
535       } else 
536         if ((PN = dyn_cast<PHINode>(Op1))) {
537           if ((CI = dyn_cast<ConstantInt>(Op0)))
538             IndVarIncrement = I;
539       }
540           
541       if (IndVarIncrement && PN == IndVar && CI->isOne())
542         continue;
543     }
544
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)
550         continue;
551     }
552
553     if (I == ExitBlock->getTerminator())
554       continue;
555
556     // Otherwise we have instruction that may not be safe.
557     return false;
558   }
559
560   // We could not find any reason to consider ExitBlock unsafe.
561   return true;
562 }
563
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
566 /// loop.
567 unsigned LoopIndexSplit::findSplitCost(Loop *L, SplitInfo &SD) {
568
569   unsigned Cost = 0;
570   BasicBlock *SDBlock = SD.SplitCondition->getParent();
571   for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
572        I != E; ++I) {
573     BasicBlock *BB = *I;
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))
577       Cost += BB->size();
578   }
579
580   return Cost;
581 }
582
583 bool LoopIndexSplit::splitLoop(SplitInfo &SD) {
584
585   BasicBlock *Preheader = L->getLoopPreheader();
586
587   // True loop is original loop. False loop is cloned loop.
588
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;
599   }
600   else {
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());
607
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());
614   }
615
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);
625
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);
630
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.
639   return false;
640 }