blob: 28ab29fd49c4742c7656f67af98f29c00320e72b [file] [log] [blame]
Chris Lattnerd213f0f2001-06-20 19:27:11 +00001//===- 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:
Chris Lattner364b1472001-06-22 02:24:38 +00006// - There is a single induction variable for each loop (at least loops that
7// used to contain at least one induction variable)
Chris Lattner3b34c592001-06-27 23:36:09 +00008// * 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
Chris Lattner364b1472001-06-22 02:24:38 +000010// Header block, allowing it to be found easily.
Chris Lattnerd213f0f2001-06-20 19:27:11 +000011// - All other preexisting induction variables are adjusted to operate in
12// terms of this primary induction variable
Chris Lattnerd473a0a2001-06-25 07:32:19 +000013// - Induction variables with a step size of 0 have been eliminated.
Chris Lattnerd213f0f2001-06-20 19:27:11 +000014//
Chris Lattner364b1472001-06-22 02:24:38 +000015// 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//
Chris Lattnerd213f0f2001-06-20 19:27:11 +000020//===----------------------------------------------------------------------===//
21
Chris Lattnerd473a0a2001-06-25 07:32:19 +000022#include "llvm/Opt/AllOpts.h"
Chris Lattnerc9f39b22001-06-24 04:05:45 +000023#include "llvm/ConstPoolVals.h"
24#include "llvm/Analysis/IntervalPartition.h"
Chris Lattnerd213f0f2001-06-20 19:27:11 +000025#include "llvm/Assembly/Writer.h"
Chris Lattnerda956802001-06-21 05:27:22 +000026#include "llvm/Tools/STLExtras.h"
Chris Lattnerd473a0a2001-06-25 07:32:19 +000027#include "llvm/SymbolTable.h"
Chris Lattner364b1472001-06-22 02:24:38 +000028#include "llvm/iOther.h"
Chris Lattnerd473a0a2001-06-25 07:32:19 +000029#include "llvm/CFG.h"
Chris Lattnerc9f39b22001-06-24 04:05:45 +000030#include <algorithm>
Chris Lattnerd213f0f2001-06-20 19:27:11 +000031
Chris Lattner364b1472001-06-22 02:24:38 +000032// isLoopInvariant - Return true if the specified value/basic block source is
33// an interval invariant computation.
34//
35static bool isLoopInvariant(cfg::Interval *Int, Value *V) {
Chris Lattner3b34c592001-06-27 23:36:09 +000036 assert(V->isConstant() || V->isInstruction() || V->isMethodArgument());
Chris Lattnerd213f0f2001-06-20 19:27:11 +000037
Chris Lattner3b34c592001-06-27 23:36:09 +000038 if (!V->isInstruction())
Chris Lattner364b1472001-06-22 02:24:38 +000039 return true; // Constants and arguments are always loop invariant
40
41 BasicBlock *ValueBlock = ((Instruction*)V)->getParent();
42 assert(ValueBlock && "Instruction not embedded in basic block!");
43
44 // For now, only consider values from outside of the interval, regardless of
45 // whether the expression could be lifted out of the loop by some LICM.
46 //
47 // TODO: invoke LICM library if we find out it would be useful.
48 //
49 return !Int->contains(ValueBlock);
50}
51
52
53// isLinearInductionVariableH - Return isLIV if the expression V is a linear
54// expression defined in terms of loop invariant computations, and a single
55// instance of the PHI node PN. Return isLIC if the expression V is a loop
56// invariant computation. Return isNLIV if the expression is a negated linear
57// induction variable. Return isOther if it is neither.
58//
59// Currently allowed operators are: ADD, SUB, NEG
60// TODO: This should allow casts!
61//
62enum LIVType { isLIV, isLIC, isNLIV, isOther };
63//
64// neg - Negate the sign of a LIV expression.
65inline LIVType neg(LIVType T) {
66 assert(T == isLIV || T == isNLIV && "Negate Only works on LIV expressions");
67 return T == isLIV ? isNLIV : isLIV;
68}
69//
70static LIVType isLinearInductionVariableH(cfg::Interval *Int, Value *V,
71 PHINode *PN) {
72 if (V == PN) { return isLIV; } // PHI node references are (0+PHI)
73 if (isLoopInvariant(Int, V)) return isLIC;
74
Chris Lattner3b34c592001-06-27 23:36:09 +000075 // loop variant computations must be instructions!
76 Instruction *I = V->castInstructionAsserting();
Chris Lattner364b1472001-06-22 02:24:38 +000077 switch (I->getInstType()) { // Handle each instruction seperately
78 case Instruction::Neg: {
79 Value *SubV = ((UnaryOperator*)I)->getOperand(0);
80 LIVType SubLIVType = isLinearInductionVariableH(Int, SubV, PN);
81 switch (SubLIVType) {
82 case isLIC: // Loop invariant & other computations remain the same
83 case isOther: return SubLIVType;
84 case isLIV: // Return the opposite signed LIV type
85 case isNLIV: return neg(isLIV);
86 }
87 }
88 case Instruction::Add:
89 case Instruction::Sub: {
90 Value *SubV1 = ((BinaryOperator*)I)->getOperand(0);
91 Value *SubV2 = ((BinaryOperator*)I)->getOperand(1);
92 LIVType SubLIVType1 = isLinearInductionVariableH(Int, SubV1, PN);
93 if (SubLIVType1 == isOther) return isOther; // Early bailout
94 LIVType SubLIVType2 = isLinearInductionVariableH(Int, SubV2, PN);
95
96 switch (SubLIVType2) {
97 case isOther: return isOther; // Unknown subexpression type
98 case isLIC: return SubLIVType1; // Constant offset, return type #1
99 case isLIV:
100 case isNLIV:
101 // So now we know that we have a linear induction variable on the RHS of
102 // the ADD or SUB instruction. SubLIVType1 cannot be isOther, so it is
103 // either a Loop Invariant computation, or a LIV type.
104 if (SubLIVType1 == isLIC) {
105 // Loop invariant computation, we know this is a LIV then.
106 return (I->getInstType() == Instruction::Add) ?
107 SubLIVType2 : neg(SubLIVType2);
108 }
109
110 // If the LHS is also a LIV Expression, we cannot add two LIVs together
111 if (I->getInstType() == Instruction::Add) return isOther;
112
113 // We can only subtract two LIVs if they are the same type, which yields
114 // a LIC, because the LIVs cancel each other out.
115 return (SubLIVType1 == SubLIVType2) ? isLIC : isOther;
116 }
117 // NOT REACHED
118 }
119
120 default: // Any other instruction is not a LINEAR induction var
121 return isOther;
122 }
123}
124
125// isLinearInductionVariable - Return true if the specified expression is a
126// "linear induction variable", which is an expression involving a single
127// instance of the PHI node and a loop invariant value that is added or
128// subtracted to the PHI node. This is calculated by walking the SSA graph
129//
130static inline bool isLinearInductionVariable(cfg::Interval *Int, Value *V,
131 PHINode *PN) {
132 return isLinearInductionVariableH(Int, V, PN) == isLIV;
133}
134
135
136// isSimpleInductionVar - Return true iff the cannonical induction variable PN
137// has an initializer of the constant value 0, and has a step size of constant
138// 1.
139static inline bool isSimpleInductionVar(PHINode *PN) {
140 assert(PN->getNumIncomingValues() == 2 && "Must have cannonical PHI node!");
141 Value *Initializer = PN->getIncomingValue(0);
Chris Lattner3b34c592001-06-27 23:36:09 +0000142 if (!Initializer->isConstant()) return false;
Chris Lattner364b1472001-06-22 02:24:38 +0000143
Chris Lattnerc9f39b22001-06-24 04:05:45 +0000144 if (Initializer->getType()->isSigned()) { // Signed constant value...
145 if (((ConstPoolSInt*)Initializer)->getValue() != 0) return false;
146 } else if (Initializer->getType()->isUnsigned()) { // Unsigned constant value
147 if (((ConstPoolUInt*)Initializer)->getValue() != 0) return false;
148 } else {
149 return false; // Not signed or unsigned? Must be FP type or something
150 }
151
Chris Lattnerd473a0a2001-06-25 07:32:19 +0000152 Value *StepExpr = PN->getIncomingValue(1);
Chris Lattner3b34c592001-06-27 23:36:09 +0000153 if (!StepExpr->isInstruction() ||
154 ((Instruction*)StepExpr)->getInstType() != Instruction::Add)
155 return false;
156
Chris Lattner364b1472001-06-22 02:24:38 +0000157 BinaryOperator *I = (BinaryOperator*)StepExpr;
Chris Lattner3b34c592001-06-27 23:36:09 +0000158 assert(I->getOperand(0)->isInstruction() &&
159 ((Instruction*)I->getOperand(0))->isPHINode() &&
Chris Lattner364b1472001-06-22 02:24:38 +0000160 "PHI node should be first operand of ADD instruction!");
161
162 // Get the right hand side of the ADD node. See if it is a constant 1.
163 Value *StepSize = I->getOperand(1);
Chris Lattner3b34c592001-06-27 23:36:09 +0000164 if (!StepSize->isConstant()) return false;
Chris Lattner364b1472001-06-22 02:24:38 +0000165
Chris Lattnerc9f39b22001-06-24 04:05:45 +0000166 if (StepSize->getType()->isSigned()) { // Signed constant value...
167 if (((ConstPoolSInt*)StepSize)->getValue() != 1) return false;
168 } else if (StepSize->getType()->isUnsigned()) { // Unsigned constant value
169 if (((ConstPoolUInt*)StepSize)->getValue() != 1) return false;
170 } else {
171 return false; // Not signed or unsigned? Must be FP type or something
172 }
Chris Lattner364b1472001-06-22 02:24:38 +0000173
Chris Lattnerc9f39b22001-06-24 04:05:45 +0000174 // At this point, we know the initializer is a constant value 0 and the step
175 // size is a constant value 1. This is our simple induction variable!
176 return true;
Chris Lattnerda956802001-06-21 05:27:22 +0000177}
178
Chris Lattnerd473a0a2001-06-25 07:32:19 +0000179// InjectSimpleInductionVariable - Insert a cannonical induction variable into
180// the interval header Header. This assumes that the flow graph is in
181// simplified form (so we know that the header block has exactly 2 predecessors)
182//
183// TODO: This should inherit the largest type that is being used by the already
184// present induction variables (instead of always using uint)
185//
186static PHINode *InjectSimpleInductionVariable(cfg::Interval *Int) {
187 string PHIName, AddName;
188
189 BasicBlock *Header = Int->getHeaderNode();
190 Method *M = Header->getParent();
191
192 if (M->hasSymbolTable()) {
193 // Only name the induction variable if the method isn't stripped.
194 PHIName = M->getSymbolTable()->getUniqueName(Type::UIntTy, "ind_var");
195 AddName = M->getSymbolTable()->getUniqueName(Type::UIntTy, "ind_var_next");
196 }
197
198 // Create the neccesary instructions...
199 PHINode *PN = new PHINode(Type::UIntTy, PHIName);
200 ConstPoolVal *One = new ConstPoolUInt(Type::UIntTy, 1);
201 ConstPoolVal *Zero = new ConstPoolUInt(Type::UIntTy, 0);
202 BinaryOperator *AddNode = BinaryOperator::create(Instruction::Add,
203 PN, One, AddName);
204
205 // Figure out which predecessors I have to play with... there should be
206 // exactly two... one of which is a loop predecessor, and one of which is not.
207 //
208 cfg::pred_iterator PI = cfg::pred_begin(Header);
209 assert(PI != cfg::pred_end(Header) && "Header node should have 2 preds!");
210 BasicBlock *Pred1 = *PI; ++PI;
211 assert(PI != cfg::pred_end(Header) && "Header node should have 2 preds!");
212 BasicBlock *Pred2 = *PI;
213 assert(++PI == cfg::pred_end(Header) && "Header node should have 2 preds!");
214
215 // Make Pred1 be the loop entrance predecessor, Pred2 be the Loop predecessor
216 if (Int->contains(Pred1)) swap(Pred1, Pred2);
217
218 assert(!Int->contains(Pred1) && "Pred1 should be loop entrance!");
219 assert( Int->contains(Pred2) && "Pred2 should be looping edge!");
220
221 // Link the instructions into the PHI node...
222 PN->addIncoming(Zero, Pred1); // The initializer is first argument
223 PN->addIncoming(AddNode, Pred2); // The step size is second PHI argument
224
225 // Insert the PHI node into the Header of the loop. It shall be the first
226 // instruction, because the "Simple" Induction Variable must be first in the
227 // block.
228 //
229 BasicBlock::InstListType &IL = Header->getInstList();
230 IL.push_front(PN);
231
232 // Insert the Add instruction as the first (non-phi) instruction in the
233 // header node's basic block.
Chris Lattner3b34c592001-06-27 23:36:09 +0000234 BasicBlock::iterator I = IL.begin();
Chris Lattnerd473a0a2001-06-25 07:32:19 +0000235 while ((*I)->isPHINode()) ++I;
236 IL.insert(I, AddNode);
237
238 // Insert the constants into the constant pool for the method...
239 M->getConstantPool().insert(One);
240 M->getConstantPool().insert(Zero);
241 return PN;
242}
243
Chris Lattner364b1472001-06-22 02:24:38 +0000244// ProcessInterval - This function is invoked once for each interval in the
245// IntervalPartition of the program. It looks for auxilliary induction
246// variables in loops. If it finds one, it:
247// * Cannonicalizes the induction variable. This consists of:
248// A. Making the first element of the PHI node be the loop invariant
249// computation, and the second element be the linear induction portion.
250// B. Changing the first element of the linear induction portion of the PHI
251// node to be of the form ADD(PHI, <loop invariant expr>).
252// * Add the induction variable PHI to a list of induction variables found.
253//
254// After this, a list of cannonical induction variables is known. This list
255// is searched to see if there is an induction variable that counts from
256// constant 0 with a step size of constant 1. If there is not one, one is
257// injected into the loop. Thus a "simple" induction variable is always known
258//
259// One a simple induction variable is known, all other induction variables are
260// modified to refer to the "simple" induction variable.
261//
262static bool ProcessInterval(cfg::Interval *Int) {
263 if (!Int->isLoop()) return false; // Not a loop? Ignore it!
264
265 vector<PHINode *> InductionVars;
266
267 BasicBlock *Header = Int->getHeaderNode();
268 // Loop over all of the PHI nodes in the interval header...
Chris Lattner3b34c592001-06-27 23:36:09 +0000269 for (BasicBlock::iterator I = Header->begin(), E = Header->end();
270 I != E && (*I)->isPHINode(); ++I) {
Chris Lattner364b1472001-06-22 02:24:38 +0000271 PHINode *PN = (PHINode*)*I;
272 if (PN->getNumIncomingValues() != 2) { // These should be eliminated by now.
273 cerr << "Found interval header with more than 2 predecessors! Ignoring\n";
274 return false; // Todo, make an assertion.
275 }
276
277 // For this to be an induction variable, one of the arguments must be a
278 // loop invariant expression, and the other must be an expression involving
279 // the PHI node, along with possible additions and subtractions of loop
280 // invariant values.
281 //
282 BasicBlock *BB1 = PN->getIncomingBlock(0);
283 Value *V1 = PN->getIncomingValue(0);
284 BasicBlock *BB2 = PN->getIncomingBlock(1);
285 Value *V2 = PN->getIncomingValue(1);
286
287 // Figure out which computation is loop invariant...
288 if (!isLoopInvariant(Int, V1)) {
289 // V1 is *not* loop invariant. Check to see if V2 is:
290 if (isLoopInvariant(Int, V2)) {
291 // They *are* loop invariant. Exchange BB1/BB2 and V1/V2 so that
292 // V1 is always the loop invariant computation.
293 swap(V1, V2); swap(BB1, BB2);
294 } else {
295 // Neither value is loop invariant. Must not be an induction variable.
296 // This case can happen if there is an unreachable loop in the CFG that
297 // has two tail loops in it that was not split by the cleanup phase
298 // before.
299 continue;
300 }
301 }
302
303 // At this point, we know that BB1/V1 are loop invariant. We don't know
304 // anything about BB2/V2. Check now to see if V2 is a linear induction
305 // variable.
306 //
Chris Lattnerd473a0a2001-06-25 07:32:19 +0000307 cerr << "Found loop invariant computation: " << V1 << endl;
Chris Lattner364b1472001-06-22 02:24:38 +0000308
309 if (!isLinearInductionVariable(Int, V2, PN))
310 continue; // No, it is not a linear ind var, ignore the PHI node.
311 cerr << "Found linear induction variable: " << V2;
312
313 // TODO: Cannonicalize V2
314
315 // Add this PHI node to the list of induction variables found...
316 InductionVars.push_back(PN);
317 }
318
319 // No induction variables found?
320 if (InductionVars.empty()) return false;
321
Chris Lattner364b1472001-06-22 02:24:38 +0000322 // Search to see if there is already a "simple" induction variable.
323 vector<PHINode*>::iterator It =
324 find_if(InductionVars.begin(), InductionVars.end(), isSimpleInductionVar);
325
Chris Lattnerc9f39b22001-06-24 04:05:45 +0000326 PHINode *PrimaryIndVar;
327
Chris Lattner364b1472001-06-22 02:24:38 +0000328 // A simple induction variable was not found, inject one now...
329 if (It == InductionVars.end()) {
Chris Lattnerd473a0a2001-06-25 07:32:19 +0000330 PrimaryIndVar = InjectSimpleInductionVariable(Int);
Chris Lattnerc9f39b22001-06-24 04:05:45 +0000331 } else {
332 // Move the PHI node for this induction variable to the start of the PHI
333 // list in HeaderNode... we do not need to do this for the inserted case
334 // because the inserted node will always be placed at the beginning of
335 // HeaderNode.
336 //
337 PrimaryIndVar = *It;
Chris Lattner3b34c592001-06-27 23:36:09 +0000338 BasicBlock::iterator i =
339 find(Header->begin(), Header->end(), PrimaryIndVar);
340 assert(i != Header->end() &&
Chris Lattnerc9f39b22001-06-24 04:05:45 +0000341 "How could Primary IndVar not be in the header!?!!?");
342
Chris Lattner3b34c592001-06-27 23:36:09 +0000343 if (i != Header->begin())
344 iter_swap(i, Header->begin());
Chris Lattner364b1472001-06-22 02:24:38 +0000345 }
346
Chris Lattnerc9f39b22001-06-24 04:05:45 +0000347 // Now we know that there is a simple induction variable PrimaryIndVar.
348 // Simplify all of the other induction variables to use this induction
349 // variable as their counter, and destroy the PHI nodes that correspond to
350 // the old indvars.
Chris Lattner364b1472001-06-22 02:24:38 +0000351 //
352 // TODO
353
Chris Lattnerc9f39b22001-06-24 04:05:45 +0000354
355 cerr << "Found Interval Header with indvars (primary indvar should be first "
Chris Lattner3b34c592001-06-27 23:36:09 +0000356 << "phi): \n" << Header << "\nPrimaryIndVar: " << PrimaryIndVar;
Chris Lattnerc9f39b22001-06-24 04:05:45 +0000357
Chris Lattner364b1472001-06-22 02:24:38 +0000358 return false; // TODO: true;
359}
360
361
362// ProcessIntervalPartition - This function loops over the interval partition
363// processing each interval with ProcessInterval
364//
Chris Lattnerda956802001-06-21 05:27:22 +0000365static bool ProcessIntervalPartition(cfg::IntervalPartition &IP) {
366 // This currently just prints out information about the interval structure
367 // of the method...
Chris Lattnerd473a0a2001-06-25 07:32:19 +0000368#if 0
Chris Lattnerda956802001-06-21 05:27:22 +0000369 static unsigned N = 0;
370 cerr << "\n***********Interval Partition #" << (++N) << "************\n\n";
371 copy(IP.begin(), IP.end(), ostream_iterator<cfg::Interval*>(cerr, "\n"));
372
373 cerr << "\n*********** PERFORMING WORK ************\n\n";
Chris Lattnerd473a0a2001-06-25 07:32:19 +0000374#endif
Chris Lattnerda956802001-06-21 05:27:22 +0000375 // Loop over all of the intervals in the partition and look for induction
376 // variables in intervals that represent loops.
377 //
378 return reduce_apply(IP.begin(), IP.end(), bitwise_or<bool>(), false,
379 ptr_fun(ProcessInterval));
Chris Lattnerd213f0f2001-06-20 19:27:11 +0000380}
381
Chris Lattner53b1c012001-06-25 03:55:37 +0000382#include "llvm/Analysis/LoopDepth.h"
Chris Lattner364b1472001-06-22 02:24:38 +0000383
384// DoInductionVariableCannonicalize - Simplify induction variables in loops.
385// This function loops over an interval partition of a program, reducing it
386// until the graph is gone.
Chris Lattnerd213f0f2001-06-20 19:27:11 +0000387//
388bool DoInductionVariableCannonicalize(Method *M) {
Chris Lattnerd473a0a2001-06-25 07:32:19 +0000389 // TODO: REMOVE
390 if (0) { // Print basic blocks with their depth
Chris Lattner53b1c012001-06-25 03:55:37 +0000391 LoopDepthCalculator LDC(M);
Chris Lattner3b34c592001-06-27 23:36:09 +0000392 for (Method::iterator I = M->begin(); I != M->end(); ++I) {
Chris Lattner53b1c012001-06-25 03:55:37 +0000393 cerr << "Basic Block Depth: " << LDC.getLoopDepth(*I) << *I;
394 }
Chris Lattner53b1c012001-06-25 03:55:37 +0000395 }
396
397
Chris Lattnerda956802001-06-21 05:27:22 +0000398 cfg::IntervalPartition *IP = new cfg::IntervalPartition(M);
399 bool Changed = false;
Chris Lattnerd213f0f2001-06-20 19:27:11 +0000400
Chris Lattnerda956802001-06-21 05:27:22 +0000401 while (!IP->isDegeneratePartition()) {
402 Changed |= ProcessIntervalPartition(*IP);
Chris Lattner56832052001-06-20 22:44:38 +0000403
Chris Lattnerda956802001-06-21 05:27:22 +0000404 // Calculate the reduced version of this graph until we get to an
405 // irreducible graph or a degenerate graph...
406 //
407 cfg::IntervalPartition *NewIP = new cfg::IntervalPartition(*IP, false);
408 if (NewIP->size() == IP->size()) {
409 cerr << "IRREDUCIBLE GRAPH FOUND!!!\n";
410 return Changed;
411 }
412 delete IP;
413 IP = NewIP;
414 }
Chris Lattner56832052001-06-20 22:44:38 +0000415
Chris Lattnerda956802001-06-21 05:27:22 +0000416 delete IP;
417 return Changed;
Chris Lattnerd213f0f2001-06-20 19:27:11 +0000418}