blob: 6a2bc714bbebf466b28fe23207211fa48b4dd16a [file] [log] [blame]
Chris Lattner53e677a2004-04-02 20:23:17 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
17// can handle. These classes are reference counted, managed by the SCEVHandle
18// class. We only create one SCEV of a particular shape, so pointer-comparisons
19// for equality are legal.
20//
21// One important aspect of the SCEV objects is that they are never cyclic, even
22// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23// the PHI node is one of the idioms that we can represent (e.g., a polynomial
24// recurrence) then we represent it directly as a recurrence node, otherwise we
25// represent it as a SCEVUnknown node.
26//
27// In addition to being able to represent expressions of various types, we also
28// have folders that are used to build the *canonical* representation for a
29// particular expression. These folders are capable of using a variety of
30// rewrite rules to simplify the expressions.
31//
32// Once the folders are defined, we can implement the more interesting
33// higher-level code, such as the code that recognizes PHI nodes of various
34// types, computes the execution count of a loop, etc.
35//
Chris Lattner53e677a2004-04-02 20:23:17 +000036// TODO: We should use these routines and value representations to implement
37// dependence analysis!
38//
39//===----------------------------------------------------------------------===//
40//
41// There are several good references for the techniques used in this analysis.
42//
43// Chains of recurrences -- a method to expedite the evaluation
44// of closed-form functions
45// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46//
47// On computational properties of chains of recurrences
48// Eugene V. Zima
49//
50// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51// Robert A. van Engelen
52//
53// Efficient Symbolic Analysis for Optimizing Compilers
54// Robert A. van Engelen
55//
56// Using the chains of recurrences algebra for data dependence testing and
57// induction variable substitution
58// MS Thesis, Johnie Birch
59//
60//===----------------------------------------------------------------------===//
61
Chris Lattner0a7f98c2004-04-15 15:07:24 +000062#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000063#include "llvm/Constants.h"
64#include "llvm/DerivedTypes.h"
65#include "llvm/Instructions.h"
66#include "llvm/Type.h"
67#include "llvm/Value.h"
68#include "llvm/Analysis/LoopInfo.h"
69#include "llvm/Assembly/Writer.h"
70#include "llvm/Transforms/Scalar.h"
Chris Lattner7980fb92004-04-17 18:36:24 +000071#include "llvm/Transforms/Utils/Local.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000072#include "llvm/Support/CFG.h"
73#include "llvm/Support/ConstantRange.h"
74#include "llvm/Support/InstIterator.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000075#include "llvm/Support/CommandLine.h"
76#include "llvm/ADT/Statistic.h"
Brian Gaekec5985172004-04-16 15:57:32 +000077#include <cmath>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000078#include <algorithm>
Chris Lattner53e677a2004-04-02 20:23:17 +000079using namespace llvm;
80
81namespace {
82 RegisterAnalysis<ScalarEvolution>
Chris Lattner45a1cf82004-04-19 03:42:32 +000083 R("scalar-evolution", "Scalar Evolution Analysis");
Chris Lattner53e677a2004-04-02 20:23:17 +000084
85 Statistic<>
86 NumBruteForceEvaluations("scalar-evolution",
87 "Number of brute force evaluations needed to calculate high-order polynomial exit values");
88 Statistic<>
89 NumTripCountsComputed("scalar-evolution",
90 "Number of loops with predictable loop counts");
91 Statistic<>
92 NumTripCountsNotComputed("scalar-evolution",
93 "Number of loops without predictable loop counts");
Chris Lattner7980fb92004-04-17 18:36:24 +000094 Statistic<>
95 NumBruteForceTripCountsComputed("scalar-evolution",
96 "Number of loops with trip counts computed by force");
97
98 cl::opt<unsigned>
99 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
100 cl::desc("Maximum number of iterations SCEV will symbolically execute a constant derived loop"),
101 cl::init(100));
Chris Lattner53e677a2004-04-02 20:23:17 +0000102}
103
104//===----------------------------------------------------------------------===//
105// SCEV class definitions
106//===----------------------------------------------------------------------===//
107
108//===----------------------------------------------------------------------===//
109// Implementation of the SCEV class.
110//
Chris Lattner53e677a2004-04-02 20:23:17 +0000111SCEV::~SCEV() {}
112void SCEV::dump() const {
113 print(std::cerr);
114}
115
116/// getValueRange - Return the tightest constant bounds that this value is
117/// known to have. This method is only valid on integer SCEV objects.
118ConstantRange SCEV::getValueRange() const {
119 const Type *Ty = getType();
120 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
121 Ty = Ty->getUnsignedVersion();
122 // Default to a full range if no better information is available.
123 return ConstantRange(getType());
124}
125
126
127SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
128
129bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
130 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000131 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000132}
133
134const Type *SCEVCouldNotCompute::getType() const {
135 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000136 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000137}
138
139bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
140 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
141 return false;
142}
143
Chris Lattner53e677a2004-04-02 20:23:17 +0000144void SCEVCouldNotCompute::print(std::ostream &OS) const {
145 OS << "***COULDNOTCOMPUTE***";
146}
147
148bool SCEVCouldNotCompute::classof(const SCEV *S) {
149 return S->getSCEVType() == scCouldNotCompute;
150}
151
152
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000153// SCEVConstants - Only allow the creation of one SCEVConstant for any
154// particular value. Don't use a SCEVHandle here, or else the object will
155// never be deleted!
156static std::map<ConstantInt*, SCEVConstant*> SCEVConstants;
157
Chris Lattner53e677a2004-04-02 20:23:17 +0000158
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000159SCEVConstant::~SCEVConstant() {
160 SCEVConstants.erase(V);
161}
Chris Lattner53e677a2004-04-02 20:23:17 +0000162
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000163SCEVHandle SCEVConstant::get(ConstantInt *V) {
164 // Make sure that SCEVConstant instances are all unsigned.
165 if (V->getType()->isSigned()) {
166 const Type *NewTy = V->getType()->getUnsignedVersion();
167 V = cast<ConstantUInt>(ConstantExpr::getCast(V, NewTy));
168 }
169
170 SCEVConstant *&R = SCEVConstants[V];
171 if (R == 0) R = new SCEVConstant(V);
172 return R;
173}
Chris Lattner53e677a2004-04-02 20:23:17 +0000174
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000175ConstantRange SCEVConstant::getValueRange() const {
176 return ConstantRange(V);
177}
Chris Lattner53e677a2004-04-02 20:23:17 +0000178
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000179const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000180
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000181void SCEVConstant::print(std::ostream &OS) const {
182 WriteAsOperand(OS, V, false);
183}
Chris Lattner53e677a2004-04-02 20:23:17 +0000184
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000185// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
186// particular input. Don't use a SCEVHandle here, or else the object will
187// never be deleted!
188static std::map<std::pair<SCEV*, const Type*>, SCEVTruncateExpr*> SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000189
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000190SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
191 : SCEV(scTruncate), Op(op), Ty(ty) {
192 assert(Op->getType()->isInteger() && Ty->isInteger() &&
193 Ty->isUnsigned() &&
194 "Cannot truncate non-integer value!");
195 assert(Op->getType()->getPrimitiveSize() > Ty->getPrimitiveSize() &&
196 "This is not a truncating conversion!");
197}
Chris Lattner53e677a2004-04-02 20:23:17 +0000198
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000199SCEVTruncateExpr::~SCEVTruncateExpr() {
200 SCEVTruncates.erase(std::make_pair(Op, Ty));
201}
Chris Lattner53e677a2004-04-02 20:23:17 +0000202
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000203ConstantRange SCEVTruncateExpr::getValueRange() const {
204 return getOperand()->getValueRange().truncate(getType());
205}
Chris Lattner53e677a2004-04-02 20:23:17 +0000206
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000207void SCEVTruncateExpr::print(std::ostream &OS) const {
208 OS << "(truncate " << *Op << " to " << *Ty << ")";
209}
210
211// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
212// particular input. Don't use a SCEVHandle here, or else the object will never
213// be deleted!
214static std::map<std::pair<SCEV*, const Type*>,
215 SCEVZeroExtendExpr*> SCEVZeroExtends;
216
217SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
218 : SCEV(scTruncate), Op(Op), Ty(ty) {
219 assert(Op->getType()->isInteger() && Ty->isInteger() &&
220 Ty->isUnsigned() &&
221 "Cannot zero extend non-integer value!");
222 assert(Op->getType()->getPrimitiveSize() < Ty->getPrimitiveSize() &&
223 "This is not an extending conversion!");
224}
225
226SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
227 SCEVZeroExtends.erase(std::make_pair(Op, Ty));
228}
229
230ConstantRange SCEVZeroExtendExpr::getValueRange() const {
231 return getOperand()->getValueRange().zeroExtend(getType());
232}
233
234void SCEVZeroExtendExpr::print(std::ostream &OS) const {
235 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
236}
237
238// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
239// particular input. Don't use a SCEVHandle here, or else the object will never
240// be deleted!
241static std::map<std::pair<unsigned, std::vector<SCEV*> >,
242 SCEVCommutativeExpr*> SCEVCommExprs;
243
244SCEVCommutativeExpr::~SCEVCommutativeExpr() {
245 SCEVCommExprs.erase(std::make_pair(getSCEVType(),
246 std::vector<SCEV*>(Operands.begin(),
247 Operands.end())));
248}
249
250void SCEVCommutativeExpr::print(std::ostream &OS) const {
251 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
252 const char *OpStr = getOperationStr();
253 OS << "(" << *Operands[0];
254 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
255 OS << OpStr << *Operands[i];
256 OS << ")";
257}
258
259// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
260// input. Don't use a SCEVHandle here, or else the object will never be
261// deleted!
262static std::map<std::pair<SCEV*, SCEV*>, SCEVUDivExpr*> SCEVUDivs;
263
264SCEVUDivExpr::~SCEVUDivExpr() {
265 SCEVUDivs.erase(std::make_pair(LHS, RHS));
266}
267
268void SCEVUDivExpr::print(std::ostream &OS) const {
269 OS << "(" << *LHS << " /u " << *RHS << ")";
270}
271
272const Type *SCEVUDivExpr::getType() const {
273 const Type *Ty = LHS->getType();
274 if (Ty->isSigned()) Ty = Ty->getUnsignedVersion();
275 return Ty;
276}
277
278// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
279// particular input. Don't use a SCEVHandle here, or else the object will never
280// be deleted!
281static std::map<std::pair<const Loop *, std::vector<SCEV*> >,
282 SCEVAddRecExpr*> SCEVAddRecExprs;
283
284SCEVAddRecExpr::~SCEVAddRecExpr() {
285 SCEVAddRecExprs.erase(std::make_pair(L,
286 std::vector<SCEV*>(Operands.begin(),
287 Operands.end())));
288}
289
290bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
291 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
292 // contain L.
293 return !QueryLoop->contains(L->getHeader());
Chris Lattner53e677a2004-04-02 20:23:17 +0000294}
295
296
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000297void SCEVAddRecExpr::print(std::ostream &OS) const {
298 OS << "{" << *Operands[0];
299 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
300 OS << ",+," << *Operands[i];
301 OS << "}<" << L->getHeader()->getName() + ">";
302}
Chris Lattner53e677a2004-04-02 20:23:17 +0000303
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000304// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
305// value. Don't use a SCEVHandle here, or else the object will never be
306// deleted!
307static std::map<Value*, SCEVUnknown*> SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000308
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000309SCEVUnknown::~SCEVUnknown() { SCEVUnknowns.erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000310
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000311bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
312 // All non-instruction values are loop invariant. All instructions are loop
313 // invariant if they are not contained in the specified loop.
314 if (Instruction *I = dyn_cast<Instruction>(V))
315 return !L->contains(I->getParent());
316 return true;
317}
Chris Lattner53e677a2004-04-02 20:23:17 +0000318
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000319const Type *SCEVUnknown::getType() const {
320 return V->getType();
321}
Chris Lattner53e677a2004-04-02 20:23:17 +0000322
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000323void SCEVUnknown::print(std::ostream &OS) const {
324 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000325}
326
Chris Lattner8d741b82004-06-20 06:23:15 +0000327//===----------------------------------------------------------------------===//
328// SCEV Utilities
329//===----------------------------------------------------------------------===//
330
331namespace {
332 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
333 /// than the complexity of the RHS. This comparator is used to canonicalize
334 /// expressions.
335 struct SCEVComplexityCompare {
336 bool operator()(SCEV *LHS, SCEV *RHS) {
337 return LHS->getSCEVType() < RHS->getSCEVType();
338 }
339 };
340}
341
342/// GroupByComplexity - Given a list of SCEV objects, order them by their
343/// complexity, and group objects of the same complexity together by value.
344/// When this routine is finished, we know that any duplicates in the vector are
345/// consecutive and that complexity is monotonically increasing.
346///
347/// Note that we go take special precautions to ensure that we get determinstic
348/// results from this routine. In other words, we don't want the results of
349/// this to depend on where the addresses of various SCEV objects happened to
350/// land in memory.
351///
352static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
353 if (Ops.size() < 2) return; // Noop
354 if (Ops.size() == 2) {
355 // This is the common case, which also happens to be trivially simple.
356 // Special case it.
357 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
358 std::swap(Ops[0], Ops[1]);
359 return;
360 }
361
362 // Do the rough sort by complexity.
363 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
364
365 // Now that we are sorted by complexity, group elements of the same
366 // complexity. Note that this is, at worst, N^2, but the vector is likely to
367 // be extremely short in practice. Note that we take this approach because we
368 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000369 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000370 SCEV *S = Ops[i];
371 unsigned Complexity = S->getSCEVType();
372
373 // If there are any objects of the same complexity and same value as this
374 // one, group them.
375 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
376 if (Ops[j] == S) { // Found a duplicate.
377 // Move it to immediately after i'th element.
378 std::swap(Ops[i+1], Ops[j]);
379 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000380 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000381 }
382 }
383 }
384}
385
Chris Lattner53e677a2004-04-02 20:23:17 +0000386
Chris Lattner53e677a2004-04-02 20:23:17 +0000387
388//===----------------------------------------------------------------------===//
389// Simple SCEV method implementations
390//===----------------------------------------------------------------------===//
391
392/// getIntegerSCEV - Given an integer or FP type, create a constant for the
393/// specified signed integer value and return a SCEV for the constant.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000394SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000395 Constant *C;
396 if (Val == 0)
397 C = Constant::getNullValue(Ty);
398 else if (Ty->isFloatingPoint())
399 C = ConstantFP::get(Ty, Val);
400 else if (Ty->isSigned())
401 C = ConstantSInt::get(Ty, Val);
402 else {
403 C = ConstantSInt::get(Ty->getSignedVersion(), Val);
404 C = ConstantExpr::getCast(C, Ty);
405 }
406 return SCEVUnknown::get(C);
407}
408
409/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
410/// input value to the specified type. If the type must be extended, it is zero
411/// extended.
412static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
413 const Type *SrcTy = V->getType();
414 assert(SrcTy->isInteger() && Ty->isInteger() &&
415 "Cannot truncate or zero extend with non-integer arguments!");
416 if (SrcTy->getPrimitiveSize() == Ty->getPrimitiveSize())
417 return V; // No conversion
418 if (SrcTy->getPrimitiveSize() > Ty->getPrimitiveSize())
419 return SCEVTruncateExpr::get(V, Ty);
420 return SCEVZeroExtendExpr::get(V, Ty);
421}
422
423/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
424///
425static SCEVHandle getNegativeSCEV(const SCEVHandle &V) {
426 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
427 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
428
Chris Lattnerb06432c2004-04-23 21:29:03 +0000429 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
Chris Lattner53e677a2004-04-02 20:23:17 +0000430}
431
432/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
433///
434static SCEVHandle getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
435 // X - Y --> X + -Y
436 return SCEVAddExpr::get(LHS, getNegativeSCEV(RHS));
437}
438
439
440/// Binomial - Evaluate N!/((N-M)!*M!) . Note that N is often large and M is
441/// often very small, so we try to reduce the number of N! terms we need to
442/// evaluate by evaluating this as (N!/(N-M)!)/M!
443static ConstantInt *Binomial(ConstantInt *N, unsigned M) {
444 uint64_t NVal = N->getRawValue();
445 uint64_t FirstTerm = 1;
446 for (unsigned i = 0; i != M; ++i)
447 FirstTerm *= NVal-i;
448
449 unsigned MFactorial = 1;
450 for (; M; --M)
451 MFactorial *= M;
452
453 Constant *Result = ConstantUInt::get(Type::ULongTy, FirstTerm/MFactorial);
454 Result = ConstantExpr::getCast(Result, N->getType());
455 assert(isa<ConstantInt>(Result) && "Cast of integer not folded??");
456 return cast<ConstantInt>(Result);
457}
458
459/// PartialFact - Compute V!/(V-NumSteps)!
460static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
461 // Handle this case efficiently, it is common to have constant iteration
462 // counts while computing loop exit values.
463 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
464 uint64_t Val = SC->getValue()->getRawValue();
465 uint64_t Result = 1;
466 for (; NumSteps; --NumSteps)
467 Result *= Val-(NumSteps-1);
468 Constant *Res = ConstantUInt::get(Type::ULongTy, Result);
469 return SCEVUnknown::get(ConstantExpr::getCast(Res, V->getType()));
470 }
471
472 const Type *Ty = V->getType();
473 if (NumSteps == 0)
Chris Lattnerb06432c2004-04-23 21:29:03 +0000474 return SCEVUnknown::getIntegerSCEV(1, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000475
476 SCEVHandle Result = V;
477 for (unsigned i = 1; i != NumSteps; ++i)
Chris Lattnerb06432c2004-04-23 21:29:03 +0000478 Result = SCEVMulExpr::get(Result, getMinusSCEV(V,
479 SCEVUnknown::getIntegerSCEV(i, Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000480 return Result;
481}
482
483
484/// evaluateAtIteration - Return the value of this chain of recurrences at
485/// the specified iteration number. We can evaluate this recurrence by
486/// multiplying each element in the chain by the binomial coefficient
487/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
488///
489/// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
490///
491/// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
492/// Is the binomial equation safe using modular arithmetic??
493///
494SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
495 SCEVHandle Result = getStart();
496 int Divisor = 1;
497 const Type *Ty = It->getType();
498 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
499 SCEVHandle BC = PartialFact(It, i);
500 Divisor *= i;
501 SCEVHandle Val = SCEVUDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
Chris Lattnerb06432c2004-04-23 21:29:03 +0000502 SCEVUnknown::getIntegerSCEV(Divisor,Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000503 Result = SCEVAddExpr::get(Result, Val);
504 }
505 return Result;
506}
507
508
509//===----------------------------------------------------------------------===//
510// SCEV Expression folder implementations
511//===----------------------------------------------------------------------===//
512
513SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
514 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
515 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
516
517 // If the input value is a chrec scev made out of constants, truncate
518 // all of the constants.
519 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
520 std::vector<SCEVHandle> Operands;
521 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
522 // FIXME: This should allow truncation of other expression types!
523 if (isa<SCEVConstant>(AddRec->getOperand(i)))
524 Operands.push_back(get(AddRec->getOperand(i), Ty));
525 else
526 break;
527 if (Operands.size() == AddRec->getNumOperands())
528 return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
529 }
530
531 SCEVTruncateExpr *&Result = SCEVTruncates[std::make_pair(Op, Ty)];
532 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
533 return Result;
534}
535
536SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
537 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
538 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
539
540 // FIXME: If the input value is a chrec scev, and we can prove that the value
541 // did not overflow the old, smaller, value, we can zero extend all of the
542 // operands (often constants). This would allow analysis of something like
543 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
544
545 SCEVZeroExtendExpr *&Result = SCEVZeroExtends[std::make_pair(Op, Ty)];
546 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
547 return Result;
548}
549
550// get - Get a canonical add expression, or something simpler if possible.
551SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
552 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000553 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000554
555 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000556 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000557
558 // If there are any constants, fold them together.
559 unsigned Idx = 0;
560 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
561 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000562 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000563 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
564 // We found two constants, fold them together!
565 Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue());
566 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
567 Ops[0] = SCEVConstant::get(CI);
568 Ops.erase(Ops.begin()+1); // Erase the folded element
569 if (Ops.size() == 1) return Ops[0];
570 } else {
571 // If we couldn't fold the expression, move to the next constant. Note
572 // that this is impossible to happen in practice because we always
573 // constant fold constant ints to constant ints.
574 ++Idx;
575 }
576 }
577
578 // If we are left with a constant zero being added, strip it off.
579 if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
580 Ops.erase(Ops.begin());
581 --Idx;
582 }
583 }
584
Chris Lattner627018b2004-04-07 16:16:11 +0000585 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000586
587 // Okay, check to see if the same value occurs in the operand list twice. If
588 // so, merge them together into an multiply expression. Since we sorted the
589 // list, these values are required to be adjacent.
590 const Type *Ty = Ops[0]->getType();
591 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
592 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
593 // Found a match, merge the two values into a multiply, and add any
594 // remaining values to the result.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000595 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000596 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
597 if (Ops.size() == 2)
598 return Mul;
599 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
600 Ops.push_back(Mul);
601 return SCEVAddExpr::get(Ops);
602 }
603
604 // Okay, now we know the first non-constant operand. If there are add
605 // operands they would be next.
606 if (Idx < Ops.size()) {
607 bool DeletedAdd = false;
608 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
609 // If we have an add, expand the add operands onto the end of the operands
610 // list.
611 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
612 Ops.erase(Ops.begin()+Idx);
613 DeletedAdd = true;
614 }
615
616 // If we deleted at least one add, we added operands to the end of the list,
617 // and they are not necessarily sorted. Recurse to resort and resimplify
618 // any operands we just aquired.
619 if (DeletedAdd)
620 return get(Ops);
621 }
622
623 // Skip over the add expression until we get to a multiply.
624 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
625 ++Idx;
626
627 // If we are adding something to a multiply expression, make sure the
628 // something is not already an operand of the multiply. If so, merge it into
629 // the multiply.
630 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
631 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
632 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
633 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
634 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
635 if (MulOpSCEV == Ops[AddOp] &&
636 (Mul->getNumOperands() != 2 || !isa<SCEVConstant>(MulOpSCEV))) {
637 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
638 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
639 if (Mul->getNumOperands() != 2) {
640 // If the multiply has more than two operands, we must get the
641 // Y*Z term.
642 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
643 MulOps.erase(MulOps.begin()+MulOp);
644 InnerMul = SCEVMulExpr::get(MulOps);
645 }
Chris Lattnerb06432c2004-04-23 21:29:03 +0000646 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000647 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
648 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
649 if (Ops.size() == 2) return OuterMul;
650 if (AddOp < Idx) {
651 Ops.erase(Ops.begin()+AddOp);
652 Ops.erase(Ops.begin()+Idx-1);
653 } else {
654 Ops.erase(Ops.begin()+Idx);
655 Ops.erase(Ops.begin()+AddOp-1);
656 }
657 Ops.push_back(OuterMul);
658 return SCEVAddExpr::get(Ops);
659 }
660
661 // Check this multiply against other multiplies being added together.
662 for (unsigned OtherMulIdx = Idx+1;
663 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
664 ++OtherMulIdx) {
665 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
666 // If MulOp occurs in OtherMul, we can fold the two multiplies
667 // together.
668 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
669 OMulOp != e; ++OMulOp)
670 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
671 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
672 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
673 if (Mul->getNumOperands() != 2) {
674 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
675 MulOps.erase(MulOps.begin()+MulOp);
676 InnerMul1 = SCEVMulExpr::get(MulOps);
677 }
678 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
679 if (OtherMul->getNumOperands() != 2) {
680 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
681 OtherMul->op_end());
682 MulOps.erase(MulOps.begin()+OMulOp);
683 InnerMul2 = SCEVMulExpr::get(MulOps);
684 }
685 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
686 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
687 if (Ops.size() == 2) return OuterMul;
688 Ops.erase(Ops.begin()+Idx);
689 Ops.erase(Ops.begin()+OtherMulIdx-1);
690 Ops.push_back(OuterMul);
691 return SCEVAddExpr::get(Ops);
692 }
693 }
694 }
695 }
696
697 // If there are any add recurrences in the operands list, see if any other
698 // added values are loop invariant. If so, we can fold them into the
699 // recurrence.
700 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
701 ++Idx;
702
703 // Scan over all recurrences, trying to fold loop invariants into them.
704 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
705 // Scan all of the other operands to this add and add them to the vector if
706 // they are loop invariant w.r.t. the recurrence.
707 std::vector<SCEVHandle> LIOps;
708 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
709 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
710 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
711 LIOps.push_back(Ops[i]);
712 Ops.erase(Ops.begin()+i);
713 --i; --e;
714 }
715
716 // If we found some loop invariants, fold them into the recurrence.
717 if (!LIOps.empty()) {
718 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
719 LIOps.push_back(AddRec->getStart());
720
721 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
722 AddRecOps[0] = SCEVAddExpr::get(LIOps);
723
724 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
725 // If all of the other operands were loop invariant, we are done.
726 if (Ops.size() == 1) return NewRec;
727
728 // Otherwise, add the folded AddRec by the non-liv parts.
729 for (unsigned i = 0;; ++i)
730 if (Ops[i] == AddRec) {
731 Ops[i] = NewRec;
732 break;
733 }
734 return SCEVAddExpr::get(Ops);
735 }
736
737 // Okay, if there weren't any loop invariants to be folded, check to see if
738 // there are multiple AddRec's with the same loop induction variable being
739 // added together. If so, we can fold them.
740 for (unsigned OtherIdx = Idx+1;
741 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
742 if (OtherIdx != Idx) {
743 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
744 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
745 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
746 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
747 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
748 if (i >= NewOps.size()) {
749 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
750 OtherAddRec->op_end());
751 break;
752 }
753 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
754 }
755 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
756
757 if (Ops.size() == 2) return NewAddRec;
758
759 Ops.erase(Ops.begin()+Idx);
760 Ops.erase(Ops.begin()+OtherIdx-1);
761 Ops.push_back(NewAddRec);
762 return SCEVAddExpr::get(Ops);
763 }
764 }
765
766 // Otherwise couldn't fold anything into this recurrence. Move onto the
767 // next one.
768 }
769
770 // Okay, it looks like we really DO need an add expr. Check to see if we
771 // already have one, otherwise create a new one.
772 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
773 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scAddExpr,
774 SCEVOps)];
775 if (Result == 0) Result = new SCEVAddExpr(Ops);
776 return Result;
777}
778
779
780SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
781 assert(!Ops.empty() && "Cannot get empty mul!");
782
783 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000784 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000785
786 // If there are any constants, fold them together.
787 unsigned Idx = 0;
788 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
789
790 // C1*(C2+V) -> C1*C2 + C1*V
791 if (Ops.size() == 2)
792 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
793 if (Add->getNumOperands() == 2 &&
794 isa<SCEVConstant>(Add->getOperand(0)))
795 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
796 SCEVMulExpr::get(LHSC, Add->getOperand(1)));
797
798
799 ++Idx;
800 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
801 // We found two constants, fold them together!
802 Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue());
803 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
804 Ops[0] = SCEVConstant::get(CI);
805 Ops.erase(Ops.begin()+1); // Erase the folded element
806 if (Ops.size() == 1) return Ops[0];
807 } else {
808 // If we couldn't fold the expression, move to the next constant. Note
809 // that this is impossible to happen in practice because we always
810 // constant fold constant ints to constant ints.
811 ++Idx;
812 }
813 }
814
815 // If we are left with a constant one being multiplied, strip it off.
816 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
817 Ops.erase(Ops.begin());
818 --Idx;
819 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
820 // If we have a multiply of zero, it will always be zero.
821 return Ops[0];
822 }
823 }
824
825 // Skip over the add expression until we get to a multiply.
826 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
827 ++Idx;
828
829 if (Ops.size() == 1)
830 return Ops[0];
831
832 // If there are mul operands inline them all into this expression.
833 if (Idx < Ops.size()) {
834 bool DeletedMul = false;
835 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
836 // If we have an mul, expand the mul operands onto the end of the operands
837 // list.
838 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
839 Ops.erase(Ops.begin()+Idx);
840 DeletedMul = true;
841 }
842
843 // If we deleted at least one mul, we added operands to the end of the list,
844 // and they are not necessarily sorted. Recurse to resort and resimplify
845 // any operands we just aquired.
846 if (DeletedMul)
847 return get(Ops);
848 }
849
850 // If there are any add recurrences in the operands list, see if any other
851 // added values are loop invariant. If so, we can fold them into the
852 // recurrence.
853 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
854 ++Idx;
855
856 // Scan over all recurrences, trying to fold loop invariants into them.
857 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
858 // Scan all of the other operands to this mul and add them to the vector if
859 // they are loop invariant w.r.t. the recurrence.
860 std::vector<SCEVHandle> LIOps;
861 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
862 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
863 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
864 LIOps.push_back(Ops[i]);
865 Ops.erase(Ops.begin()+i);
866 --i; --e;
867 }
868
869 // If we found some loop invariants, fold them into the recurrence.
870 if (!LIOps.empty()) {
871 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
872 std::vector<SCEVHandle> NewOps;
873 NewOps.reserve(AddRec->getNumOperands());
874 if (LIOps.size() == 1) {
875 SCEV *Scale = LIOps[0];
876 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
877 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
878 } else {
879 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
880 std::vector<SCEVHandle> MulOps(LIOps);
881 MulOps.push_back(AddRec->getOperand(i));
882 NewOps.push_back(SCEVMulExpr::get(MulOps));
883 }
884 }
885
886 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
887
888 // If all of the other operands were loop invariant, we are done.
889 if (Ops.size() == 1) return NewRec;
890
891 // Otherwise, multiply the folded AddRec by the non-liv parts.
892 for (unsigned i = 0;; ++i)
893 if (Ops[i] == AddRec) {
894 Ops[i] = NewRec;
895 break;
896 }
897 return SCEVMulExpr::get(Ops);
898 }
899
900 // Okay, if there weren't any loop invariants to be folded, check to see if
901 // there are multiple AddRec's with the same loop induction variable being
902 // multiplied together. If so, we can fold them.
903 for (unsigned OtherIdx = Idx+1;
904 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
905 if (OtherIdx != Idx) {
906 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
907 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
908 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
909 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
910 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
911 G->getStart());
912 SCEVHandle B = F->getStepRecurrence();
913 SCEVHandle D = G->getStepRecurrence();
914 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
915 SCEVMulExpr::get(G, B),
916 SCEVMulExpr::get(B, D));
917 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
918 F->getLoop());
919 if (Ops.size() == 2) return NewAddRec;
920
921 Ops.erase(Ops.begin()+Idx);
922 Ops.erase(Ops.begin()+OtherIdx-1);
923 Ops.push_back(NewAddRec);
924 return SCEVMulExpr::get(Ops);
925 }
926 }
927
928 // Otherwise couldn't fold anything into this recurrence. Move onto the
929 // next one.
930 }
931
932 // Okay, it looks like we really DO need an mul expr. Check to see if we
933 // already have one, otherwise create a new one.
934 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
935 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scMulExpr,
936 SCEVOps)];
937 if (Result == 0) Result = new SCEVMulExpr(Ops);
938 return Result;
939}
940
941SCEVHandle SCEVUDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
942 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
943 if (RHSC->getValue()->equalsInt(1))
944 return LHS; // X /u 1 --> x
945 if (RHSC->getValue()->isAllOnesValue())
946 return getNegativeSCEV(LHS); // X /u -1 --> -x
947
948 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
949 Constant *LHSCV = LHSC->getValue();
950 Constant *RHSCV = RHSC->getValue();
951 if (LHSCV->getType()->isSigned())
952 LHSCV = ConstantExpr::getCast(LHSCV,
953 LHSCV->getType()->getUnsignedVersion());
954 if (RHSCV->getType()->isSigned())
955 RHSCV = ConstantExpr::getCast(RHSCV, LHSCV->getType());
956 return SCEVUnknown::get(ConstantExpr::getDiv(LHSCV, RHSCV));
957 }
958 }
959
960 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
961
962 SCEVUDivExpr *&Result = SCEVUDivs[std::make_pair(LHS, RHS)];
963 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
964 return Result;
965}
966
967
968/// SCEVAddRecExpr::get - Get a add recurrence expression for the
969/// specified loop. Simplify the expression as much as possible.
970SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
971 const SCEVHandle &Step, const Loop *L) {
972 std::vector<SCEVHandle> Operands;
973 Operands.push_back(Start);
974 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
975 if (StepChrec->getLoop() == L) {
976 Operands.insert(Operands.end(), StepChrec->op_begin(),
977 StepChrec->op_end());
978 return get(Operands, L);
979 }
980
981 Operands.push_back(Step);
982 return get(Operands, L);
983}
984
985/// SCEVAddRecExpr::get - Get a add recurrence expression for the
986/// specified loop. Simplify the expression as much as possible.
987SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
988 const Loop *L) {
989 if (Operands.size() == 1) return Operands[0];
990
991 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
992 if (StepC->getValue()->isNullValue()) {
993 Operands.pop_back();
994 return get(Operands, L); // { X,+,0 } --> X
995 }
996
997 SCEVAddRecExpr *&Result =
998 SCEVAddRecExprs[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
999 Operands.end()))];
1000 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1001 return Result;
1002}
1003
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001004SCEVHandle SCEVUnknown::get(Value *V) {
1005 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1006 return SCEVConstant::get(CI);
1007 SCEVUnknown *&Result = SCEVUnknowns[V];
1008 if (Result == 0) Result = new SCEVUnknown(V);
1009 return Result;
1010}
1011
Chris Lattner53e677a2004-04-02 20:23:17 +00001012
1013//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001014// ScalarEvolutionsImpl Definition and Implementation
1015//===----------------------------------------------------------------------===//
1016//
1017/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1018/// evolution code.
1019///
1020namespace {
1021 struct ScalarEvolutionsImpl {
1022 /// F - The function we are analyzing.
1023 ///
1024 Function &F;
1025
1026 /// LI - The loop information for the function we are currently analyzing.
1027 ///
1028 LoopInfo &LI;
1029
1030 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1031 /// things.
1032 SCEVHandle UnknownValue;
1033
1034 /// Scalars - This is a cache of the scalars we have analyzed so far.
1035 ///
1036 std::map<Value*, SCEVHandle> Scalars;
1037
1038 /// IterationCounts - Cache the iteration count of the loops for this
1039 /// function as they are computed.
1040 std::map<const Loop*, SCEVHandle> IterationCounts;
1041
Chris Lattner3221ad02004-04-17 22:58:41 +00001042 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1043 /// the PHI instructions that we attempt to compute constant evolutions for.
1044 /// This allows us to avoid potentially expensive recomputation of these
1045 /// properties. An instruction maps to null if we are unable to compute its
1046 /// exit value.
1047 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1048
Chris Lattner53e677a2004-04-02 20:23:17 +00001049 public:
1050 ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1051 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1052
1053 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1054 /// expression and create a new one.
1055 SCEVHandle getSCEV(Value *V);
1056
1057 /// getSCEVAtScope - Compute the value of the specified expression within
1058 /// the indicated loop (which may be null to indicate in no loop). If the
1059 /// expression cannot be evaluated, return UnknownValue itself.
1060 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1061
1062
1063 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1064 /// an analyzable loop-invariant iteration count.
1065 bool hasLoopInvariantIterationCount(const Loop *L);
1066
1067 /// getIterationCount - If the specified loop has a predictable iteration
1068 /// count, return it. Note that it is not valid to call this method on a
1069 /// loop without a loop-invariant iteration count.
1070 SCEVHandle getIterationCount(const Loop *L);
1071
1072 /// deleteInstructionFromRecords - This method should be called by the
1073 /// client before it removes an instruction from the program, to make sure
1074 /// that no dangling references are left around.
1075 void deleteInstructionFromRecords(Instruction *I);
1076
1077 private:
1078 /// createSCEV - We know that there is no SCEV for the specified value.
1079 /// Analyze the expression.
1080 SCEVHandle createSCEV(Value *V);
1081 SCEVHandle createNodeForCast(CastInst *CI);
1082
1083 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1084 /// SCEVs.
1085 SCEVHandle createNodeForPHI(PHINode *PN);
1086 void UpdatePHIUserScalarEntries(Instruction *I, PHINode *PN,
1087 std::set<Instruction*> &UpdatedInsts);
1088
1089 /// ComputeIterationCount - Compute the number of times the specified loop
1090 /// will iterate.
1091 SCEVHandle ComputeIterationCount(const Loop *L);
1092
Chris Lattner7980fb92004-04-17 18:36:24 +00001093 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1094 /// constant number of times (the condition evolves only from constants),
1095 /// try to evaluate a few iterations of the loop until we get the exit
1096 /// condition gets a value of ExitWhen (true or false). If we cannot
1097 /// evaluate the trip count of the loop, return UnknownValue.
1098 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1099 bool ExitWhen);
1100
Chris Lattner53e677a2004-04-02 20:23:17 +00001101 /// HowFarToZero - Return the number of times a backedge comparing the
1102 /// specified value to zero will execute. If not computable, return
1103 /// UnknownValue
1104 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1105
1106 /// HowFarToNonZero - Return the number of times a backedge checking the
1107 /// specified value for nonzero will execute. If not computable, return
1108 /// UnknownValue
1109 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattner3221ad02004-04-17 22:58:41 +00001110
1111 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1112 /// in the header of its containing loop, we know the loop executes a
1113 /// constant number of times, and the PHI node is just a recurrence
1114 /// involving constants, fold it.
1115 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its,
1116 const Loop *L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001117 };
1118}
1119
1120//===----------------------------------------------------------------------===//
1121// Basic SCEV Analysis and PHI Idiom Recognition Code
1122//
1123
1124/// deleteInstructionFromRecords - This method should be called by the
1125/// client before it removes an instruction from the program, to make sure
1126/// that no dangling references are left around.
1127void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
1128 Scalars.erase(I);
Chris Lattner3221ad02004-04-17 22:58:41 +00001129 if (PHINode *PN = dyn_cast<PHINode>(I))
1130 ConstantEvolutionLoopExitValue.erase(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001131}
1132
1133
1134/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1135/// expression and create a new one.
1136SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1137 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1138
1139 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1140 if (I != Scalars.end()) return I->second;
1141 SCEVHandle S = createSCEV(V);
1142 Scalars.insert(std::make_pair(V, S));
1143 return S;
1144}
1145
1146
1147/// UpdatePHIUserScalarEntries - After PHI node analysis, we have a bunch of
1148/// entries in the scalar map that refer to the "symbolic" PHI value instead of
1149/// the recurrence value. After we resolve the PHI we must loop over all of the
1150/// using instructions that have scalar map entries and update them.
1151void ScalarEvolutionsImpl::UpdatePHIUserScalarEntries(Instruction *I,
1152 PHINode *PN,
1153 std::set<Instruction*> &UpdatedInsts) {
1154 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1155 if (SI == Scalars.end()) return; // This scalar wasn't previous processed.
1156 if (UpdatedInsts.insert(I).second) {
1157 Scalars.erase(SI); // Remove the old entry
1158 getSCEV(I); // Calculate the new entry
1159
1160 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1161 UI != E; ++UI)
1162 UpdatePHIUserScalarEntries(cast<Instruction>(*UI), PN, UpdatedInsts);
1163 }
1164}
1165
1166
1167/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1168/// a loop header, making it a potential recurrence, or it doesn't.
1169///
1170SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1171 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1172 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1173 if (L->getHeader() == PN->getParent()) {
1174 // If it lives in the loop header, it has two incoming values, one
1175 // from outside the loop, and one from inside.
1176 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1177 unsigned BackEdge = IncomingEdge^1;
1178
1179 // While we are analyzing this PHI node, handle its value symbolically.
1180 SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1181 assert(Scalars.find(PN) == Scalars.end() &&
1182 "PHI node already processed?");
1183 Scalars.insert(std::make_pair(PN, SymbolicName));
1184
1185 // Using this symbolic name for the PHI, analyze the value coming around
1186 // the back-edge.
1187 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1188
1189 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1190 // has a special value for the first iteration of the loop.
1191
1192 // If the value coming around the backedge is an add with the symbolic
1193 // value we just inserted, then we found a simple induction variable!
1194 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1195 // If there is a single occurrence of the symbolic value, replace it
1196 // with a recurrence.
1197 unsigned FoundIndex = Add->getNumOperands();
1198 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1199 if (Add->getOperand(i) == SymbolicName)
1200 if (FoundIndex == e) {
1201 FoundIndex = i;
1202 break;
1203 }
1204
1205 if (FoundIndex != Add->getNumOperands()) {
1206 // Create an add with everything but the specified operand.
1207 std::vector<SCEVHandle> Ops;
1208 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1209 if (i != FoundIndex)
1210 Ops.push_back(Add->getOperand(i));
1211 SCEVHandle Accum = SCEVAddExpr::get(Ops);
1212
1213 // This is not a valid addrec if the step amount is varying each
1214 // loop iteration, but is not itself an addrec in this loop.
1215 if (Accum->isLoopInvariant(L) ||
1216 (isa<SCEVAddRecExpr>(Accum) &&
1217 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1218 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1219 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L);
1220
1221 // Okay, for the entire analysis of this edge we assumed the PHI
1222 // to be symbolic. We now need to go back and update all of the
1223 // entries for the scalars that use the PHI (except for the PHI
1224 // itself) to use the new analyzed value instead of the "symbolic"
1225 // value.
1226 Scalars.find(PN)->second = PHISCEV; // Update the PHI value
1227 std::set<Instruction*> UpdatedInsts;
1228 UpdatedInsts.insert(PN);
1229 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
1230 UI != E; ++UI)
1231 UpdatePHIUserScalarEntries(cast<Instruction>(*UI), PN,
1232 UpdatedInsts);
1233 return PHISCEV;
1234 }
1235 }
1236 }
1237
1238 return SymbolicName;
1239 }
1240
1241 // If it's not a loop phi, we can't handle it yet.
1242 return SCEVUnknown::get(PN);
1243}
1244
1245/// createNodeForCast - Handle the various forms of casts that we support.
1246///
1247SCEVHandle ScalarEvolutionsImpl::createNodeForCast(CastInst *CI) {
1248 const Type *SrcTy = CI->getOperand(0)->getType();
1249 const Type *DestTy = CI->getType();
1250
1251 // If this is a noop cast (ie, conversion from int to uint), ignore it.
1252 if (SrcTy->isLosslesslyConvertibleTo(DestTy))
1253 return getSCEV(CI->getOperand(0));
1254
1255 if (SrcTy->isInteger() && DestTy->isInteger()) {
1256 // Otherwise, if this is a truncating integer cast, we can represent this
1257 // cast.
1258 if (SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1259 return SCEVTruncateExpr::get(getSCEV(CI->getOperand(0)),
1260 CI->getType()->getUnsignedVersion());
1261 if (SrcTy->isUnsigned() &&
1262 SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1263 return SCEVZeroExtendExpr::get(getSCEV(CI->getOperand(0)),
1264 CI->getType()->getUnsignedVersion());
1265 }
1266
1267 // If this is an sign or zero extending cast and we can prove that the value
1268 // will never overflow, we could do similar transformations.
1269
1270 // Otherwise, we can't handle this cast!
1271 return SCEVUnknown::get(CI);
1272}
1273
1274
1275/// createSCEV - We know that there is no SCEV for the specified value.
1276/// Analyze the expression.
1277///
1278SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1279 if (Instruction *I = dyn_cast<Instruction>(V)) {
1280 switch (I->getOpcode()) {
1281 case Instruction::Add:
1282 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1283 getSCEV(I->getOperand(1)));
1284 case Instruction::Mul:
1285 return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1286 getSCEV(I->getOperand(1)));
1287 case Instruction::Div:
1288 if (V->getType()->isInteger() && V->getType()->isUnsigned())
1289 return SCEVUDivExpr::get(getSCEV(I->getOperand(0)),
1290 getSCEV(I->getOperand(1)));
1291 break;
1292
1293 case Instruction::Sub:
1294 return getMinusSCEV(getSCEV(I->getOperand(0)), getSCEV(I->getOperand(1)));
1295
1296 case Instruction::Shl:
1297 // Turn shift left of a constant amount into a multiply.
1298 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1299 Constant *X = ConstantInt::get(V->getType(), 1);
1300 X = ConstantExpr::getShl(X, SA);
1301 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1302 }
1303 break;
1304
1305 case Instruction::Shr:
1306 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1307 if (V->getType()->isUnsigned()) {
1308 Constant *X = ConstantInt::get(V->getType(), 1);
1309 X = ConstantExpr::getShl(X, SA);
1310 return SCEVUDivExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1311 }
1312 break;
1313
1314 case Instruction::Cast:
1315 return createNodeForCast(cast<CastInst>(I));
1316
1317 case Instruction::PHI:
1318 return createNodeForPHI(cast<PHINode>(I));
1319
1320 default: // We cannot analyze this expression.
1321 break;
1322 }
1323 }
1324
1325 return SCEVUnknown::get(V);
1326}
1327
1328
1329
1330//===----------------------------------------------------------------------===//
1331// Iteration Count Computation Code
1332//
1333
1334/// getIterationCount - If the specified loop has a predictable iteration
1335/// count, return it. Note that it is not valid to call this method on a
1336/// loop without a loop-invariant iteration count.
1337SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1338 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1339 if (I == IterationCounts.end()) {
1340 SCEVHandle ItCount = ComputeIterationCount(L);
1341 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1342 if (ItCount != UnknownValue) {
1343 assert(ItCount->isLoopInvariant(L) &&
1344 "Computed trip count isn't loop invariant for loop!");
1345 ++NumTripCountsComputed;
1346 } else if (isa<PHINode>(L->getHeader()->begin())) {
1347 // Only count loops that have phi nodes as not being computable.
1348 ++NumTripCountsNotComputed;
1349 }
1350 }
1351 return I->second;
1352}
1353
1354/// ComputeIterationCount - Compute the number of times the specified loop
1355/// will iterate.
1356SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1357 // If the loop has a non-one exit block count, we can't analyze it.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001358 std::vector<BasicBlock*> ExitBlocks;
1359 L->getExitBlocks(ExitBlocks);
1360 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001361
1362 // Okay, there is one exit block. Try to find the condition that causes the
1363 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001364 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001365
1366 BasicBlock *ExitingBlock = 0;
1367 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1368 PI != E; ++PI)
1369 if (L->contains(*PI)) {
1370 if (ExitingBlock == 0)
1371 ExitingBlock = *PI;
1372 else
1373 return UnknownValue; // More than one block exiting!
1374 }
1375 assert(ExitingBlock && "No exits from loop, something is broken!");
1376
1377 // Okay, we've computed the exiting block. See what condition causes us to
1378 // exit.
1379 //
1380 // FIXME: we should be able to handle switch instructions (with a single exit)
1381 // FIXME: We should handle cast of int to bool as well
1382 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1383 if (ExitBr == 0) return UnknownValue;
1384 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1385 SetCondInst *ExitCond = dyn_cast<SetCondInst>(ExitBr->getCondition());
Chris Lattner7980fb92004-04-17 18:36:24 +00001386 if (ExitCond == 0) // Not a setcc
1387 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1388 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00001389
1390 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1391 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1392
1393 // Try to evaluate any dependencies out of the loop.
1394 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1395 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1396 Tmp = getSCEVAtScope(RHS, L);
1397 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1398
1399 // If the condition was exit on true, convert the condition to exit on false.
1400 Instruction::BinaryOps Cond;
1401 if (ExitBr->getSuccessor(1) == ExitBlock)
1402 Cond = ExitCond->getOpcode();
1403 else
1404 Cond = ExitCond->getInverseCondition();
1405
1406 // At this point, we would like to compute how many iterations of the loop the
1407 // predicate will return true for these inputs.
1408 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1409 // If there is a constant, force it into the RHS.
1410 std::swap(LHS, RHS);
1411 Cond = SetCondInst::getSwappedCondition(Cond);
1412 }
1413
1414 // FIXME: think about handling pointer comparisons! i.e.:
1415 // while (P != P+100) ++P;
1416
1417 // If we have a comparison of a chrec against a constant, try to use value
1418 // ranges to answer this query.
1419 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1420 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1421 if (AddRec->getLoop() == L) {
1422 // Form the comparison range using the constant of the correct type so
1423 // that the ConstantRange class knows to do a signed or unsigned
1424 // comparison.
1425 ConstantInt *CompVal = RHSC->getValue();
1426 const Type *RealTy = ExitCond->getOperand(0)->getType();
1427 CompVal = dyn_cast<ConstantInt>(ConstantExpr::getCast(CompVal, RealTy));
1428 if (CompVal) {
1429 // Form the constant range.
1430 ConstantRange CompRange(Cond, CompVal);
1431
1432 // Now that we have it, if it's signed, convert it to an unsigned
1433 // range.
1434 if (CompRange.getLower()->getType()->isSigned()) {
1435 const Type *NewTy = RHSC->getValue()->getType();
1436 Constant *NewL = ConstantExpr::getCast(CompRange.getLower(), NewTy);
1437 Constant *NewU = ConstantExpr::getCast(CompRange.getUpper(), NewTy);
1438 CompRange = ConstantRange(NewL, NewU);
1439 }
1440
1441 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange);
1442 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1443 }
1444 }
1445
1446 switch (Cond) {
1447 case Instruction::SetNE: // while (X != Y)
1448 // Convert to: while (X-Y != 0)
Chris Lattner7980fb92004-04-17 18:36:24 +00001449 if (LHS->getType()->isInteger()) {
1450 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
1451 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1452 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001453 break;
1454 case Instruction::SetEQ:
1455 // Convert to: while (X-Y == 0) // while (X == Y)
Chris Lattner7980fb92004-04-17 18:36:24 +00001456 if (LHS->getType()->isInteger()) {
1457 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
1458 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1459 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001460 break;
1461 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001462#if 0
Chris Lattner53e677a2004-04-02 20:23:17 +00001463 std::cerr << "ComputeIterationCount ";
1464 if (ExitCond->getOperand(0)->getType()->isUnsigned())
1465 std::cerr << "[unsigned] ";
1466 std::cerr << *LHS << " "
1467 << Instruction::getOpcodeName(Cond) << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001468#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00001469 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001470 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001471
1472 return ComputeIterationCountExhaustively(L, ExitCond,
1473 ExitBr->getSuccessor(0) == ExitBlock);
1474}
1475
Chris Lattner3221ad02004-04-17 22:58:41 +00001476/// CanConstantFold - Return true if we can constant fold an instruction of the
1477/// specified type, assuming that all operands were constants.
1478static bool CanConstantFold(const Instruction *I) {
1479 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I) ||
1480 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1481 return true;
Chris Lattner7980fb92004-04-17 18:36:24 +00001482
Chris Lattner3221ad02004-04-17 22:58:41 +00001483 if (const CallInst *CI = dyn_cast<CallInst>(I))
1484 if (const Function *F = CI->getCalledFunction())
1485 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1486 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00001487}
1488
Chris Lattner3221ad02004-04-17 22:58:41 +00001489/// ConstantFold - Constant fold an instruction of the specified type with the
1490/// specified constant operands. This function may modify the operands vector.
1491static Constant *ConstantFold(const Instruction *I,
1492 std::vector<Constant*> &Operands) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001493 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
1494 return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]);
1495
1496 switch (I->getOpcode()) {
1497 case Instruction::Cast:
1498 return ConstantExpr::getCast(Operands[0], I->getType());
1499 case Instruction::Select:
1500 return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]);
1501 case Instruction::Call:
Reid Spencere8404342004-07-18 00:18:30 +00001502 if (Function *GV = dyn_cast<Function>(Operands[0])) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001503 Operands.erase(Operands.begin());
Reid Spencere8404342004-07-18 00:18:30 +00001504 return ConstantFoldCall(cast<Function>(GV), Operands);
Chris Lattner7980fb92004-04-17 18:36:24 +00001505 }
1506
1507 return 0;
1508 case Instruction::GetElementPtr:
1509 Constant *Base = Operands[0];
1510 Operands.erase(Operands.begin());
1511 return ConstantExpr::getGetElementPtr(Base, Operands);
1512 }
1513 return 0;
1514}
1515
1516
Chris Lattner3221ad02004-04-17 22:58:41 +00001517/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1518/// in the loop that V is derived from. We allow arbitrary operations along the
1519/// way, but the operands of an operation must either be constants or a value
1520/// derived from a constant PHI. If this expression does not fit with these
1521/// constraints, return null.
1522static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1523 // If this is not an instruction, or if this is an instruction outside of the
1524 // loop, it can't be derived from a loop PHI.
1525 Instruction *I = dyn_cast<Instruction>(V);
1526 if (I == 0 || !L->contains(I->getParent())) return 0;
1527
1528 if (PHINode *PN = dyn_cast<PHINode>(I))
1529 if (L->getHeader() == I->getParent())
1530 return PN;
1531 else
1532 // We don't currently keep track of the control flow needed to evaluate
1533 // PHIs, so we cannot handle PHIs inside of loops.
1534 return 0;
1535
1536 // If we won't be able to constant fold this expression even if the operands
1537 // are constants, return early.
1538 if (!CanConstantFold(I)) return 0;
1539
1540 // Otherwise, we can evaluate this instruction if all of its operands are
1541 // constant or derived from a PHI node themselves.
1542 PHINode *PHI = 0;
1543 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1544 if (!(isa<Constant>(I->getOperand(Op)) ||
1545 isa<GlobalValue>(I->getOperand(Op)))) {
1546 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1547 if (P == 0) return 0; // Not evolving from PHI
1548 if (PHI == 0)
1549 PHI = P;
1550 else if (PHI != P)
1551 return 0; // Evolving from multiple different PHIs.
1552 }
1553
1554 // This is a expression evolving from a constant PHI!
1555 return PHI;
1556}
1557
1558/// EvaluateExpression - Given an expression that passes the
1559/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1560/// in the loop has the value PHIVal. If we can't fold this expression for some
1561/// reason, return null.
1562static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1563 if (isa<PHINode>(V)) return PHIVal;
Chris Lattner3221ad02004-04-17 22:58:41 +00001564 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
Reid Spencere8404342004-07-18 00:18:30 +00001565 return GV;
1566 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00001567 Instruction *I = cast<Instruction>(V);
1568
1569 std::vector<Constant*> Operands;
1570 Operands.resize(I->getNumOperands());
1571
1572 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1573 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1574 if (Operands[i] == 0) return 0;
1575 }
1576
1577 return ConstantFold(I, Operands);
1578}
1579
1580/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1581/// in the header of its containing loop, we know the loop executes a
1582/// constant number of times, and the PHI node is just a recurrence
1583/// involving constants, fold it.
1584Constant *ScalarEvolutionsImpl::
1585getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) {
1586 std::map<PHINode*, Constant*>::iterator I =
1587 ConstantEvolutionLoopExitValue.find(PN);
1588 if (I != ConstantEvolutionLoopExitValue.end())
1589 return I->second;
1590
1591 if (Its > MaxBruteForceIterations)
1592 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1593
1594 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1595
1596 // Since the loop is canonicalized, the PHI node must have two entries. One
1597 // entry must be a constant (coming in from outside of the loop), and the
1598 // second must be derived from the same PHI.
1599 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1600 Constant *StartCST =
1601 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1602 if (StartCST == 0)
1603 return RetVal = 0; // Must be a constant.
1604
1605 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1606 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1607 if (PN2 != PN)
1608 return RetVal = 0; // Not derived from same PHI.
1609
1610 // Execute the loop symbolically to determine the exit value.
1611 unsigned IterationNum = 0;
1612 unsigned NumIterations = Its;
1613 if (NumIterations != Its)
1614 return RetVal = 0; // More than 2^32 iterations??
1615
1616 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1617 if (IterationNum == NumIterations)
1618 return RetVal = PHIVal; // Got exit value!
1619
1620 // Compute the value of the PHI node for the next iteration.
1621 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1622 if (NextPHI == PHIVal)
1623 return RetVal = NextPHI; // Stopped evolving!
1624 if (NextPHI == 0)
1625 return 0; // Couldn't evaluate!
1626 PHIVal = NextPHI;
1627 }
1628}
1629
Chris Lattner7980fb92004-04-17 18:36:24 +00001630/// ComputeIterationCountExhaustively - If the trip is known to execute a
1631/// constant number of times (the condition evolves only from constants),
1632/// try to evaluate a few iterations of the loop until we get the exit
1633/// condition gets a value of ExitWhen (true or false). If we cannot
1634/// evaluate the trip count of the loop, return UnknownValue.
1635SCEVHandle ScalarEvolutionsImpl::
1636ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1637 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1638 if (PN == 0) return UnknownValue;
1639
1640 // Since the loop is canonicalized, the PHI node must have two entries. One
1641 // entry must be a constant (coming in from outside of the loop), and the
1642 // second must be derived from the same PHI.
1643 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1644 Constant *StartCST =
1645 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1646 if (StartCST == 0) return UnknownValue; // Must be a constant.
1647
1648 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1649 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1650 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
1651
1652 // Okay, we find a PHI node that defines the trip count of this loop. Execute
1653 // the loop symbolically to determine when the condition gets a value of
1654 // "ExitWhen".
1655 unsigned IterationNum = 0;
1656 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
1657 for (Constant *PHIVal = StartCST;
1658 IterationNum != MaxIterations; ++IterationNum) {
1659 ConstantBool *CondVal =
1660 dyn_cast_or_null<ConstantBool>(EvaluateExpression(Cond, PHIVal));
1661 if (!CondVal) return UnknownValue; // Couldn't symbolically evaluate.
Chris Lattner3221ad02004-04-17 22:58:41 +00001662
Chris Lattner7980fb92004-04-17 18:36:24 +00001663 if (CondVal->getValue() == ExitWhen) {
Chris Lattner3221ad02004-04-17 22:58:41 +00001664 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00001665 ++NumBruteForceTripCountsComputed;
1666 return SCEVConstant::get(ConstantUInt::get(Type::UIntTy, IterationNum));
1667 }
1668
Chris Lattner3221ad02004-04-17 22:58:41 +00001669 // Compute the value of the PHI node for the next iteration.
1670 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1671 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00001672 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00001673 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00001674 }
1675
1676 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00001677 return UnknownValue;
1678}
1679
1680/// getSCEVAtScope - Compute the value of the specified expression within the
1681/// indicated loop (which may be null to indicate in no loop). If the
1682/// expression cannot be evaluated, return UnknownValue.
1683SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1684 // FIXME: this should be turned into a virtual method on SCEV!
1685
Chris Lattner3221ad02004-04-17 22:58:41 +00001686 if (isa<SCEVConstant>(V)) return V;
1687
1688 // If this instruction is evolves from a constant-evolving PHI, compute the
1689 // exit value from the loop without using SCEVs.
1690 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
1691 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
1692 const Loop *LI = this->LI[I->getParent()];
1693 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
1694 if (PHINode *PN = dyn_cast<PHINode>(I))
1695 if (PN->getParent() == LI->getHeader()) {
1696 // Okay, there is no closed form solution for the PHI node. Check
1697 // to see if the loop that contains it has a known iteration count.
1698 // If so, we may be able to force computation of the exit value.
1699 SCEVHandle IterationCount = getIterationCount(LI);
1700 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
1701 // Okay, we know how many times the containing loop executes. If
1702 // this is a constant evolving PHI node, get the final value at
1703 // the specified iteration number.
1704 Constant *RV = getConstantEvolutionLoopExitValue(PN,
1705 ICC->getValue()->getRawValue(),
1706 LI);
1707 if (RV) return SCEVUnknown::get(RV);
1708 }
1709 }
1710
1711 // Okay, this is a some expression that we cannot symbolically evaluate
1712 // into a SCEV. Check to see if it's possible to symbolically evaluate
1713 // the arguments into constants, and if see, try to constant propagate the
1714 // result. This is particularly useful for computing loop exit values.
1715 if (CanConstantFold(I)) {
1716 std::vector<Constant*> Operands;
1717 Operands.reserve(I->getNumOperands());
1718 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1719 Value *Op = I->getOperand(i);
1720 if (Constant *C = dyn_cast<Constant>(Op)) {
1721 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00001722 } else {
1723 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
1724 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
1725 Operands.push_back(ConstantExpr::getCast(SC->getValue(),
1726 Op->getType()));
1727 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
1728 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
1729 Operands.push_back(ConstantExpr::getCast(C, Op->getType()));
1730 else
1731 return V;
1732 } else {
1733 return V;
1734 }
1735 }
1736 }
1737 return SCEVUnknown::get(ConstantFold(I, Operands));
1738 }
1739 }
1740
1741 // This is some other type of SCEVUnknown, just return it.
1742 return V;
1743 }
1744
Chris Lattner53e677a2004-04-02 20:23:17 +00001745 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
1746 // Avoid performing the look-up in the common case where the specified
1747 // expression has no loop-variant portions.
1748 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
1749 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1750 if (OpAtScope != Comm->getOperand(i)) {
1751 if (OpAtScope == UnknownValue) return UnknownValue;
1752 // Okay, at least one of these operands is loop variant but might be
1753 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00001754 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00001755 NewOps.push_back(OpAtScope);
1756
1757 for (++i; i != e; ++i) {
1758 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1759 if (OpAtScope == UnknownValue) return UnknownValue;
1760 NewOps.push_back(OpAtScope);
1761 }
1762 if (isa<SCEVAddExpr>(Comm))
1763 return SCEVAddExpr::get(NewOps);
1764 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
1765 return SCEVMulExpr::get(NewOps);
1766 }
1767 }
1768 // If we got here, all operands are loop invariant.
1769 return Comm;
1770 }
1771
1772 if (SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(V)) {
1773 SCEVHandle LHS = getSCEVAtScope(UDiv->getLHS(), L);
1774 if (LHS == UnknownValue) return LHS;
1775 SCEVHandle RHS = getSCEVAtScope(UDiv->getRHS(), L);
1776 if (RHS == UnknownValue) return RHS;
1777 if (LHS == UDiv->getLHS() && RHS == UDiv->getRHS())
1778 return UDiv; // must be loop invariant
1779 return SCEVUDivExpr::get(LHS, RHS);
1780 }
1781
1782 // If this is a loop recurrence for a loop that does not contain L, then we
1783 // are dealing with the final value computed by the loop.
1784 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
1785 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
1786 // To evaluate this recurrence, we need to know how many times the AddRec
1787 // loop iterates. Compute this now.
1788 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
1789 if (IterationCount == UnknownValue) return UnknownValue;
1790 IterationCount = getTruncateOrZeroExtend(IterationCount,
1791 AddRec->getType());
1792
1793 // If the value is affine, simplify the expression evaluation to just
1794 // Start + Step*IterationCount.
1795 if (AddRec->isAffine())
1796 return SCEVAddExpr::get(AddRec->getStart(),
1797 SCEVMulExpr::get(IterationCount,
1798 AddRec->getOperand(1)));
1799
1800 // Otherwise, evaluate it the hard way.
1801 return AddRec->evaluateAtIteration(IterationCount);
1802 }
1803 return UnknownValue;
1804 }
1805
1806 //assert(0 && "Unknown SCEV type!");
1807 return UnknownValue;
1808}
1809
1810
1811/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
1812/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
1813/// might be the same) or two SCEVCouldNotCompute objects.
1814///
1815static std::pair<SCEVHandle,SCEVHandle>
1816SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
1817 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
1818 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
1819 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
1820 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
1821
1822 // We currently can only solve this if the coefficients are constants.
1823 if (!L || !M || !N) {
1824 SCEV *CNC = new SCEVCouldNotCompute();
1825 return std::make_pair(CNC, CNC);
1826 }
1827
1828 Constant *Two = ConstantInt::get(L->getValue()->getType(), 2);
1829
1830 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
1831 Constant *C = L->getValue();
1832 // The B coefficient is M-N/2
1833 Constant *B = ConstantExpr::getSub(M->getValue(),
1834 ConstantExpr::getDiv(N->getValue(),
1835 Two));
1836 // The A coefficient is N/2
1837 Constant *A = ConstantExpr::getDiv(N->getValue(), Two);
1838
1839 // Compute the B^2-4ac term.
1840 Constant *SqrtTerm =
1841 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
1842 ConstantExpr::getMul(A, C));
1843 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
1844
1845 // Compute floor(sqrt(B^2-4ac))
1846 ConstantUInt *SqrtVal =
1847 cast<ConstantUInt>(ConstantExpr::getCast(SqrtTerm,
1848 SqrtTerm->getType()->getUnsignedVersion()));
1849 uint64_t SqrtValV = SqrtVal->getValue();
Chris Lattnerea9e0052004-04-05 19:05:15 +00001850 uint64_t SqrtValV2 = (uint64_t)sqrt(SqrtValV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001851 // The square root might not be precise for arbitrary 64-bit integer
1852 // values. Do some sanity checks to ensure it's correct.
1853 if (SqrtValV2*SqrtValV2 > SqrtValV ||
1854 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
1855 SCEV *CNC = new SCEVCouldNotCompute();
1856 return std::make_pair(CNC, CNC);
1857 }
1858
1859 SqrtVal = ConstantUInt::get(Type::ULongTy, SqrtValV2);
1860 SqrtTerm = ConstantExpr::getCast(SqrtVal, SqrtTerm->getType());
1861
1862 Constant *NegB = ConstantExpr::getNeg(B);
1863 Constant *TwoA = ConstantExpr::getMul(A, Two);
1864
1865 // The divisions must be performed as signed divisions.
1866 const Type *SignedTy = NegB->getType()->getSignedVersion();
1867 NegB = ConstantExpr::getCast(NegB, SignedTy);
1868 TwoA = ConstantExpr::getCast(TwoA, SignedTy);
1869 SqrtTerm = ConstantExpr::getCast(SqrtTerm, SignedTy);
1870
1871 Constant *Solution1 =
1872 ConstantExpr::getDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
1873 Constant *Solution2 =
1874 ConstantExpr::getDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
1875 return std::make_pair(SCEVUnknown::get(Solution1),
1876 SCEVUnknown::get(Solution2));
1877}
1878
1879/// HowFarToZero - Return the number of times a backedge comparing the specified
1880/// value to zero will execute. If not computable, return UnknownValue
1881SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
1882 // If the value is a constant
1883 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
1884 // If the value is already zero, the branch will execute zero times.
1885 if (C->getValue()->isNullValue()) return C;
1886 return UnknownValue; // Otherwise it will loop infinitely.
1887 }
1888
1889 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
1890 if (!AddRec || AddRec->getLoop() != L)
1891 return UnknownValue;
1892
1893 if (AddRec->isAffine()) {
1894 // If this is an affine expression the execution count of this branch is
1895 // equal to:
1896 //
1897 // (0 - Start/Step) iff Start % Step == 0
1898 //
1899 // Get the initial value for the loop.
1900 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
1901 SCEVHandle Step = AddRec->getOperand(1);
1902
1903 Step = getSCEVAtScope(Step, L->getParentLoop());
1904
1905 // Figure out if Start % Step == 0.
1906 // FIXME: We should add DivExpr and RemExpr operations to our AST.
1907 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
1908 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
1909 return getNegativeSCEV(Start); // 0 - Start/1 == -Start
1910 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
1911 return Start; // 0 - Start/-1 == Start
1912
1913 // Check to see if Start is divisible by SC with no remainder.
1914 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
1915 ConstantInt *StartCC = StartC->getValue();
1916 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
1917 Constant *Rem = ConstantExpr::getRem(StartNegC, StepC->getValue());
1918 if (Rem->isNullValue()) {
1919 Constant *Result =ConstantExpr::getDiv(StartNegC,StepC->getValue());
1920 return SCEVUnknown::get(Result);
1921 }
1922 }
1923 }
1924 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
1925 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
1926 // the quadratic equation to solve it.
1927 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
1928 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
1929 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
1930 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001931#if 0
Chris Lattner53e677a2004-04-02 20:23:17 +00001932 std::cerr << "HFTZ: " << *V << " - sol#1: " << *R1
1933 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001934#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00001935 // Pick the smallest positive root value.
1936 assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?");
1937 if (ConstantBool *CB =
1938 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
1939 R2->getValue()))) {
1940 if (CB != ConstantBool::True)
1941 std::swap(R1, R2); // R1 is the minimum root now.
1942
1943 // We can only use this value if the chrec ends up with an exact zero
1944 // value at this index. When solving for "X*X != 5", for example, we
1945 // should not accept a root of 2.
1946 SCEVHandle Val = AddRec->evaluateAtIteration(R1);
1947 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
1948 if (EvalVal->getValue()->isNullValue())
1949 return R1; // We found a quadratic root!
1950 }
1951 }
1952 }
1953
1954 return UnknownValue;
1955}
1956
1957/// HowFarToNonZero - Return the number of times a backedge checking the
1958/// specified value for nonzero will execute. If not computable, return
1959/// UnknownValue
1960SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
1961 // Loops that look like: while (X == 0) are very strange indeed. We don't
1962 // handle them yet except for the trivial case. This could be expanded in the
1963 // future as needed.
1964
1965 // If the value is a constant, check to see if it is known to be non-zero
1966 // already. If so, the backedge will execute zero times.
1967 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
1968 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
1969 Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero);
1970 if (NonZero == ConstantBool::True)
1971 return getSCEV(Zero);
1972 return UnknownValue; // Otherwise it will loop infinitely.
1973 }
1974
1975 // We could implement others, but I really doubt anyone writes loops like
1976 // this, and if they did, they would already be constant folded.
1977 return UnknownValue;
1978}
1979
1980static ConstantInt *
1981EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1982 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1983 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1984 assert(isa<SCEVConstant>(Val) &&
1985 "Evaluation of SCEV at constant didn't fold correctly?");
1986 return cast<SCEVConstant>(Val)->getValue();
1987}
1988
1989
1990/// getNumIterationsInRange - Return the number of iterations of this loop that
1991/// produce values in the specified constant range. Another way of looking at
1992/// this is that it returns the first iteration number where the value is not in
1993/// the condition, thus computing the exit count. If the iteration count can't
1994/// be computed, an instance of SCEVCouldNotCompute is returned.
1995SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const {
1996 if (Range.isFullSet()) // Infinite loop.
1997 return new SCEVCouldNotCompute();
1998
1999 // If the start is a non-zero constant, shift the range to simplify things.
2000 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2001 if (!SC->getValue()->isNullValue()) {
2002 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Chris Lattnerb06432c2004-04-23 21:29:03 +00002003 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002004 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2005 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2006 return ShiftedAddRec->getNumIterationsInRange(
2007 Range.subtract(SC->getValue()));
2008 // This is strange and shouldn't happen.
2009 return new SCEVCouldNotCompute();
2010 }
2011
2012 // The only time we can solve this is when we have all constant indices.
2013 // Otherwise, we cannot determine the overflow conditions.
2014 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2015 if (!isa<SCEVConstant>(getOperand(i)))
2016 return new SCEVCouldNotCompute();
2017
2018
2019 // Okay at this point we know that all elements of the chrec are constants and
2020 // that the start element is zero.
2021
2022 // First check to see if the range contains zero. If not, the first
2023 // iteration exits.
2024 ConstantInt *Zero = ConstantInt::get(getType(), 0);
2025 if (!Range.contains(Zero)) return SCEVConstant::get(Zero);
2026
2027 if (isAffine()) {
2028 // If this is an affine expression then we have this situation:
2029 // Solve {0,+,A} in Range === Ax in Range
2030
2031 // Since we know that zero is in the range, we know that the upper value of
2032 // the range must be the first possible exit value. Also note that we
2033 // already checked for a full range.
2034 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
2035 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue();
2036 ConstantInt *One = ConstantInt::get(getType(), 1);
2037
2038 // The exit value should be (Upper+A-1)/A.
2039 Constant *ExitValue = Upper;
2040 if (A != One) {
2041 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
2042 ExitValue = ConstantExpr::getDiv(ExitValue, A);
2043 }
2044 assert(isa<ConstantInt>(ExitValue) &&
2045 "Constant folding of integers not implemented?");
2046
2047 // Evaluate at the exit value. If we really did fall out of the valid
2048 // range, then we computed our trip count, otherwise wrap around or other
2049 // things must have happened.
2050 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
2051 if (Range.contains(Val))
2052 return new SCEVCouldNotCompute(); // Something strange happened
2053
2054 // Ensure that the previous value is in the range. This is a sanity check.
2055 assert(Range.contains(EvaluateConstantChrecAtConstant(this,
2056 ConstantExpr::getSub(ExitValue, One))) &&
2057 "Linear scev computation is off in a bad way!");
2058 return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2059 } else if (isQuadratic()) {
2060 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2061 // quadratic equation to solve it. To do this, we must frame our problem in
2062 // terms of figuring out when zero is crossed, instead of when
2063 // Range.getUpper() is crossed.
2064 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
2065 NewOps[0] = getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
2066 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2067
2068 // Next, solve the constructed addrec
2069 std::pair<SCEVHandle,SCEVHandle> Roots =
2070 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2071 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2072 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2073 if (R1) {
2074 // Pick the smallest positive root value.
2075 assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?");
2076 if (ConstantBool *CB =
2077 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2078 R2->getValue()))) {
2079 if (CB != ConstantBool::True)
2080 std::swap(R1, R2); // R1 is the minimum root now.
2081
2082 // Make sure the root is not off by one. The returned iteration should
2083 // not be in the range, but the previous one should be. When solving
2084 // for "X*X < 5", for example, we should not return a root of 2.
2085 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2086 R1->getValue());
2087 if (Range.contains(R1Val)) {
2088 // The next iteration must be out of the range...
2089 Constant *NextVal =
2090 ConstantExpr::getAdd(R1->getValue(),
2091 ConstantInt::get(R1->getType(), 1));
2092
2093 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2094 if (!Range.contains(R1Val))
2095 return SCEVUnknown::get(NextVal);
2096 return new SCEVCouldNotCompute(); // Something strange happened
2097 }
2098
2099 // If R1 was not in the range, then it is a good return value. Make
2100 // sure that R1-1 WAS in the range though, just in case.
2101 Constant *NextVal =
2102 ConstantExpr::getSub(R1->getValue(),
2103 ConstantInt::get(R1->getType(), 1));
2104 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2105 if (Range.contains(R1Val))
2106 return R1;
2107 return new SCEVCouldNotCompute(); // Something strange happened
2108 }
2109 }
2110 }
2111
2112 // Fallback, if this is a general polynomial, figure out the progression
2113 // through brute force: evaluate until we find an iteration that fails the
2114 // test. This is likely to be slow, but getting an accurate trip count is
2115 // incredibly important, we will be able to simplify the exit test a lot, and
2116 // we are almost guaranteed to get a trip count in this case.
2117 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2118 ConstantInt *One = ConstantInt::get(getType(), 1);
2119 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2120 do {
2121 ++NumBruteForceEvaluations;
2122 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2123 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2124 return new SCEVCouldNotCompute();
2125
2126 // Check to see if we found the value!
2127 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()))
2128 return SCEVConstant::get(TestVal);
2129
2130 // Increment to test the next index.
2131 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
2132 } while (TestVal != EndVal);
2133
2134 return new SCEVCouldNotCompute();
2135}
2136
2137
2138
2139//===----------------------------------------------------------------------===//
2140// ScalarEvolution Class Implementation
2141//===----------------------------------------------------------------------===//
2142
2143bool ScalarEvolution::runOnFunction(Function &F) {
2144 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2145 return false;
2146}
2147
2148void ScalarEvolution::releaseMemory() {
2149 delete (ScalarEvolutionsImpl*)Impl;
2150 Impl = 0;
2151}
2152
2153void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2154 AU.setPreservesAll();
2155 AU.addRequiredID(LoopSimplifyID);
2156 AU.addRequiredTransitive<LoopInfo>();
2157}
2158
2159SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2160 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2161}
2162
2163SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2164 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2165}
2166
2167bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2168 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2169}
2170
2171SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2172 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2173}
2174
2175void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2176 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2177}
2178
Chris Lattner53e677a2004-04-02 20:23:17 +00002179static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
2180 const Loop *L) {
2181 // Print all inner loops first
2182 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2183 PrintLoopInfo(OS, SE, *I);
2184
2185 std::cerr << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002186
2187 std::vector<BasicBlock*> ExitBlocks;
2188 L->getExitBlocks(ExitBlocks);
2189 if (ExitBlocks.size() != 1)
Chris Lattner53e677a2004-04-02 20:23:17 +00002190 std::cerr << "<multiple exits> ";
2191
2192 if (SE->hasLoopInvariantIterationCount(L)) {
2193 std::cerr << *SE->getIterationCount(L) << " iterations! ";
2194 } else {
2195 std::cerr << "Unpredictable iteration count. ";
2196 }
2197
2198 std::cerr << "\n";
2199}
2200
2201void ScalarEvolution::print(std::ostream &OS) const {
2202 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2203 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2204
2205 OS << "Classifying expressions for: " << F.getName() << "\n";
2206 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner6ffe5512004-04-27 15:13:33 +00002207 if (I->getType()->isInteger()) {
2208 OS << *I;
Chris Lattner53e677a2004-04-02 20:23:17 +00002209 OS << " --> ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002210 SCEVHandle SV = getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00002211 SV->print(OS);
2212 OS << "\t\t";
2213
Chris Lattner6ffe5512004-04-27 15:13:33 +00002214 if ((*I).getType()->isIntegral()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002215 ConstantRange Bounds = SV->getValueRange();
2216 if (!Bounds.isFullSet())
2217 OS << "Bounds: " << Bounds << " ";
2218 }
2219
Chris Lattner6ffe5512004-04-27 15:13:33 +00002220 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002221 OS << "Exits: ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002222 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002223 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2224 OS << "<<Unknown>>";
2225 } else {
2226 OS << *ExitValue;
2227 }
2228 }
2229
2230
2231 OS << "\n";
2232 }
2233
2234 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2235 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2236 PrintLoopInfo(OS, this, *I);
2237}
2238