Convert xforms over to new pass structure.
[oota-llvm.git] / lib / Transforms / Scalar / InductionVars.cpp
1 //===- InductionVars.cpp - Induction Variable Cannonicalization code --------=//
2 //
3 // This file implements induction variable cannonicalization of loops.
4 //
5 // Specifically, after this executes, the following is true:
6 //   - There is a single induction variable for each loop (at least loops that
7 //     used to contain at least one induction variable)
8 //   * This induction variable starts at 0 and steps by 1 per iteration
9 //   * This induction variable is represented by the first PHI node in the
10 //     Header block, allowing it to be found easily.
11 //   - All other preexisting induction variables are adjusted to operate in
12 //     terms of this primary induction variable
13 //   - Induction variables with a step size of 0 have been eliminated.
14 //
15 // This code assumes the following is true to perform its full job:
16 //   - The CFG has been simplified to not have multiple entrances into an
17 //     interval header.  Interval headers should only have two predecessors,
18 //     one from inside of the loop and one from outside of the loop.
19 //
20 //===----------------------------------------------------------------------===//
21
22 #include "llvm/Transforms/Scalar/InductionVars.h"
23 #include "llvm/ConstantVals.h"
24 #include "llvm/Analysis/IntervalPartition.h"
25 #include "llvm/Assembly/Writer.h"
26 #include "llvm/SymbolTable.h"
27 #include "llvm/iPHINode.h"
28 #include "llvm/Method.h"
29 #include "Support/STLExtras.h"
30 #include <algorithm>
31 #include <iostream>
32 using std::cerr;
33
34 // isLoopInvariant - Return true if the specified value/basic block source is 
35 // an interval invariant computation.
36 //
37 static bool isLoopInvariant(cfg::Interval *Int, Value *V) {
38   assert(isa<Constant>(V) || isa<Instruction>(V) || isa<MethodArgument>(V));
39
40   if (!isa<Instruction>(V))
41     return true;  // Constants and arguments are always loop invariant
42
43   BasicBlock *ValueBlock = cast<Instruction>(V)->getParent();
44   assert(ValueBlock && "Instruction not embedded in basic block!");
45
46   // For now, only consider values from outside of the interval, regardless of
47   // whether the expression could be lifted out of the loop by some LICM.
48   //
49   // TODO: invoke LICM library if we find out it would be useful.
50   //
51   return !Int->contains(ValueBlock);
52 }
53
54
55 // isLinearInductionVariableH - Return isLIV if the expression V is a linear
56 // expression defined in terms of loop invariant computations, and a single
57 // instance of the PHI node PN.  Return isLIC if the expression V is a loop
58 // invariant computation.  Return isNLIV if the expression is a negated linear
59 // induction variable.  Return isOther if it is neither.
60 //
61 // Currently allowed operators are: ADD, SUB, NEG
62 // TODO: This should allow casts!
63 //
64 enum LIVType { isLIV, isLIC, isNLIV, isOther };
65 //
66 // neg - Negate the sign of a LIV expression.
67 inline LIVType neg(LIVType T) { 
68   assert(T == isLIV || T == isNLIV && "Negate Only works on LIV expressions");
69   return T == isLIV ? isNLIV : isLIV; 
70 }
71 //
72 static LIVType isLinearInductionVariableH(cfg::Interval *Int, Value *V,
73                                           PHINode *PN) {
74   if (V == PN) { return isLIV; }  // PHI node references are (0+PHI)
75   if (isLoopInvariant(Int, V)) return isLIC;
76
77   // loop variant computations must be instructions!
78   Instruction *I = cast<Instruction>(V);
79   switch (I->getOpcode()) {       // Handle each instruction seperately
80   case Instruction::Add:
81   case Instruction::Sub: {
82     Value *SubV1 = cast<BinaryOperator>(I)->getOperand(0);
83     Value *SubV2 = cast<BinaryOperator>(I)->getOperand(1);
84     LIVType SubLIVType1 = isLinearInductionVariableH(Int, SubV1, PN);
85     if (SubLIVType1 == isOther) return isOther;  // Early bailout
86     LIVType SubLIVType2 = isLinearInductionVariableH(Int, SubV2, PN);
87
88     switch (SubLIVType2) {
89     case isOther: return isOther;      // Unknown subexpression type
90     case isLIC:   return SubLIVType1;  // Constant offset, return type #1
91     case isLIV:
92     case isNLIV:
93       // So now we know that we have a linear induction variable on the RHS of
94       // the ADD or SUB instruction.  SubLIVType1 cannot be isOther, so it is
95       // either a Loop Invariant computation, or a LIV type.
96       if (SubLIVType1 == isLIC) {
97         // Loop invariant computation, we know this is a LIV then.
98         return (I->getOpcode() == Instruction::Add) ? 
99                        SubLIVType2 : neg(SubLIVType2);
100       }
101
102       // If the LHS is also a LIV Expression, we cannot add two LIVs together
103       if (I->getOpcode() == Instruction::Add) return isOther;
104
105       // We can only subtract two LIVs if they are the same type, which yields
106       // a LIC, because the LIVs cancel each other out.
107       return (SubLIVType1 == SubLIVType2) ? isLIC : isOther;
108     }
109     // NOT REACHED
110   }
111
112   default:            // Any other instruction is not a LINEAR induction var
113     return isOther;
114   }
115 }
116
117 // isLinearInductionVariable - Return true if the specified expression is a
118 // "linear induction variable", which is an expression involving a single 
119 // instance of the PHI node and a loop invariant value that is added or
120 // subtracted to the PHI node.  This is calculated by walking the SSA graph
121 //
122 static inline bool isLinearInductionVariable(cfg::Interval *Int, Value *V,
123                                              PHINode *PN) {
124   return isLinearInductionVariableH(Int, V, PN) == isLIV;
125 }
126
127
128 // isSimpleInductionVar - Return true iff the cannonical induction variable PN
129 // has an initializer of the constant value 0, and has a step size of constant 
130 // 1.
131 static inline bool isSimpleInductionVar(PHINode *PN) {
132   assert(PN->getNumIncomingValues() == 2 && "Must have cannonical PHI node!");
133   Value *Initializer = PN->getIncomingValue(0);
134   if (!isa<Constant>(Initializer)) return false;
135
136   if (Initializer->getType()->isSigned()) {  // Signed constant value...
137     if (((ConstantSInt*)Initializer)->getValue() != 0) return false;
138   } else if (Initializer->getType()->isUnsigned()) {  // Unsigned constant value
139     if (((ConstantUInt*)Initializer)->getValue() != 0) return false;
140   } else {
141     return false;   // Not signed or unsigned?  Must be FP type or something
142   }
143
144   Value *StepExpr = PN->getIncomingValue(1);
145   if (!isa<Instruction>(StepExpr) ||
146       cast<Instruction>(StepExpr)->getOpcode() != Instruction::Add)
147     return false;
148
149   BinaryOperator *I = cast<BinaryOperator>(StepExpr);
150   assert(isa<PHINode>(I->getOperand(0)) && 
151          "PHI node should be first operand of ADD instruction!");
152
153   // Get the right hand side of the ADD node.  See if it is a constant 1.
154   Value *StepSize = I->getOperand(1);
155   if (!isa<Constant>(StepSize)) return false;
156
157   if (StepSize->getType()->isSigned()) {  // Signed constant value...
158     if (((ConstantSInt*)StepSize)->getValue() != 1) return false;
159   } else if (StepSize->getType()->isUnsigned()) {  // Unsigned constant value
160     if (((ConstantUInt*)StepSize)->getValue() != 1) return false;
161   } else {
162     return false;   // Not signed or unsigned?  Must be FP type or something
163   }
164
165   // At this point, we know the initializer is a constant value 0 and the step
166   // size is a constant value 1.  This is our simple induction variable!
167   return true;
168 }
169
170 // InjectSimpleInductionVariable - Insert a cannonical induction variable into
171 // the interval header Header.  This assumes that the flow graph is in 
172 // simplified form (so we know that the header block has exactly 2 predecessors)
173 //
174 // TODO: This should inherit the largest type that is being used by the already
175 // present induction variables (instead of always using uint)
176 //
177 static PHINode *InjectSimpleInductionVariable(cfg::Interval *Int) {
178   std::string PHIName, AddName;
179
180   BasicBlock *Header = Int->getHeaderNode();
181   Method *M = Header->getParent();
182
183   if (M->hasSymbolTable()) {
184     // Only name the induction variable if the method isn't stripped.
185     PHIName = M->getSymbolTable()->getUniqueName(Type::UIntTy, "ind_var");
186     AddName = M->getSymbolTable()->getUniqueName(Type::UIntTy, "ind_var_next");
187   }
188
189   // Create the neccesary instructions...
190   PHINode        *PN      = new PHINode(Type::UIntTy, PHIName);
191   Constant       *One     = ConstantUInt::get(Type::UIntTy, 1);
192   Constant       *Zero    = ConstantUInt::get(Type::UIntTy, 0);
193   BinaryOperator *AddNode = BinaryOperator::create(Instruction::Add, 
194                                                    PN, One, AddName);
195
196   // Figure out which predecessors I have to play with... there should be
197   // exactly two... one of which is a loop predecessor, and one of which is not.
198   //
199   BasicBlock::pred_iterator PI = Header->pred_begin();
200   assert(PI != Header->pred_end() && "Header node should have 2 preds!");
201   BasicBlock *Pred1 = *PI; ++PI;
202   assert(PI != Header->pred_end() && "Header node should have 2 preds!");
203   BasicBlock *Pred2 = *PI;
204   assert(++PI == Header->pred_end() && "Header node should have 2 preds!");
205
206   // Make Pred1 be the loop entrance predecessor, Pred2 be the Loop predecessor
207   if (Int->contains(Pred1)) std::swap(Pred1, Pred2);
208
209   assert(!Int->contains(Pred1) && "Pred1 should be loop entrance!");
210   assert( Int->contains(Pred2) && "Pred2 should be looping edge!");
211
212   // Link the instructions into the PHI node...
213   PN->addIncoming(Zero, Pred1);     // The initializer is first argument
214   PN->addIncoming(AddNode, Pred2);  // The step size is second PHI argument
215   
216   // Insert the PHI node into the Header of the loop.  It shall be the first
217   // instruction, because the "Simple" Induction Variable must be first in the
218   // block.
219   //
220   BasicBlock::InstListType &IL = Header->getInstList();
221   IL.push_front(PN);
222
223   // Insert the Add instruction as the first (non-phi) instruction in the 
224   // header node's basic block.
225   BasicBlock::iterator I = IL.begin();
226   while (isa<PHINode>(*I)) ++I;
227   IL.insert(I, AddNode);
228   return PN;
229 }
230
231 // ProcessInterval - This function is invoked once for each interval in the 
232 // IntervalPartition of the program.  It looks for auxilliary induction
233 // variables in loops.  If it finds one, it:
234 // * Cannonicalizes the induction variable.  This consists of:
235 //   A. Making the first element of the PHI node be the loop invariant 
236 //      computation, and the second element be the linear induction portion.
237 //   B. Changing the first element of the linear induction portion of the PHI 
238 //      node to be of the form ADD(PHI, <loop invariant expr>).
239 // * Add the induction variable PHI to a list of induction variables found.
240 //
241 // After this, a list of cannonical induction variables is known.  This list
242 // is searched to see if there is an induction variable that counts from 
243 // constant 0 with a step size of constant 1.  If there is not one, one is
244 // injected into the loop.  Thus a "simple" induction variable is always known
245 //
246 // One a simple induction variable is known, all other induction variables are
247 // modified to refer to the "simple" induction variable.
248 //
249 static bool ProcessInterval(cfg::Interval *Int) {
250   if (!Int->isLoop()) return false;  // Not a loop?  Ignore it!
251
252   std::vector<PHINode *> InductionVars;
253
254   BasicBlock *Header = Int->getHeaderNode();
255   // Loop over all of the PHI nodes in the interval header...
256   for (BasicBlock::iterator I = Header->begin(), E = Header->end(); 
257        I != E && isa<PHINode>(*I); ++I) {
258     PHINode *PN = cast<PHINode>(*I);
259     if (PN->getNumIncomingValues() != 2) { // These should be eliminated by now.
260       cerr << "Found interval header with more than 2 predecessors! Ignoring\n";
261       return false;    // Todo, make an assertion.
262     }
263
264     // For this to be an induction variable, one of the arguments must be a
265     // loop invariant expression, and the other must be an expression involving
266     // the PHI node, along with possible additions and subtractions of loop
267     // invariant values.
268     //
269     BasicBlock *BB1 = PN->getIncomingBlock(0);
270     Value      *V1  = PN->getIncomingValue(0);
271     BasicBlock *BB2 = PN->getIncomingBlock(1);
272     Value      *V2  = PN->getIncomingValue(1);
273
274     // Figure out which computation is loop invariant...
275     if (!isLoopInvariant(Int, V1)) {
276       // V1 is *not* loop invariant.  Check to see if V2 is:
277       if (isLoopInvariant(Int, V2)) {
278         // They *are* loop invariant.  Exchange BB1/BB2 and V1/V2 so that
279         // V1 is always the loop invariant computation.
280         std::swap(V1, V2); std::swap(BB1, BB2);
281       } else {
282         // Neither value is loop invariant.  Must not be an induction variable.
283         // This case can happen if there is an unreachable loop in the CFG that
284         // has two tail loops in it that was not split by the cleanup phase
285         // before.
286         continue;
287       }      
288     }
289
290     // At this point, we know that BB1/V1 are loop invariant.  We don't know
291     // anything about BB2/V2.  Check now to see if V2 is a linear induction
292     // variable.
293     //
294     cerr << "Found loop invariant computation: " << V1 << "\n";
295     
296     if (!isLinearInductionVariable(Int, V2, PN))
297       continue;         // No, it is not a linear ind var, ignore the PHI node.
298     cerr << "Found linear induction variable: " << V2;
299
300     // TODO: Cannonicalize V2
301
302     // Add this PHI node to the list of induction variables found...
303     InductionVars.push_back(PN);    
304   }
305
306   // No induction variables found?
307   if (InductionVars.empty()) return false;
308
309   // Search to see if there is already a "simple" induction variable.
310   std::vector<PHINode*>::iterator It = 
311     find_if(InductionVars.begin(), InductionVars.end(), isSimpleInductionVar);
312   
313   PHINode *PrimaryIndVar;
314
315   // A simple induction variable was not found, inject one now...
316   if (It == InductionVars.end()) {
317     PrimaryIndVar = InjectSimpleInductionVariable(Int);
318   } else {
319     // Move the PHI node for this induction variable to the start of the PHI
320     // list in HeaderNode... we do not need to do this for the inserted case
321     // because the inserted node will always be placed at the beginning of
322     // HeaderNode.
323     //
324     PrimaryIndVar = *It;
325     BasicBlock::iterator i =
326       find(Header->begin(), Header->end(), PrimaryIndVar);
327     assert(i != Header->end() && 
328            "How could Primary IndVar not be in the header!?!!?");
329
330     if (i != Header->begin())
331       std::iter_swap(i, Header->begin());
332   }
333
334   // Now we know that there is a simple induction variable PrimaryIndVar.
335   // Simplify all of the other induction variables to use this induction 
336   // variable as their counter, and destroy the PHI nodes that correspond to
337   // the old indvars.
338   //
339   // TODO
340
341
342   cerr << "Found Interval Header with indvars (primary indvar should be first "
343        << "phi): \n" << Header << "\nPrimaryIndVar: " << PrimaryIndVar;
344
345   return false;  // TODO: true;
346 }
347
348
349 // ProcessIntervalPartition - This function loops over the interval partition
350 // processing each interval with ProcessInterval
351 //
352 static bool ProcessIntervalPartition(cfg::IntervalPartition &IP) {
353   // This currently just prints out information about the interval structure
354   // of the method...
355 #if 0
356   static unsigned N = 0;
357   cerr << "\n***********Interval Partition #" << (++N) << "************\n\n";
358   copy(IP.begin(), IP.end(), ostream_iterator<cfg::Interval*>(cerr, "\n"));
359
360   cerr << "\n*********** PERFORMING WORK ************\n\n";
361 #endif
362   // Loop over all of the intervals in the partition and look for induction
363   // variables in intervals that represent loops.
364   //
365   return reduce_apply(IP.begin(), IP.end(), bitwise_or<bool>(), false,
366                       std::ptr_fun(ProcessInterval));
367 }
368
369 // DoInductionVariableCannonicalize - Simplify induction variables in loops.
370 // This function loops over an interval partition of a program, reducing it
371 // until the graph is gone.
372 //
373 bool InductionVariableCannonicalize::doIt(Method *M, 
374                                           cfg::IntervalPartition &IP) {
375   bool Changed = false;
376
377 #if 0
378   while (!IP->isDegeneratePartition()) {
379     Changed |= ProcessIntervalPartition(*IP);
380
381     // Calculate the reduced version of this graph until we get to an 
382     // irreducible graph or a degenerate graph...
383     //
384     cfg::IntervalPartition *NewIP = new cfg::IntervalPartition(*IP, false);
385     if (NewIP->size() == IP->size()) {
386       cerr << "IRREDUCIBLE GRAPH FOUND!!!\n";
387       return Changed;
388     }
389     delete IP;
390     IP = NewIP;
391   }
392
393   delete IP;
394 #endif
395   return Changed;
396 }
397
398
399 bool InductionVariableCannonicalize::runOnMethod(Method *M) {
400   return doIt(M, getAnalysis<cfg::IntervalPartition>());
401 }
402
403 // getAnalysisUsageInfo - This function works on the call graph of a module.
404 // It is capable of updating the call graph to reflect the new state of the
405 // module.
406 //
407 void InductionVariableCannonicalize::getAnalysisUsageInfo(
408                                            Pass::AnalysisSet &Required,
409                                            Pass::AnalysisSet &Destroyed,
410                                            Pass::AnalysisSet &Provided) {
411   Required.push_back(cfg::IntervalPartition::ID);
412 }