blob: 9f0513f36e8ad8871719e7575acc0b25abc5080d [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 Lattner7e02b7e2001-06-30 04:36:40 +000022#include "llvm/Optimizations/InductionVars.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 Lattnerd473a0a2001-06-25 07:32:19 +000026#include "llvm/SymbolTable.h"
Chris Lattner364b1472001-06-22 02:24:38 +000027#include "llvm/iOther.h"
Chris Lattnercee8f9a2001-11-27 00:03:19 +000028#include "Support/STLExtras.h"
Chris Lattnerc9f39b22001-06-24 04:05:45 +000029#include <algorithm>
Chris Lattnerd213f0f2001-06-20 19:27:11 +000030
Chris Lattner7e02b7e2001-06-30 04:36:40 +000031#include "llvm/Analysis/LoopDepth.h"
32
33using namespace opt;
34
Chris Lattner364b1472001-06-22 02:24:38 +000035// isLoopInvariant - Return true if the specified value/basic block source is
36// an interval invariant computation.
37//
38static bool isLoopInvariant(cfg::Interval *Int, Value *V) {
Chris Lattner1d87bcf2001-10-01 20:11:19 +000039 assert(isa<ConstPoolVal>(V) || isa<Instruction>(V) || isa<MethodArgument>(V));
Chris Lattnerd213f0f2001-06-20 19:27:11 +000040
Chris Lattner1d87bcf2001-10-01 20:11:19 +000041 if (!isa<Instruction>(V))
Chris Lattner364b1472001-06-22 02:24:38 +000042 return true; // Constants and arguments are always loop invariant
43
Chris Lattnerb00c5822001-10-02 03:41:24 +000044 BasicBlock *ValueBlock = cast<Instruction>(V)->getParent();
Chris Lattner364b1472001-06-22 02:24:38 +000045 assert(ValueBlock && "Instruction not embedded in basic block!");
46
47 // For now, only consider values from outside of the interval, regardless of
48 // whether the expression could be lifted out of the loop by some LICM.
49 //
50 // TODO: invoke LICM library if we find out it would be useful.
51 //
52 return !Int->contains(ValueBlock);
53}
54
55
56// isLinearInductionVariableH - Return isLIV if the expression V is a linear
57// expression defined in terms of loop invariant computations, and a single
58// instance of the PHI node PN. Return isLIC if the expression V is a loop
59// invariant computation. Return isNLIV if the expression is a negated linear
60// induction variable. Return isOther if it is neither.
61//
62// Currently allowed operators are: ADD, SUB, NEG
63// TODO: This should allow casts!
64//
65enum LIVType { isLIV, isLIC, isNLIV, isOther };
66//
67// neg - Negate the sign of a LIV expression.
68inline LIVType neg(LIVType T) {
69 assert(T == isLIV || T == isNLIV && "Negate Only works on LIV expressions");
70 return T == isLIV ? isNLIV : isLIV;
71}
72//
73static LIVType isLinearInductionVariableH(cfg::Interval *Int, Value *V,
74 PHINode *PN) {
75 if (V == PN) { return isLIV; } // PHI node references are (0+PHI)
76 if (isLoopInvariant(Int, V)) return isLIC;
77
Chris Lattner3b34c592001-06-27 23:36:09 +000078 // loop variant computations must be instructions!
Chris Lattner9636a912001-10-01 16:18:37 +000079 Instruction *I = cast<Instruction>(V);
Chris Lattnera41f50d2001-07-07 19:24:15 +000080 switch (I->getOpcode()) { // Handle each instruction seperately
Chris Lattner364b1472001-06-22 02:24:38 +000081 case Instruction::Add:
82 case Instruction::Sub: {
Chris Lattnerb00c5822001-10-02 03:41:24 +000083 Value *SubV1 = cast<BinaryOperator>(I)->getOperand(0);
84 Value *SubV2 = cast<BinaryOperator>(I)->getOperand(1);
Chris Lattner364b1472001-06-22 02:24:38 +000085 LIVType SubLIVType1 = isLinearInductionVariableH(Int, SubV1, PN);
86 if (SubLIVType1 == isOther) return isOther; // Early bailout
87 LIVType SubLIVType2 = isLinearInductionVariableH(Int, SubV2, PN);
88
89 switch (SubLIVType2) {
90 case isOther: return isOther; // Unknown subexpression type
91 case isLIC: return SubLIVType1; // Constant offset, return type #1
92 case isLIV:
93 case isNLIV:
94 // So now we know that we have a linear induction variable on the RHS of
95 // the ADD or SUB instruction. SubLIVType1 cannot be isOther, so it is
96 // either a Loop Invariant computation, or a LIV type.
97 if (SubLIVType1 == isLIC) {
98 // Loop invariant computation, we know this is a LIV then.
Chris Lattnera41f50d2001-07-07 19:24:15 +000099 return (I->getOpcode() == Instruction::Add) ?
Chris Lattner364b1472001-06-22 02:24:38 +0000100 SubLIVType2 : neg(SubLIVType2);
101 }
102
103 // If the LHS is also a LIV Expression, we cannot add two LIVs together
Chris Lattnera41f50d2001-07-07 19:24:15 +0000104 if (I->getOpcode() == Instruction::Add) return isOther;
Chris Lattner364b1472001-06-22 02:24:38 +0000105
106 // We can only subtract two LIVs if they are the same type, which yields
107 // a LIC, because the LIVs cancel each other out.
108 return (SubLIVType1 == SubLIVType2) ? isLIC : isOther;
109 }
110 // NOT REACHED
111 }
112
113 default: // Any other instruction is not a LINEAR induction var
114 return isOther;
115 }
116}
117
118// isLinearInductionVariable - Return true if the specified expression is a
119// "linear induction variable", which is an expression involving a single
120// instance of the PHI node and a loop invariant value that is added or
121// subtracted to the PHI node. This is calculated by walking the SSA graph
122//
123static inline bool isLinearInductionVariable(cfg::Interval *Int, Value *V,
124 PHINode *PN) {
125 return isLinearInductionVariableH(Int, V, PN) == isLIV;
126}
127
128
129// isSimpleInductionVar - Return true iff the cannonical induction variable PN
130// has an initializer of the constant value 0, and has a step size of constant
131// 1.
132static inline bool isSimpleInductionVar(PHINode *PN) {
133 assert(PN->getNumIncomingValues() == 2 && "Must have cannonical PHI node!");
134 Value *Initializer = PN->getIncomingValue(0);
Chris Lattner1d87bcf2001-10-01 20:11:19 +0000135 if (!isa<ConstPoolVal>(Initializer)) return false;
Chris Lattner364b1472001-06-22 02:24:38 +0000136
Chris Lattnerc9f39b22001-06-24 04:05:45 +0000137 if (Initializer->getType()->isSigned()) { // Signed constant value...
138 if (((ConstPoolSInt*)Initializer)->getValue() != 0) return false;
139 } else if (Initializer->getType()->isUnsigned()) { // Unsigned constant value
140 if (((ConstPoolUInt*)Initializer)->getValue() != 0) return false;
141 } else {
142 return false; // Not signed or unsigned? Must be FP type or something
143 }
144
Chris Lattnerd473a0a2001-06-25 07:32:19 +0000145 Value *StepExpr = PN->getIncomingValue(1);
Chris Lattner1d87bcf2001-10-01 20:11:19 +0000146 if (!isa<Instruction>(StepExpr) ||
Chris Lattnerb00c5822001-10-02 03:41:24 +0000147 cast<Instruction>(StepExpr)->getOpcode() != Instruction::Add)
Chris Lattner3b34c592001-06-27 23:36:09 +0000148 return false;
149
Chris Lattnerb00c5822001-10-02 03:41:24 +0000150 BinaryOperator *I = cast<BinaryOperator>(StepExpr);
151 assert(isa<PHINode>(I->getOperand(0)) &&
Chris Lattner364b1472001-06-22 02:24:38 +0000152 "PHI node should be first operand of ADD instruction!");
153
154 // Get the right hand side of the ADD node. See if it is a constant 1.
155 Value *StepSize = I->getOperand(1);
Chris Lattner1d87bcf2001-10-01 20:11:19 +0000156 if (!isa<ConstPoolVal>(StepSize)) return false;
Chris Lattner364b1472001-06-22 02:24:38 +0000157
Chris Lattnerc9f39b22001-06-24 04:05:45 +0000158 if (StepSize->getType()->isSigned()) { // Signed constant value...
159 if (((ConstPoolSInt*)StepSize)->getValue() != 1) return false;
160 } else if (StepSize->getType()->isUnsigned()) { // Unsigned constant value
161 if (((ConstPoolUInt*)StepSize)->getValue() != 1) return false;
162 } else {
163 return false; // Not signed or unsigned? Must be FP type or something
164 }
Chris Lattner364b1472001-06-22 02:24:38 +0000165
Chris Lattnerc9f39b22001-06-24 04:05:45 +0000166 // At this point, we know the initializer is a constant value 0 and the step
167 // size is a constant value 1. This is our simple induction variable!
168 return true;
Chris Lattnerda956802001-06-21 05:27:22 +0000169}
170
Chris Lattnerd473a0a2001-06-25 07:32:19 +0000171// InjectSimpleInductionVariable - Insert a cannonical induction variable into
172// the interval header Header. This assumes that the flow graph is in
173// simplified form (so we know that the header block has exactly 2 predecessors)
174//
175// TODO: This should inherit the largest type that is being used by the already
176// present induction variables (instead of always using uint)
177//
178static PHINode *InjectSimpleInductionVariable(cfg::Interval *Int) {
179 string PHIName, AddName;
180
181 BasicBlock *Header = Int->getHeaderNode();
182 Method *M = Header->getParent();
183
184 if (M->hasSymbolTable()) {
185 // Only name the induction variable if the method isn't stripped.
186 PHIName = M->getSymbolTable()->getUniqueName(Type::UIntTy, "ind_var");
187 AddName = M->getSymbolTable()->getUniqueName(Type::UIntTy, "ind_var_next");
188 }
189
190 // Create the neccesary instructions...
191 PHINode *PN = new PHINode(Type::UIntTy, PHIName);
Chris Lattner73657452001-09-07 16:42:26 +0000192 ConstPoolVal *One = ConstPoolUInt::get(Type::UIntTy, 1);
193 ConstPoolVal *Zero = ConstPoolUInt::get(Type::UIntTy, 0);
Chris Lattnerd473a0a2001-06-25 07:32:19 +0000194 BinaryOperator *AddNode = BinaryOperator::create(Instruction::Add,
195 PN, One, AddName);
196
197 // Figure out which predecessors I have to play with... there should be
198 // exactly two... one of which is a loop predecessor, and one of which is not.
199 //
Chris Lattnerf0604b82001-10-01 13:19:53 +0000200 BasicBlock::pred_iterator PI = Header->pred_begin();
201 assert(PI != Header->pred_end() && "Header node should have 2 preds!");
Chris Lattnerd473a0a2001-06-25 07:32:19 +0000202 BasicBlock *Pred1 = *PI; ++PI;
Chris Lattnerf0604b82001-10-01 13:19:53 +0000203 assert(PI != Header->pred_end() && "Header node should have 2 preds!");
Chris Lattnerd473a0a2001-06-25 07:32:19 +0000204 BasicBlock *Pred2 = *PI;
Chris Lattnerf0604b82001-10-01 13:19:53 +0000205 assert(++PI == Header->pred_end() && "Header node should have 2 preds!");
Chris Lattnerd473a0a2001-06-25 07:32:19 +0000206
207 // Make Pred1 be the loop entrance predecessor, Pred2 be the Loop predecessor
208 if (Int->contains(Pred1)) swap(Pred1, Pred2);
209
210 assert(!Int->contains(Pred1) && "Pred1 should be loop entrance!");
211 assert( Int->contains(Pred2) && "Pred2 should be looping edge!");
212
213 // Link the instructions into the PHI node...
214 PN->addIncoming(Zero, Pred1); // The initializer is first argument
215 PN->addIncoming(AddNode, Pred2); // The step size is second PHI argument
216
217 // Insert the PHI node into the Header of the loop. It shall be the first
218 // instruction, because the "Simple" Induction Variable must be first in the
219 // block.
220 //
221 BasicBlock::InstListType &IL = Header->getInstList();
222 IL.push_front(PN);
223
224 // Insert the Add instruction as the first (non-phi) instruction in the
225 // header node's basic block.
Chris Lattner3b34c592001-06-27 23:36:09 +0000226 BasicBlock::iterator I = IL.begin();
Chris Lattnerb00c5822001-10-02 03:41:24 +0000227 while (isa<PHINode>(*I)) ++I;
Chris Lattnerd473a0a2001-06-25 07:32:19 +0000228 IL.insert(I, AddNode);
Chris Lattnerd473a0a2001-06-25 07:32:19 +0000229 return PN;
230}
231
Chris Lattner364b1472001-06-22 02:24:38 +0000232// ProcessInterval - This function is invoked once for each interval in the
233// IntervalPartition of the program. It looks for auxilliary induction
234// variables in loops. If it finds one, it:
235// * Cannonicalizes the induction variable. This consists of:
236// A. Making the first element of the PHI node be the loop invariant
237// computation, and the second element be the linear induction portion.
238// B. Changing the first element of the linear induction portion of the PHI
239// node to be of the form ADD(PHI, <loop invariant expr>).
240// * Add the induction variable PHI to a list of induction variables found.
241//
242// After this, a list of cannonical induction variables is known. This list
243// is searched to see if there is an induction variable that counts from
244// constant 0 with a step size of constant 1. If there is not one, one is
245// injected into the loop. Thus a "simple" induction variable is always known
246//
247// One a simple induction variable is known, all other induction variables are
248// modified to refer to the "simple" induction variable.
249//
250static bool ProcessInterval(cfg::Interval *Int) {
251 if (!Int->isLoop()) return false; // Not a loop? Ignore it!
252
253 vector<PHINode *> InductionVars;
254
255 BasicBlock *Header = Int->getHeaderNode();
256 // Loop over all of the PHI nodes in the interval header...
Chris Lattner3b34c592001-06-27 23:36:09 +0000257 for (BasicBlock::iterator I = Header->begin(), E = Header->end();
Chris Lattnerb00c5822001-10-02 03:41:24 +0000258 I != E && isa<PHINode>(*I); ++I) {
259 PHINode *PN = cast<PHINode>(*I);
Chris Lattner364b1472001-06-22 02:24:38 +0000260 if (PN->getNumIncomingValues() != 2) { // These should be eliminated by now.
261 cerr << "Found interval header with more than 2 predecessors! Ignoring\n";
262 return false; // Todo, make an assertion.
263 }
264
265 // For this to be an induction variable, one of the arguments must be a
266 // loop invariant expression, and the other must be an expression involving
267 // the PHI node, along with possible additions and subtractions of loop
268 // invariant values.
269 //
270 BasicBlock *BB1 = PN->getIncomingBlock(0);
271 Value *V1 = PN->getIncomingValue(0);
272 BasicBlock *BB2 = PN->getIncomingBlock(1);
273 Value *V2 = PN->getIncomingValue(1);
274
275 // Figure out which computation is loop invariant...
276 if (!isLoopInvariant(Int, V1)) {
277 // V1 is *not* loop invariant. Check to see if V2 is:
278 if (isLoopInvariant(Int, V2)) {
279 // They *are* loop invariant. Exchange BB1/BB2 and V1/V2 so that
280 // V1 is always the loop invariant computation.
281 swap(V1, V2); swap(BB1, BB2);
282 } else {
283 // Neither value is loop invariant. Must not be an induction variable.
284 // This case can happen if there is an unreachable loop in the CFG that
285 // has two tail loops in it that was not split by the cleanup phase
286 // before.
287 continue;
288 }
289 }
290
291 // At this point, we know that BB1/V1 are loop invariant. We don't know
292 // anything about BB2/V2. Check now to see if V2 is a linear induction
293 // variable.
294 //
Chris Lattnerd473a0a2001-06-25 07:32:19 +0000295 cerr << "Found loop invariant computation: " << V1 << endl;
Chris Lattner364b1472001-06-22 02:24:38 +0000296
297 if (!isLinearInductionVariable(Int, V2, PN))
298 continue; // No, it is not a linear ind var, ignore the PHI node.
299 cerr << "Found linear induction variable: " << V2;
300
301 // TODO: Cannonicalize V2
302
303 // Add this PHI node to the list of induction variables found...
304 InductionVars.push_back(PN);
305 }
306
307 // No induction variables found?
308 if (InductionVars.empty()) return false;
309
Chris Lattner364b1472001-06-22 02:24:38 +0000310 // Search to see if there is already a "simple" induction variable.
311 vector<PHINode*>::iterator It =
312 find_if(InductionVars.begin(), InductionVars.end(), isSimpleInductionVar);
313
Chris Lattnerc9f39b22001-06-24 04:05:45 +0000314 PHINode *PrimaryIndVar;
315
Chris Lattner364b1472001-06-22 02:24:38 +0000316 // A simple induction variable was not found, inject one now...
317 if (It == InductionVars.end()) {
Chris Lattnerd473a0a2001-06-25 07:32:19 +0000318 PrimaryIndVar = InjectSimpleInductionVariable(Int);
Chris Lattnerc9f39b22001-06-24 04:05:45 +0000319 } else {
320 // Move the PHI node for this induction variable to the start of the PHI
321 // list in HeaderNode... we do not need to do this for the inserted case
322 // because the inserted node will always be placed at the beginning of
323 // HeaderNode.
324 //
325 PrimaryIndVar = *It;
Chris Lattner3b34c592001-06-27 23:36:09 +0000326 BasicBlock::iterator i =
327 find(Header->begin(), Header->end(), PrimaryIndVar);
328 assert(i != Header->end() &&
Chris Lattnerc9f39b22001-06-24 04:05:45 +0000329 "How could Primary IndVar not be in the header!?!!?");
330
Chris Lattner3b34c592001-06-27 23:36:09 +0000331 if (i != Header->begin())
332 iter_swap(i, Header->begin());
Chris Lattner364b1472001-06-22 02:24:38 +0000333 }
334
Chris Lattnerc9f39b22001-06-24 04:05:45 +0000335 // Now we know that there is a simple induction variable PrimaryIndVar.
336 // Simplify all of the other induction variables to use this induction
337 // variable as their counter, and destroy the PHI nodes that correspond to
338 // the old indvars.
Chris Lattner364b1472001-06-22 02:24:38 +0000339 //
340 // TODO
341
Chris Lattnerc9f39b22001-06-24 04:05:45 +0000342
343 cerr << "Found Interval Header with indvars (primary indvar should be first "
Chris Lattner3b34c592001-06-27 23:36:09 +0000344 << "phi): \n" << Header << "\nPrimaryIndVar: " << PrimaryIndVar;
Chris Lattnerc9f39b22001-06-24 04:05:45 +0000345
Chris Lattner364b1472001-06-22 02:24:38 +0000346 return false; // TODO: true;
347}
348
349
350// ProcessIntervalPartition - This function loops over the interval partition
351// processing each interval with ProcessInterval
352//
Chris Lattnerda956802001-06-21 05:27:22 +0000353static bool ProcessIntervalPartition(cfg::IntervalPartition &IP) {
354 // This currently just prints out information about the interval structure
355 // of the method...
Chris Lattnerd473a0a2001-06-25 07:32:19 +0000356#if 0
Chris Lattnerda956802001-06-21 05:27:22 +0000357 static unsigned N = 0;
358 cerr << "\n***********Interval Partition #" << (++N) << "************\n\n";
359 copy(IP.begin(), IP.end(), ostream_iterator<cfg::Interval*>(cerr, "\n"));
360
361 cerr << "\n*********** PERFORMING WORK ************\n\n";
Chris Lattnerd473a0a2001-06-25 07:32:19 +0000362#endif
Chris Lattnerda956802001-06-21 05:27:22 +0000363 // Loop over all of the intervals in the partition and look for induction
364 // variables in intervals that represent loops.
365 //
366 return reduce_apply(IP.begin(), IP.end(), bitwise_or<bool>(), false,
367 ptr_fun(ProcessInterval));
Chris Lattnerd213f0f2001-06-20 19:27:11 +0000368}
369
Chris Lattner364b1472001-06-22 02:24:38 +0000370// DoInductionVariableCannonicalize - Simplify induction variables in loops.
371// This function loops over an interval partition of a program, reducing it
372// until the graph is gone.
Chris Lattnerd213f0f2001-06-20 19:27:11 +0000373//
Chris Lattner42c9c2c2001-10-18 05:27:33 +0000374bool opt::InductionVariableCannonicalize::doIt(Method *M) {
Chris Lattnerd473a0a2001-06-25 07:32:19 +0000375 // TODO: REMOVE
376 if (0) { // Print basic blocks with their depth
Chris Lattner53b1c012001-06-25 03:55:37 +0000377 LoopDepthCalculator LDC(M);
Chris Lattner3b34c592001-06-27 23:36:09 +0000378 for (Method::iterator I = M->begin(); I != M->end(); ++I) {
Chris Lattner53b1c012001-06-25 03:55:37 +0000379 cerr << "Basic Block Depth: " << LDC.getLoopDepth(*I) << *I;
380 }
Chris Lattner53b1c012001-06-25 03:55:37 +0000381 }
382
383
Chris Lattnerda956802001-06-21 05:27:22 +0000384 cfg::IntervalPartition *IP = new cfg::IntervalPartition(M);
385 bool Changed = false;
Chris Lattnerd213f0f2001-06-20 19:27:11 +0000386
Chris Lattnerda956802001-06-21 05:27:22 +0000387 while (!IP->isDegeneratePartition()) {
388 Changed |= ProcessIntervalPartition(*IP);
Chris Lattner56832052001-06-20 22:44:38 +0000389
Chris Lattnerda956802001-06-21 05:27:22 +0000390 // Calculate the reduced version of this graph until we get to an
391 // irreducible graph or a degenerate graph...
392 //
393 cfg::IntervalPartition *NewIP = new cfg::IntervalPartition(*IP, false);
394 if (NewIP->size() == IP->size()) {
395 cerr << "IRREDUCIBLE GRAPH FOUND!!!\n";
396 return Changed;
397 }
398 delete IP;
399 IP = NewIP;
400 }
Chris Lattner56832052001-06-20 22:44:38 +0000401
Chris Lattnerda956802001-06-21 05:27:22 +0000402 delete IP;
403 return Changed;
Chris Lattnerd213f0f2001-06-20 19:27:11 +0000404}