blob: 7d03eb9a94eeeecf5d406e09d0ab1e0d97dca6ac [file] [log] [blame]
Chris Lattner53e677a2004-04-02 20:23:17 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattner53e677a2004-04-02 20:23:17 +00003// 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.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattner53e677a2004-04-02 20:23:17 +00008//===----------------------------------------------------------------------===//
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.
Misha Brukman2b37d7c2005-04-21 21:13:18 +000031//
Chris Lattner53e677a2004-04-02 20:23:17 +000032// 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 Lattner3b27d682006-12-19 22:30:33 +000062#define DEBUG_TYPE "scalar-evolution"
Chris Lattner0a7f98c2004-04-15 15:07:24 +000063#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000064#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000066#include "llvm/GlobalVariable.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000067#include "llvm/Instructions.h"
John Criswella1156432005-10-27 15:54:34 +000068#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000069#include "llvm/Analysis/LoopInfo.h"
70#include "llvm/Assembly/Writer.h"
71#include "llvm/Transforms/Scalar.h"
72#include "llvm/Support/CFG.h"
Chris Lattner95255282006-06-28 23:17:24 +000073#include "llvm/Support/CommandLine.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000074#include "llvm/Support/Compiler.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000075#include "llvm/Support/ConstantRange.h"
76#include "llvm/Support/InstIterator.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000077#include "llvm/Support/ManagedStatic.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000078#include "llvm/Support/MathExtras.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000079#include "llvm/Support/Streams.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000080#include "llvm/ADT/Statistic.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000081#include <ostream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000082#include <algorithm>
Jeff Cohen97af7512006-12-02 02:22:01 +000083#include <cmath>
Chris Lattner53e677a2004-04-02 20:23:17 +000084using namespace llvm;
85
Chris Lattner3b27d682006-12-19 22:30:33 +000086STATISTIC(NumBruteForceEvaluations,
87 "Number of brute force evaluations needed to "
88 "calculate high-order polynomial exit values");
89STATISTIC(NumArrayLenItCounts,
90 "Number of trip counts computed with array length");
91STATISTIC(NumTripCountsComputed,
92 "Number of loops with predictable loop counts");
93STATISTIC(NumTripCountsNotComputed,
94 "Number of loops without predictable loop counts");
95STATISTIC(NumBruteForceTripCountsComputed,
96 "Number of loops with trip counts computed by force");
97
98cl::opt<unsigned>
99MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
100 cl::desc("Maximum number of iterations SCEV will "
101 "symbolically execute a constant derived loop"),
102 cl::init(100));
103
Chris Lattner53e677a2004-04-02 20:23:17 +0000104namespace {
Chris Lattner5d8925c2006-08-27 22:30:17 +0000105 RegisterPass<ScalarEvolution>
Chris Lattner45a1cf82004-04-19 03:42:32 +0000106 R("scalar-evolution", "Scalar Evolution Analysis");
Chris Lattner53e677a2004-04-02 20:23:17 +0000107}
108
109//===----------------------------------------------------------------------===//
110// SCEV class definitions
111//===----------------------------------------------------------------------===//
112
113//===----------------------------------------------------------------------===//
114// Implementation of the SCEV class.
115//
Chris Lattner53e677a2004-04-02 20:23:17 +0000116SCEV::~SCEV() {}
117void SCEV::dump() const {
Bill Wendlinge8156192006-12-07 01:30:32 +0000118 print(cerr);
Chris Lattner53e677a2004-04-02 20:23:17 +0000119}
120
121/// getValueRange - Return the tightest constant bounds that this value is
122/// known to have. This method is only valid on integer SCEV objects.
123ConstantRange SCEV::getValueRange() const {
124 const Type *Ty = getType();
125 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
126 Ty = Ty->getUnsignedVersion();
127 // Default to a full range if no better information is available.
128 return ConstantRange(getType());
129}
130
131
132SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
133
134bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
135 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000136 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000137}
138
139const Type *SCEVCouldNotCompute::getType() const {
140 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000141 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000142}
143
144bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
145 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
146 return false;
147}
148
Chris Lattner4dc534c2005-02-13 04:37:18 +0000149SCEVHandle SCEVCouldNotCompute::
150replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
151 const SCEVHandle &Conc) const {
152 return this;
153}
154
Chris Lattner53e677a2004-04-02 20:23:17 +0000155void SCEVCouldNotCompute::print(std::ostream &OS) const {
156 OS << "***COULDNOTCOMPUTE***";
157}
158
159bool SCEVCouldNotCompute::classof(const SCEV *S) {
160 return S->getSCEVType() == scCouldNotCompute;
161}
162
163
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000164// SCEVConstants - Only allow the creation of one SCEVConstant for any
165// particular value. Don't use a SCEVHandle here, or else the object will
166// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000167static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000168
Chris Lattner53e677a2004-04-02 20:23:17 +0000169
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000170SCEVConstant::~SCEVConstant() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000171 SCEVConstants->erase(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000172}
Chris Lattner53e677a2004-04-02 20:23:17 +0000173
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000174SCEVHandle SCEVConstant::get(ConstantInt *V) {
175 // Make sure that SCEVConstant instances are all unsigned.
176 if (V->getType()->isSigned()) {
177 const Type *NewTy = V->getType()->getUnsignedVersion();
Reid Spencer14bab5d2006-12-04 17:05:42 +0000178 V = cast<ConstantInt>(
Reid Spencer7858b332006-12-05 19:14:13 +0000179 ConstantExpr::getBitCast(V, NewTy));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000180 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000181
Chris Lattnerb3364092006-10-04 21:49:37 +0000182 SCEVConstant *&R = (*SCEVConstants)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000183 if (R == 0) R = new SCEVConstant(V);
184 return R;
185}
Chris Lattner53e677a2004-04-02 20:23:17 +0000186
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000187ConstantRange SCEVConstant::getValueRange() const {
188 return ConstantRange(V);
189}
Chris Lattner53e677a2004-04-02 20:23:17 +0000190
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000191const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000192
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000193void SCEVConstant::print(std::ostream &OS) const {
194 WriteAsOperand(OS, V, false);
195}
Chris Lattner53e677a2004-04-02 20:23:17 +0000196
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000197// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
198// particular input. Don't use a SCEVHandle here, or else the object will
199// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000200static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
201 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000202
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000203SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
204 : SCEV(scTruncate), Op(op), Ty(ty) {
205 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000206 "Cannot truncate non-integer value!");
207 assert(Op->getType()->getPrimitiveSize() > Ty->getPrimitiveSize() &&
208 "This is not a truncating conversion!");
209}
Chris Lattner53e677a2004-04-02 20:23:17 +0000210
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000211SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000212 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000213}
Chris Lattner53e677a2004-04-02 20:23:17 +0000214
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000215ConstantRange SCEVTruncateExpr::getValueRange() const {
216 return getOperand()->getValueRange().truncate(getType());
217}
Chris Lattner53e677a2004-04-02 20:23:17 +0000218
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000219void SCEVTruncateExpr::print(std::ostream &OS) const {
220 OS << "(truncate " << *Op << " to " << *Ty << ")";
221}
222
223// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
224// particular input. Don't use a SCEVHandle here, or else the object will never
225// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000226static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
227 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000228
229SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Reid Spencer48d8a702006-11-01 21:53:12 +0000230 : SCEV(scZeroExtend), Op(op), Ty(ty) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000231 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000232 "Cannot zero extend non-integer value!");
233 assert(Op->getType()->getPrimitiveSize() < Ty->getPrimitiveSize() &&
234 "This is not an extending conversion!");
235}
236
237SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000238 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000239}
240
241ConstantRange SCEVZeroExtendExpr::getValueRange() const {
242 return getOperand()->getValueRange().zeroExtend(getType());
243}
244
245void SCEVZeroExtendExpr::print(std::ostream &OS) const {
246 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
247}
248
249// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
250// particular input. Don't use a SCEVHandle here, or else the object will never
251// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000252static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
253 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000254
255SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000256 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
257 std::vector<SCEV*>(Operands.begin(),
258 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000259}
260
261void SCEVCommutativeExpr::print(std::ostream &OS) const {
262 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
263 const char *OpStr = getOperationStr();
264 OS << "(" << *Operands[0];
265 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
266 OS << OpStr << *Operands[i];
267 OS << ")";
268}
269
Chris Lattner4dc534c2005-02-13 04:37:18 +0000270SCEVHandle SCEVCommutativeExpr::
271replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
272 const SCEVHandle &Conc) const {
273 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
274 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
275 if (H != getOperand(i)) {
276 std::vector<SCEVHandle> NewOps;
277 NewOps.reserve(getNumOperands());
278 for (unsigned j = 0; j != i; ++j)
279 NewOps.push_back(getOperand(j));
280 NewOps.push_back(H);
281 for (++i; i != e; ++i)
282 NewOps.push_back(getOperand(i)->
283 replaceSymbolicValuesWithConcrete(Sym, Conc));
284
285 if (isa<SCEVAddExpr>(this))
286 return SCEVAddExpr::get(NewOps);
287 else if (isa<SCEVMulExpr>(this))
288 return SCEVMulExpr::get(NewOps);
289 else
290 assert(0 && "Unknown commutative expr!");
291 }
292 }
293 return this;
294}
295
296
Chris Lattner60a05cc2006-04-01 04:48:52 +0000297// SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000298// input. Don't use a SCEVHandle here, or else the object will never be
299// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000300static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
301 SCEVSDivExpr*> > SCEVSDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000302
Chris Lattner60a05cc2006-04-01 04:48:52 +0000303SCEVSDivExpr::~SCEVSDivExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000304 SCEVSDivs->erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000305}
306
Chris Lattner60a05cc2006-04-01 04:48:52 +0000307void SCEVSDivExpr::print(std::ostream &OS) const {
308 OS << "(" << *LHS << " /s " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000309}
310
Chris Lattner60a05cc2006-04-01 04:48:52 +0000311const Type *SCEVSDivExpr::getType() const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000312 const Type *Ty = LHS->getType();
Chris Lattner60a05cc2006-04-01 04:48:52 +0000313 if (Ty->isUnsigned()) Ty = Ty->getSignedVersion();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000314 return Ty;
315}
316
317// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
318// particular input. Don't use a SCEVHandle here, or else the object will never
319// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000320static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
321 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000322
323SCEVAddRecExpr::~SCEVAddRecExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000324 SCEVAddRecExprs->erase(std::make_pair(L,
325 std::vector<SCEV*>(Operands.begin(),
326 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000327}
328
Chris Lattner4dc534c2005-02-13 04:37:18 +0000329SCEVHandle SCEVAddRecExpr::
330replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
331 const SCEVHandle &Conc) const {
332 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
333 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
334 if (H != getOperand(i)) {
335 std::vector<SCEVHandle> NewOps;
336 NewOps.reserve(getNumOperands());
337 for (unsigned j = 0; j != i; ++j)
338 NewOps.push_back(getOperand(j));
339 NewOps.push_back(H);
340 for (++i; i != e; ++i)
341 NewOps.push_back(getOperand(i)->
342 replaceSymbolicValuesWithConcrete(Sym, Conc));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000343
Chris Lattner4dc534c2005-02-13 04:37:18 +0000344 return get(NewOps, L);
345 }
346 }
347 return this;
348}
349
350
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000351bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
352 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000353 // contain L and if the start is invariant.
354 return !QueryLoop->contains(L->getHeader()) &&
355 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000356}
357
358
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000359void SCEVAddRecExpr::print(std::ostream &OS) const {
360 OS << "{" << *Operands[0];
361 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
362 OS << ",+," << *Operands[i];
363 OS << "}<" << L->getHeader()->getName() + ">";
364}
Chris Lattner53e677a2004-04-02 20:23:17 +0000365
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000366// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
367// value. Don't use a SCEVHandle here, or else the object will never be
368// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000369static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000370
Chris Lattnerb3364092006-10-04 21:49:37 +0000371SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000372
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000373bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
374 // All non-instruction values are loop invariant. All instructions are loop
375 // invariant if they are not contained in the specified loop.
376 if (Instruction *I = dyn_cast<Instruction>(V))
377 return !L->contains(I->getParent());
378 return true;
379}
Chris Lattner53e677a2004-04-02 20:23:17 +0000380
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000381const Type *SCEVUnknown::getType() const {
382 return V->getType();
383}
Chris Lattner53e677a2004-04-02 20:23:17 +0000384
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000385void SCEVUnknown::print(std::ostream &OS) const {
386 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000387}
388
Chris Lattner8d741b82004-06-20 06:23:15 +0000389//===----------------------------------------------------------------------===//
390// SCEV Utilities
391//===----------------------------------------------------------------------===//
392
393namespace {
394 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
395 /// than the complexity of the RHS. This comparator is used to canonicalize
396 /// expressions.
Chris Lattner95255282006-06-28 23:17:24 +0000397 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Chris Lattner8d741b82004-06-20 06:23:15 +0000398 bool operator()(SCEV *LHS, SCEV *RHS) {
399 return LHS->getSCEVType() < RHS->getSCEVType();
400 }
401 };
402}
403
404/// GroupByComplexity - Given a list of SCEV objects, order them by their
405/// complexity, and group objects of the same complexity together by value.
406/// When this routine is finished, we know that any duplicates in the vector are
407/// consecutive and that complexity is monotonically increasing.
408///
409/// Note that we go take special precautions to ensure that we get determinstic
410/// results from this routine. In other words, we don't want the results of
411/// this to depend on where the addresses of various SCEV objects happened to
412/// land in memory.
413///
414static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
415 if (Ops.size() < 2) return; // Noop
416 if (Ops.size() == 2) {
417 // This is the common case, which also happens to be trivially simple.
418 // Special case it.
419 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
420 std::swap(Ops[0], Ops[1]);
421 return;
422 }
423
424 // Do the rough sort by complexity.
425 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
426
427 // Now that we are sorted by complexity, group elements of the same
428 // complexity. Note that this is, at worst, N^2, but the vector is likely to
429 // be extremely short in practice. Note that we take this approach because we
430 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000431 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000432 SCEV *S = Ops[i];
433 unsigned Complexity = S->getSCEVType();
434
435 // If there are any objects of the same complexity and same value as this
436 // one, group them.
437 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
438 if (Ops[j] == S) { // Found a duplicate.
439 // Move it to immediately after i'th element.
440 std::swap(Ops[i+1], Ops[j]);
441 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000442 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000443 }
444 }
445 }
446}
447
Chris Lattner53e677a2004-04-02 20:23:17 +0000448
Chris Lattner53e677a2004-04-02 20:23:17 +0000449
450//===----------------------------------------------------------------------===//
451// Simple SCEV method implementations
452//===----------------------------------------------------------------------===//
453
454/// getIntegerSCEV - Given an integer or FP type, create a constant for the
455/// specified signed integer value and return a SCEV for the constant.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000456SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000457 Constant *C;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000458 if (Val == 0)
Chris Lattner53e677a2004-04-02 20:23:17 +0000459 C = Constant::getNullValue(Ty);
460 else if (Ty->isFloatingPoint())
461 C = ConstantFP::get(Ty, Val);
462 else if (Ty->isSigned())
Reid Spencerb83eb642006-10-20 07:07:24 +0000463 C = ConstantInt::get(Ty, Val);
Chris Lattner53e677a2004-04-02 20:23:17 +0000464 else {
Reid Spencerb83eb642006-10-20 07:07:24 +0000465 C = ConstantInt::get(Ty->getSignedVersion(), Val);
Reid Spencer7858b332006-12-05 19:14:13 +0000466 C = ConstantExpr::getBitCast(C, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000467 }
468 return SCEVUnknown::get(C);
469}
470
471/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
472/// input value to the specified type. If the type must be extended, it is zero
473/// extended.
474static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
475 const Type *SrcTy = V->getType();
476 assert(SrcTy->isInteger() && Ty->isInteger() &&
477 "Cannot truncate or zero extend with non-integer arguments!");
478 if (SrcTy->getPrimitiveSize() == Ty->getPrimitiveSize())
479 return V; // No conversion
480 if (SrcTy->getPrimitiveSize() > Ty->getPrimitiveSize())
481 return SCEVTruncateExpr::get(V, Ty);
482 return SCEVZeroExtendExpr::get(V, Ty);
483}
484
485/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
486///
Chris Lattnerbac5b462005-03-09 05:34:41 +0000487SCEVHandle SCEV::getNegativeSCEV(const SCEVHandle &V) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000488 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
489 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000490
Chris Lattnerb06432c2004-04-23 21:29:03 +0000491 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
Chris Lattner53e677a2004-04-02 20:23:17 +0000492}
493
494/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
495///
Chris Lattnerbac5b462005-03-09 05:34:41 +0000496SCEVHandle SCEV::getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000497 // X - Y --> X + -Y
Chris Lattnerbac5b462005-03-09 05:34:41 +0000498 return SCEVAddExpr::get(LHS, SCEV::getNegativeSCEV(RHS));
Chris Lattner53e677a2004-04-02 20:23:17 +0000499}
500
501
Chris Lattner53e677a2004-04-02 20:23:17 +0000502/// PartialFact - Compute V!/(V-NumSteps)!
503static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
504 // Handle this case efficiently, it is common to have constant iteration
505 // counts while computing loop exit values.
506 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000507 uint64_t Val = SC->getValue()->getZExtValue();
Chris Lattner53e677a2004-04-02 20:23:17 +0000508 uint64_t Result = 1;
509 for (; NumSteps; --NumSteps)
510 Result *= Val-(NumSteps-1);
Reid Spencerb83eb642006-10-20 07:07:24 +0000511 Constant *Res = ConstantInt::get(Type::ULongTy, Result);
Reid Spencer14bab5d2006-12-04 17:05:42 +0000512 return SCEVUnknown::get(
Reid Spencer7858b332006-12-05 19:14:13 +0000513 ConstantExpr::getTruncOrBitCast(Res, V->getType()));
Chris Lattner53e677a2004-04-02 20:23:17 +0000514 }
515
516 const Type *Ty = V->getType();
517 if (NumSteps == 0)
Chris Lattnerb06432c2004-04-23 21:29:03 +0000518 return SCEVUnknown::getIntegerSCEV(1, Ty);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000519
Chris Lattner53e677a2004-04-02 20:23:17 +0000520 SCEVHandle Result = V;
521 for (unsigned i = 1; i != NumSteps; ++i)
Chris Lattnerbac5b462005-03-09 05:34:41 +0000522 Result = SCEVMulExpr::get(Result, SCEV::getMinusSCEV(V,
Chris Lattnerb06432c2004-04-23 21:29:03 +0000523 SCEVUnknown::getIntegerSCEV(i, Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000524 return Result;
525}
526
527
528/// evaluateAtIteration - Return the value of this chain of recurrences at
529/// the specified iteration number. We can evaluate this recurrence by
530/// multiplying each element in the chain by the binomial coefficient
531/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
532///
533/// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
534///
535/// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
536/// Is the binomial equation safe using modular arithmetic??
537///
538SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
539 SCEVHandle Result = getStart();
540 int Divisor = 1;
541 const Type *Ty = It->getType();
542 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
543 SCEVHandle BC = PartialFact(It, i);
544 Divisor *= i;
Chris Lattner60a05cc2006-04-01 04:48:52 +0000545 SCEVHandle Val = SCEVSDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
Chris Lattnerb06432c2004-04-23 21:29:03 +0000546 SCEVUnknown::getIntegerSCEV(Divisor,Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000547 Result = SCEVAddExpr::get(Result, Val);
548 }
549 return Result;
550}
551
552
553//===----------------------------------------------------------------------===//
554// SCEV Expression folder implementations
555//===----------------------------------------------------------------------===//
556
557SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
558 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Reid Spencer7858b332006-12-05 19:14:13 +0000559 return SCEVUnknown::get(
Reid Spencer315d0552006-12-05 22:39:58 +0000560 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000561
562 // If the input value is a chrec scev made out of constants, truncate
563 // all of the constants.
564 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
565 std::vector<SCEVHandle> Operands;
566 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
567 // FIXME: This should allow truncation of other expression types!
568 if (isa<SCEVConstant>(AddRec->getOperand(i)))
569 Operands.push_back(get(AddRec->getOperand(i), Ty));
570 else
571 break;
572 if (Operands.size() == AddRec->getNumOperands())
573 return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
574 }
575
Chris Lattnerb3364092006-10-04 21:49:37 +0000576 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000577 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
578 return Result;
579}
580
581SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
582 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Reid Spencer7858b332006-12-05 19:14:13 +0000583 return SCEVUnknown::get(
Reid Spencerd977d862006-12-12 23:36:14 +0000584 ConstantExpr::getZExt(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000585
586 // FIXME: If the input value is a chrec scev, and we can prove that the value
587 // did not overflow the old, smaller, value, we can zero extend all of the
588 // operands (often constants). This would allow analysis of something like
589 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
590
Chris Lattnerb3364092006-10-04 21:49:37 +0000591 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000592 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
593 return Result;
594}
595
596// get - Get a canonical add expression, or something simpler if possible.
597SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
598 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000599 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000600
601 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000602 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000603
604 // If there are any constants, fold them together.
605 unsigned Idx = 0;
606 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
607 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000608 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000609 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
610 // We found two constants, fold them together!
611 Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue());
612 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
613 Ops[0] = SCEVConstant::get(CI);
614 Ops.erase(Ops.begin()+1); // Erase the folded element
615 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000616 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000617 } else {
618 // If we couldn't fold the expression, move to the next constant. Note
619 // that this is impossible to happen in practice because we always
620 // constant fold constant ints to constant ints.
621 ++Idx;
622 }
623 }
624
625 // If we are left with a constant zero being added, strip it off.
626 if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
627 Ops.erase(Ops.begin());
628 --Idx;
629 }
630 }
631
Chris Lattner627018b2004-04-07 16:16:11 +0000632 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000633
Chris Lattner53e677a2004-04-02 20:23:17 +0000634 // Okay, check to see if the same value occurs in the operand list twice. If
635 // so, merge them together into an multiply expression. Since we sorted the
636 // list, these values are required to be adjacent.
637 const Type *Ty = Ops[0]->getType();
638 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
639 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
640 // Found a match, merge the two values into a multiply, and add any
641 // remaining values to the result.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000642 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000643 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
644 if (Ops.size() == 2)
645 return Mul;
646 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
647 Ops.push_back(Mul);
648 return SCEVAddExpr::get(Ops);
649 }
650
651 // Okay, now we know the first non-constant operand. If there are add
652 // operands they would be next.
653 if (Idx < Ops.size()) {
654 bool DeletedAdd = false;
655 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
656 // If we have an add, expand the add operands onto the end of the operands
657 // list.
658 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
659 Ops.erase(Ops.begin()+Idx);
660 DeletedAdd = true;
661 }
662
663 // If we deleted at least one add, we added operands to the end of the list,
664 // and they are not necessarily sorted. Recurse to resort and resimplify
665 // any operands we just aquired.
666 if (DeletedAdd)
667 return get(Ops);
668 }
669
670 // Skip over the add expression until we get to a multiply.
671 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
672 ++Idx;
673
674 // If we are adding something to a multiply expression, make sure the
675 // something is not already an operand of the multiply. If so, merge it into
676 // the multiply.
677 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
678 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
679 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
680 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
681 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000682 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000683 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
684 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
685 if (Mul->getNumOperands() != 2) {
686 // If the multiply has more than two operands, we must get the
687 // Y*Z term.
688 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
689 MulOps.erase(MulOps.begin()+MulOp);
690 InnerMul = SCEVMulExpr::get(MulOps);
691 }
Chris Lattnerb06432c2004-04-23 21:29:03 +0000692 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000693 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
694 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
695 if (Ops.size() == 2) return OuterMul;
696 if (AddOp < Idx) {
697 Ops.erase(Ops.begin()+AddOp);
698 Ops.erase(Ops.begin()+Idx-1);
699 } else {
700 Ops.erase(Ops.begin()+Idx);
701 Ops.erase(Ops.begin()+AddOp-1);
702 }
703 Ops.push_back(OuterMul);
704 return SCEVAddExpr::get(Ops);
705 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000706
Chris Lattner53e677a2004-04-02 20:23:17 +0000707 // Check this multiply against other multiplies being added together.
708 for (unsigned OtherMulIdx = Idx+1;
709 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
710 ++OtherMulIdx) {
711 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
712 // If MulOp occurs in OtherMul, we can fold the two multiplies
713 // together.
714 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
715 OMulOp != e; ++OMulOp)
716 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
717 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
718 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
719 if (Mul->getNumOperands() != 2) {
720 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
721 MulOps.erase(MulOps.begin()+MulOp);
722 InnerMul1 = SCEVMulExpr::get(MulOps);
723 }
724 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
725 if (OtherMul->getNumOperands() != 2) {
726 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
727 OtherMul->op_end());
728 MulOps.erase(MulOps.begin()+OMulOp);
729 InnerMul2 = SCEVMulExpr::get(MulOps);
730 }
731 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
732 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
733 if (Ops.size() == 2) return OuterMul;
734 Ops.erase(Ops.begin()+Idx);
735 Ops.erase(Ops.begin()+OtherMulIdx-1);
736 Ops.push_back(OuterMul);
737 return SCEVAddExpr::get(Ops);
738 }
739 }
740 }
741 }
742
743 // If there are any add recurrences in the operands list, see if any other
744 // added values are loop invariant. If so, we can fold them into the
745 // recurrence.
746 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
747 ++Idx;
748
749 // Scan over all recurrences, trying to fold loop invariants into them.
750 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
751 // Scan all of the other operands to this add and add them to the vector if
752 // they are loop invariant w.r.t. the recurrence.
753 std::vector<SCEVHandle> LIOps;
754 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
755 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
756 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
757 LIOps.push_back(Ops[i]);
758 Ops.erase(Ops.begin()+i);
759 --i; --e;
760 }
761
762 // If we found some loop invariants, fold them into the recurrence.
763 if (!LIOps.empty()) {
764 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
765 LIOps.push_back(AddRec->getStart());
766
767 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
768 AddRecOps[0] = SCEVAddExpr::get(LIOps);
769
770 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
771 // If all of the other operands were loop invariant, we are done.
772 if (Ops.size() == 1) return NewRec;
773
774 // Otherwise, add the folded AddRec by the non-liv parts.
775 for (unsigned i = 0;; ++i)
776 if (Ops[i] == AddRec) {
777 Ops[i] = NewRec;
778 break;
779 }
780 return SCEVAddExpr::get(Ops);
781 }
782
783 // Okay, if there weren't any loop invariants to be folded, check to see if
784 // there are multiple AddRec's with the same loop induction variable being
785 // added together. If so, we can fold them.
786 for (unsigned OtherIdx = Idx+1;
787 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
788 if (OtherIdx != Idx) {
789 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
790 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
791 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
792 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
793 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
794 if (i >= NewOps.size()) {
795 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
796 OtherAddRec->op_end());
797 break;
798 }
799 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
800 }
801 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
802
803 if (Ops.size() == 2) return NewAddRec;
804
805 Ops.erase(Ops.begin()+Idx);
806 Ops.erase(Ops.begin()+OtherIdx-1);
807 Ops.push_back(NewAddRec);
808 return SCEVAddExpr::get(Ops);
809 }
810 }
811
812 // Otherwise couldn't fold anything into this recurrence. Move onto the
813 // next one.
814 }
815
816 // Okay, it looks like we really DO need an add expr. Check to see if we
817 // already have one, otherwise create a new one.
818 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000819 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
820 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000821 if (Result == 0) Result = new SCEVAddExpr(Ops);
822 return Result;
823}
824
825
826SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
827 assert(!Ops.empty() && "Cannot get empty mul!");
828
829 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000830 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000831
832 // If there are any constants, fold them together.
833 unsigned Idx = 0;
834 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
835
836 // C1*(C2+V) -> C1*C2 + C1*V
837 if (Ops.size() == 2)
838 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
839 if (Add->getNumOperands() == 2 &&
840 isa<SCEVConstant>(Add->getOperand(0)))
841 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
842 SCEVMulExpr::get(LHSC, Add->getOperand(1)));
843
844
845 ++Idx;
846 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
847 // We found two constants, fold them together!
848 Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue());
849 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
850 Ops[0] = SCEVConstant::get(CI);
851 Ops.erase(Ops.begin()+1); // Erase the folded element
852 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000853 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000854 } else {
855 // If we couldn't fold the expression, move to the next constant. Note
856 // that this is impossible to happen in practice because we always
857 // constant fold constant ints to constant ints.
858 ++Idx;
859 }
860 }
861
862 // If we are left with a constant one being multiplied, strip it off.
863 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
864 Ops.erase(Ops.begin());
865 --Idx;
866 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
867 // If we have a multiply of zero, it will always be zero.
868 return Ops[0];
869 }
870 }
871
872 // Skip over the add expression until we get to a multiply.
873 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
874 ++Idx;
875
876 if (Ops.size() == 1)
877 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000878
Chris Lattner53e677a2004-04-02 20:23:17 +0000879 // If there are mul operands inline them all into this expression.
880 if (Idx < Ops.size()) {
881 bool DeletedMul = false;
882 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
883 // If we have an mul, expand the mul operands onto the end of the operands
884 // list.
885 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
886 Ops.erase(Ops.begin()+Idx);
887 DeletedMul = true;
888 }
889
890 // If we deleted at least one mul, we added operands to the end of the list,
891 // and they are not necessarily sorted. Recurse to resort and resimplify
892 // any operands we just aquired.
893 if (DeletedMul)
894 return get(Ops);
895 }
896
897 // If there are any add recurrences in the operands list, see if any other
898 // added values are loop invariant. If so, we can fold them into the
899 // recurrence.
900 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
901 ++Idx;
902
903 // Scan over all recurrences, trying to fold loop invariants into them.
904 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
905 // Scan all of the other operands to this mul and add them to the vector if
906 // they are loop invariant w.r.t. the recurrence.
907 std::vector<SCEVHandle> LIOps;
908 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
909 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
910 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
911 LIOps.push_back(Ops[i]);
912 Ops.erase(Ops.begin()+i);
913 --i; --e;
914 }
915
916 // If we found some loop invariants, fold them into the recurrence.
917 if (!LIOps.empty()) {
918 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
919 std::vector<SCEVHandle> NewOps;
920 NewOps.reserve(AddRec->getNumOperands());
921 if (LIOps.size() == 1) {
922 SCEV *Scale = LIOps[0];
923 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
924 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
925 } else {
926 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
927 std::vector<SCEVHandle> MulOps(LIOps);
928 MulOps.push_back(AddRec->getOperand(i));
929 NewOps.push_back(SCEVMulExpr::get(MulOps));
930 }
931 }
932
933 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
934
935 // If all of the other operands were loop invariant, we are done.
936 if (Ops.size() == 1) return NewRec;
937
938 // Otherwise, multiply the folded AddRec by the non-liv parts.
939 for (unsigned i = 0;; ++i)
940 if (Ops[i] == AddRec) {
941 Ops[i] = NewRec;
942 break;
943 }
944 return SCEVMulExpr::get(Ops);
945 }
946
947 // Okay, if there weren't any loop invariants to be folded, check to see if
948 // there are multiple AddRec's with the same loop induction variable being
949 // multiplied together. If so, we can fold them.
950 for (unsigned OtherIdx = Idx+1;
951 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
952 if (OtherIdx != Idx) {
953 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
954 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
955 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
956 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
957 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
958 G->getStart());
959 SCEVHandle B = F->getStepRecurrence();
960 SCEVHandle D = G->getStepRecurrence();
961 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
962 SCEVMulExpr::get(G, B),
963 SCEVMulExpr::get(B, D));
964 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
965 F->getLoop());
966 if (Ops.size() == 2) return NewAddRec;
967
968 Ops.erase(Ops.begin()+Idx);
969 Ops.erase(Ops.begin()+OtherIdx-1);
970 Ops.push_back(NewAddRec);
971 return SCEVMulExpr::get(Ops);
972 }
973 }
974
975 // Otherwise couldn't fold anything into this recurrence. Move onto the
976 // next one.
977 }
978
979 // Okay, it looks like we really DO need an mul expr. Check to see if we
980 // already have one, otherwise create a new one.
981 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000982 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
983 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000984 if (Result == 0)
985 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000986 return Result;
987}
988
Chris Lattner60a05cc2006-04-01 04:48:52 +0000989SCEVHandle SCEVSDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000990 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
991 if (RHSC->getValue()->equalsInt(1))
Reid Spencer1628cec2006-10-26 06:15:43 +0000992 return LHS; // X sdiv 1 --> x
Chris Lattner53e677a2004-04-02 20:23:17 +0000993 if (RHSC->getValue()->isAllOnesValue())
Reid Spencer1628cec2006-10-26 06:15:43 +0000994 return SCEV::getNegativeSCEV(LHS); // X sdiv -1 --> -x
Chris Lattner53e677a2004-04-02 20:23:17 +0000995
996 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
997 Constant *LHSCV = LHSC->getValue();
998 Constant *RHSCV = RHSC->getValue();
Reid Spencer1628cec2006-10-26 06:15:43 +0000999 return SCEVUnknown::get(ConstantExpr::getSDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001000 }
1001 }
1002
1003 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1004
Chris Lattnerb3364092006-10-04 21:49:37 +00001005 SCEVSDivExpr *&Result = (*SCEVSDivs)[std::make_pair(LHS, RHS)];
Chris Lattner60a05cc2006-04-01 04:48:52 +00001006 if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001007 return Result;
1008}
1009
1010
1011/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1012/// specified loop. Simplify the expression as much as possible.
1013SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
1014 const SCEVHandle &Step, const Loop *L) {
1015 std::vector<SCEVHandle> Operands;
1016 Operands.push_back(Start);
1017 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1018 if (StepChrec->getLoop() == L) {
1019 Operands.insert(Operands.end(), StepChrec->op_begin(),
1020 StepChrec->op_end());
1021 return get(Operands, L);
1022 }
1023
1024 Operands.push_back(Step);
1025 return get(Operands, L);
1026}
1027
1028/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1029/// specified loop. Simplify the expression as much as possible.
1030SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
1031 const Loop *L) {
1032 if (Operands.size() == 1) return Operands[0];
1033
1034 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
1035 if (StepC->getValue()->isNullValue()) {
1036 Operands.pop_back();
1037 return get(Operands, L); // { X,+,0 } --> X
1038 }
1039
1040 SCEVAddRecExpr *&Result =
Chris Lattnerb3364092006-10-04 21:49:37 +00001041 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1042 Operands.end()))];
Chris Lattner53e677a2004-04-02 20:23:17 +00001043 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1044 return Result;
1045}
1046
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001047SCEVHandle SCEVUnknown::get(Value *V) {
1048 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1049 return SCEVConstant::get(CI);
Chris Lattnerb3364092006-10-04 21:49:37 +00001050 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001051 if (Result == 0) Result = new SCEVUnknown(V);
1052 return Result;
1053}
1054
Chris Lattner53e677a2004-04-02 20:23:17 +00001055
1056//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001057// ScalarEvolutionsImpl Definition and Implementation
1058//===----------------------------------------------------------------------===//
1059//
1060/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1061/// evolution code.
1062///
1063namespace {
Chris Lattner95255282006-06-28 23:17:24 +00001064 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Chris Lattner53e677a2004-04-02 20:23:17 +00001065 /// F - The function we are analyzing.
1066 ///
1067 Function &F;
1068
1069 /// LI - The loop information for the function we are currently analyzing.
1070 ///
1071 LoopInfo &LI;
1072
1073 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1074 /// things.
1075 SCEVHandle UnknownValue;
1076
1077 /// Scalars - This is a cache of the scalars we have analyzed so far.
1078 ///
1079 std::map<Value*, SCEVHandle> Scalars;
1080
1081 /// IterationCounts - Cache the iteration count of the loops for this
1082 /// function as they are computed.
1083 std::map<const Loop*, SCEVHandle> IterationCounts;
1084
Chris Lattner3221ad02004-04-17 22:58:41 +00001085 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1086 /// the PHI instructions that we attempt to compute constant evolutions for.
1087 /// This allows us to avoid potentially expensive recomputation of these
1088 /// properties. An instruction maps to null if we are unable to compute its
1089 /// exit value.
1090 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001091
Chris Lattner53e677a2004-04-02 20:23:17 +00001092 public:
1093 ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1094 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1095
1096 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1097 /// expression and create a new one.
1098 SCEVHandle getSCEV(Value *V);
1099
Chris Lattnera0740fb2005-08-09 23:36:33 +00001100 /// hasSCEV - Return true if the SCEV for this value has already been
1101 /// computed.
1102 bool hasSCEV(Value *V) const {
1103 return Scalars.count(V);
1104 }
1105
1106 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1107 /// the specified value.
1108 void setSCEV(Value *V, const SCEVHandle &H) {
1109 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1110 assert(isNew && "This entry already existed!");
1111 }
1112
1113
Chris Lattner53e677a2004-04-02 20:23:17 +00001114 /// getSCEVAtScope - Compute the value of the specified expression within
1115 /// the indicated loop (which may be null to indicate in no loop). If the
1116 /// expression cannot be evaluated, return UnknownValue itself.
1117 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1118
1119
1120 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1121 /// an analyzable loop-invariant iteration count.
1122 bool hasLoopInvariantIterationCount(const Loop *L);
1123
1124 /// getIterationCount - If the specified loop has a predictable iteration
1125 /// count, return it. Note that it is not valid to call this method on a
1126 /// loop without a loop-invariant iteration count.
1127 SCEVHandle getIterationCount(const Loop *L);
1128
1129 /// deleteInstructionFromRecords - This method should be called by the
1130 /// client before it removes an instruction from the program, to make sure
1131 /// that no dangling references are left around.
1132 void deleteInstructionFromRecords(Instruction *I);
1133
1134 private:
1135 /// createSCEV - We know that there is no SCEV for the specified value.
1136 /// Analyze the expression.
1137 SCEVHandle createSCEV(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001138
1139 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1140 /// SCEVs.
1141 SCEVHandle createNodeForPHI(PHINode *PN);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001142
1143 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1144 /// for the specified instruction and replaces any references to the
1145 /// symbolic value SymName with the specified value. This is used during
1146 /// PHI resolution.
1147 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1148 const SCEVHandle &SymName,
1149 const SCEVHandle &NewVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00001150
1151 /// ComputeIterationCount - Compute the number of times the specified loop
1152 /// will iterate.
1153 SCEVHandle ComputeIterationCount(const Loop *L);
1154
Chris Lattner673e02b2004-10-12 01:49:27 +00001155 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1156 /// 'setcc load X, cst', try to se if we can compute the trip count.
1157 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1158 Constant *RHS,
1159 const Loop *L,
1160 unsigned SetCCOpcode);
1161
Chris Lattner7980fb92004-04-17 18:36:24 +00001162 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1163 /// constant number of times (the condition evolves only from constants),
1164 /// try to evaluate a few iterations of the loop until we get the exit
1165 /// condition gets a value of ExitWhen (true or false). If we cannot
1166 /// evaluate the trip count of the loop, return UnknownValue.
1167 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1168 bool ExitWhen);
1169
Chris Lattner53e677a2004-04-02 20:23:17 +00001170 /// HowFarToZero - Return the number of times a backedge comparing the
1171 /// specified value to zero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001172 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001173 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1174
1175 /// HowFarToNonZero - Return the number of times a backedge checking the
1176 /// specified value for nonzero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001177 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001178 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattner3221ad02004-04-17 22:58:41 +00001179
Chris Lattnerdb25de42005-08-15 23:33:51 +00001180 /// HowManyLessThans - Return the number of times a backedge containing the
1181 /// specified less-than comparison will execute. If not computable, return
1182 /// UnknownValue.
1183 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L);
1184
Chris Lattner3221ad02004-04-17 22:58:41 +00001185 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1186 /// in the header of its containing loop, we know the loop executes a
1187 /// constant number of times, and the PHI node is just a recurrence
1188 /// involving constants, fold it.
1189 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its,
1190 const Loop *L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001191 };
1192}
1193
1194//===----------------------------------------------------------------------===//
1195// Basic SCEV Analysis and PHI Idiom Recognition Code
1196//
1197
1198/// deleteInstructionFromRecords - This method should be called by the
1199/// client before it removes an instruction from the program, to make sure
1200/// that no dangling references are left around.
1201void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
1202 Scalars.erase(I);
Chris Lattner3221ad02004-04-17 22:58:41 +00001203 if (PHINode *PN = dyn_cast<PHINode>(I))
1204 ConstantEvolutionLoopExitValue.erase(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001205}
1206
1207
1208/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1209/// expression and create a new one.
1210SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1211 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1212
1213 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1214 if (I != Scalars.end()) return I->second;
1215 SCEVHandle S = createSCEV(V);
1216 Scalars.insert(std::make_pair(V, S));
1217 return S;
1218}
1219
Chris Lattner4dc534c2005-02-13 04:37:18 +00001220/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1221/// the specified instruction and replaces any references to the symbolic value
1222/// SymName with the specified value. This is used during PHI resolution.
1223void ScalarEvolutionsImpl::
1224ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1225 const SCEVHandle &NewVal) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001226 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001227 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001228
Chris Lattner4dc534c2005-02-13 04:37:18 +00001229 SCEVHandle NV =
1230 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal);
1231 if (NV == SI->second) return; // No change.
1232
1233 SI->second = NV; // Update the scalars map!
1234
1235 // Any instruction values that use this instruction might also need to be
1236 // updated!
1237 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1238 UI != E; ++UI)
1239 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1240}
Chris Lattner53e677a2004-04-02 20:23:17 +00001241
1242/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1243/// a loop header, making it a potential recurrence, or it doesn't.
1244///
1245SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1246 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1247 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1248 if (L->getHeader() == PN->getParent()) {
1249 // If it lives in the loop header, it has two incoming values, one
1250 // from outside the loop, and one from inside.
1251 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1252 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001253
Chris Lattner53e677a2004-04-02 20:23:17 +00001254 // While we are analyzing this PHI node, handle its value symbolically.
1255 SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1256 assert(Scalars.find(PN) == Scalars.end() &&
1257 "PHI node already processed?");
1258 Scalars.insert(std::make_pair(PN, SymbolicName));
1259
1260 // Using this symbolic name for the PHI, analyze the value coming around
1261 // the back-edge.
1262 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1263
1264 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1265 // has a special value for the first iteration of the loop.
1266
1267 // If the value coming around the backedge is an add with the symbolic
1268 // value we just inserted, then we found a simple induction variable!
1269 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1270 // If there is a single occurrence of the symbolic value, replace it
1271 // with a recurrence.
1272 unsigned FoundIndex = Add->getNumOperands();
1273 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1274 if (Add->getOperand(i) == SymbolicName)
1275 if (FoundIndex == e) {
1276 FoundIndex = i;
1277 break;
1278 }
1279
1280 if (FoundIndex != Add->getNumOperands()) {
1281 // Create an add with everything but the specified operand.
1282 std::vector<SCEVHandle> Ops;
1283 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1284 if (i != FoundIndex)
1285 Ops.push_back(Add->getOperand(i));
1286 SCEVHandle Accum = SCEVAddExpr::get(Ops);
1287
1288 // This is not a valid addrec if the step amount is varying each
1289 // loop iteration, but is not itself an addrec in this loop.
1290 if (Accum->isLoopInvariant(L) ||
1291 (isa<SCEVAddRecExpr>(Accum) &&
1292 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1293 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1294 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L);
1295
1296 // Okay, for the entire analysis of this edge we assumed the PHI
1297 // to be symbolic. We now need to go back and update all of the
1298 // entries for the scalars that use the PHI (except for the PHI
1299 // itself) to use the new analyzed value instead of the "symbolic"
1300 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001301 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001302 return PHISCEV;
1303 }
1304 }
Chris Lattner97156e72006-04-26 18:34:07 +00001305 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1306 // Otherwise, this could be a loop like this:
1307 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1308 // In this case, j = {1,+,1} and BEValue is j.
1309 // Because the other in-value of i (0) fits the evolution of BEValue
1310 // i really is an addrec evolution.
1311 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1312 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1313
1314 // If StartVal = j.start - j.stride, we can use StartVal as the
1315 // initial step of the addrec evolution.
1316 if (StartVal == SCEV::getMinusSCEV(AddRec->getOperand(0),
1317 AddRec->getOperand(1))) {
1318 SCEVHandle PHISCEV =
1319 SCEVAddRecExpr::get(StartVal, AddRec->getOperand(1), L);
1320
1321 // Okay, for the entire analysis of this edge we assumed the PHI
1322 // to be symbolic. We now need to go back and update all of the
1323 // entries for the scalars that use the PHI (except for the PHI
1324 // itself) to use the new analyzed value instead of the "symbolic"
1325 // value.
1326 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1327 return PHISCEV;
1328 }
1329 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001330 }
1331
1332 return SymbolicName;
1333 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001334
Chris Lattner53e677a2004-04-02 20:23:17 +00001335 // If it's not a loop phi, we can't handle it yet.
1336 return SCEVUnknown::get(PN);
1337}
1338
Chris Lattnera17f0392006-12-12 02:26:09 +00001339/// GetConstantFactor - Determine the largest constant factor that S has. For
1340/// example, turn {4,+,8} -> 4. (S umod result) should always equal zero.
1341static uint64_t GetConstantFactor(SCEVHandle S) {
1342 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
1343 if (uint64_t V = C->getValue()->getZExtValue())
1344 return V;
1345 else // Zero is a multiple of everything.
1346 return 1ULL << (S->getType()->getPrimitiveSizeInBits()-1);
1347 }
1348
1349 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
1350 return GetConstantFactor(T->getOperand()) &
1351 T->getType()->getIntegralTypeMask();
1352 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S))
1353 return GetConstantFactor(E->getOperand());
1354
1355 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1356 // The result is the min of all operands.
1357 uint64_t Res = GetConstantFactor(A->getOperand(0));
1358 for (unsigned i = 1, e = A->getNumOperands(); i != e && Res > 1; ++i)
1359 Res = std::min(Res, GetConstantFactor(A->getOperand(i)));
1360 return Res;
1361 }
1362
1363 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
1364 // The result is the product of all the operands.
1365 uint64_t Res = GetConstantFactor(M->getOperand(0));
1366 for (unsigned i = 1, e = M->getNumOperands(); i != e; ++i)
1367 Res *= GetConstantFactor(M->getOperand(i));
1368 return Res;
1369 }
1370
1371 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Chris Lattner75de5ab2006-12-19 01:16:02 +00001372 // For now, we just handle linear expressions.
1373 if (A->getNumOperands() == 2) {
1374 // We want the GCD between the start and the stride value.
1375 uint64_t Start = GetConstantFactor(A->getOperand(0));
1376 if (Start == 1) return 1;
1377 uint64_t Stride = GetConstantFactor(A->getOperand(1));
1378 return GreatestCommonDivisor64(Start, Stride);
1379 }
Chris Lattnera17f0392006-12-12 02:26:09 +00001380 }
1381
1382 // SCEVSDivExpr, SCEVUnknown.
1383 return 1;
1384}
Chris Lattner53e677a2004-04-02 20:23:17 +00001385
1386/// createSCEV - We know that there is no SCEV for the specified value.
1387/// Analyze the expression.
1388///
1389SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1390 if (Instruction *I = dyn_cast<Instruction>(V)) {
1391 switch (I->getOpcode()) {
1392 case Instruction::Add:
1393 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1394 getSCEV(I->getOperand(1)));
1395 case Instruction::Mul:
1396 return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1397 getSCEV(I->getOperand(1)));
Reid Spencer1628cec2006-10-26 06:15:43 +00001398 case Instruction::SDiv:
1399 return SCEVSDivExpr::get(getSCEV(I->getOperand(0)),
1400 getSCEV(I->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001401 break;
1402
1403 case Instruction::Sub:
Chris Lattnerbac5b462005-03-09 05:34:41 +00001404 return SCEV::getMinusSCEV(getSCEV(I->getOperand(0)),
1405 getSCEV(I->getOperand(1)));
Chris Lattnera17f0392006-12-12 02:26:09 +00001406 case Instruction::Or:
1407 // If the RHS of the Or is a constant, we may have something like:
1408 // X*4+1 which got turned into X*4|1. Handle this as an add so loop
1409 // optimizations will transparently handle this case.
1410 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1411 SCEVHandle LHS = getSCEV(I->getOperand(0));
1412 uint64_t CommonFact = GetConstantFactor(LHS);
1413 assert(CommonFact && "Common factor should at least be 1!");
1414 if (CommonFact > CI->getZExtValue()) {
1415 // If the LHS is a multiple that is larger than the RHS, use +.
1416 return SCEVAddExpr::get(LHS,
1417 getSCEV(I->getOperand(1)));
1418 }
1419 }
1420 break;
1421
Chris Lattner53e677a2004-04-02 20:23:17 +00001422 case Instruction::Shl:
1423 // Turn shift left of a constant amount into a multiply.
1424 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1425 Constant *X = ConstantInt::get(V->getType(), 1);
1426 X = ConstantExpr::getShl(X, SA);
1427 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1428 }
1429 break;
1430
Reid Spencer3da59db2006-11-27 01:05:10 +00001431 case Instruction::Trunc:
Chris Lattner82e8a8f2006-12-11 00:12:31 +00001432 // We don't handle trunc to bool yet.
1433 if (I->getType()->isInteger())
Reid Spencer3da59db2006-11-27 01:05:10 +00001434 return SCEVTruncateExpr::get(getSCEV(I->getOperand(0)),
1435 I->getType()->getUnsignedVersion());
1436 break;
1437
1438 case Instruction::ZExt:
Chris Lattner82e8a8f2006-12-11 00:12:31 +00001439 // We don't handle zext from bool yet.
1440 if (I->getOperand(0)->getType()->isInteger())
Reid Spencer3da59db2006-11-27 01:05:10 +00001441 return SCEVZeroExtendExpr::get(getSCEV(I->getOperand(0)),
1442 I->getType()->getUnsignedVersion());
1443 break;
1444
1445 case Instruction::BitCast:
1446 // BitCasts are no-op casts so we just eliminate the cast.
Chris Lattner82e8a8f2006-12-11 00:12:31 +00001447 if (I->getType()->isInteger() && I->getOperand(0)->getType()->isInteger())
1448 return getSCEV(I->getOperand(0));
1449 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001450
1451 case Instruction::PHI:
1452 return createNodeForPHI(cast<PHINode>(I));
1453
1454 default: // We cannot analyze this expression.
1455 break;
1456 }
1457 }
1458
1459 return SCEVUnknown::get(V);
1460}
1461
1462
1463
1464//===----------------------------------------------------------------------===//
1465// Iteration Count Computation Code
1466//
1467
1468/// getIterationCount - If the specified loop has a predictable iteration
1469/// count, return it. Note that it is not valid to call this method on a
1470/// loop without a loop-invariant iteration count.
1471SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1472 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1473 if (I == IterationCounts.end()) {
1474 SCEVHandle ItCount = ComputeIterationCount(L);
1475 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1476 if (ItCount != UnknownValue) {
1477 assert(ItCount->isLoopInvariant(L) &&
1478 "Computed trip count isn't loop invariant for loop!");
1479 ++NumTripCountsComputed;
1480 } else if (isa<PHINode>(L->getHeader()->begin())) {
1481 // Only count loops that have phi nodes as not being computable.
1482 ++NumTripCountsNotComputed;
1483 }
1484 }
1485 return I->second;
1486}
1487
1488/// ComputeIterationCount - Compute the number of times the specified loop
1489/// will iterate.
1490SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1491 // If the loop has a non-one exit block count, we can't analyze it.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001492 std::vector<BasicBlock*> ExitBlocks;
1493 L->getExitBlocks(ExitBlocks);
1494 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001495
1496 // Okay, there is one exit block. Try to find the condition that causes the
1497 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001498 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001499
1500 BasicBlock *ExitingBlock = 0;
1501 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1502 PI != E; ++PI)
1503 if (L->contains(*PI)) {
1504 if (ExitingBlock == 0)
1505 ExitingBlock = *PI;
1506 else
1507 return UnknownValue; // More than one block exiting!
1508 }
1509 assert(ExitingBlock && "No exits from loop, something is broken!");
1510
1511 // Okay, we've computed the exiting block. See what condition causes us to
1512 // exit.
1513 //
1514 // FIXME: we should be able to handle switch instructions (with a single exit)
1515 // FIXME: We should handle cast of int to bool as well
1516 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1517 if (ExitBr == 0) return UnknownValue;
1518 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1519 SetCondInst *ExitCond = dyn_cast<SetCondInst>(ExitBr->getCondition());
Chris Lattner7980fb92004-04-17 18:36:24 +00001520 if (ExitCond == 0) // Not a setcc
1521 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1522 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00001523
Chris Lattner673e02b2004-10-12 01:49:27 +00001524 // If the condition was exit on true, convert the condition to exit on false.
1525 Instruction::BinaryOps Cond;
1526 if (ExitBr->getSuccessor(1) == ExitBlock)
1527 Cond = ExitCond->getOpcode();
1528 else
1529 Cond = ExitCond->getInverseCondition();
1530
1531 // Handle common loops like: for (X = "string"; *X; ++X)
1532 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1533 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1534 SCEVHandle ItCnt =
1535 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1536 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1537 }
1538
Chris Lattner53e677a2004-04-02 20:23:17 +00001539 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1540 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1541
1542 // Try to evaluate any dependencies out of the loop.
1543 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1544 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1545 Tmp = getSCEVAtScope(RHS, L);
1546 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1547
Chris Lattner53e677a2004-04-02 20:23:17 +00001548 // At this point, we would like to compute how many iterations of the loop the
1549 // predicate will return true for these inputs.
1550 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1551 // If there is a constant, force it into the RHS.
1552 std::swap(LHS, RHS);
1553 Cond = SetCondInst::getSwappedCondition(Cond);
1554 }
1555
1556 // FIXME: think about handling pointer comparisons! i.e.:
1557 // while (P != P+100) ++P;
1558
1559 // If we have a comparison of a chrec against a constant, try to use value
1560 // ranges to answer this query.
1561 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1562 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1563 if (AddRec->getLoop() == L) {
1564 // Form the comparison range using the constant of the correct type so
1565 // that the ConstantRange class knows to do a signed or unsigned
1566 // comparison.
1567 ConstantInt *CompVal = RHSC->getValue();
1568 const Type *RealTy = ExitCond->getOperand(0)->getType();
Reid Spencer4da49122006-12-12 05:05:00 +00001569 CompVal = dyn_cast<ConstantInt>(
Reid Spencerb6ba3e62006-12-12 09:17:50 +00001570 ConstantExpr::getBitCast(CompVal, RealTy));
Chris Lattner53e677a2004-04-02 20:23:17 +00001571 if (CompVal) {
1572 // Form the constant range.
1573 ConstantRange CompRange(Cond, CompVal);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001574
Chris Lattner53e677a2004-04-02 20:23:17 +00001575 // Now that we have it, if it's signed, convert it to an unsigned
1576 // range.
1577 if (CompRange.getLower()->getType()->isSigned()) {
1578 const Type *NewTy = RHSC->getValue()->getType();
Reid Spencerb6ba3e62006-12-12 09:17:50 +00001579 Constant *NewL = ConstantExpr::getBitCast(CompRange.getLower(),
1580 NewTy);
1581 Constant *NewU = ConstantExpr::getBitCast(CompRange.getUpper(),
1582 NewTy);
Chris Lattner53e677a2004-04-02 20:23:17 +00001583 CompRange = ConstantRange(NewL, NewU);
1584 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001585
Chris Lattner53e677a2004-04-02 20:23:17 +00001586 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange);
1587 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1588 }
1589 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001590
Chris Lattner53e677a2004-04-02 20:23:17 +00001591 switch (Cond) {
1592 case Instruction::SetNE: // while (X != Y)
1593 // Convert to: while (X-Y != 0)
Chris Lattner7980fb92004-04-17 18:36:24 +00001594 if (LHS->getType()->isInteger()) {
Chris Lattnerbac5b462005-03-09 05:34:41 +00001595 SCEVHandle TC = HowFarToZero(SCEV::getMinusSCEV(LHS, RHS), L);
Chris Lattner7980fb92004-04-17 18:36:24 +00001596 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1597 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001598 break;
1599 case Instruction::SetEQ:
1600 // Convert to: while (X-Y == 0) // while (X == Y)
Chris Lattner7980fb92004-04-17 18:36:24 +00001601 if (LHS->getType()->isInteger()) {
Chris Lattnerbac5b462005-03-09 05:34:41 +00001602 SCEVHandle TC = HowFarToNonZero(SCEV::getMinusSCEV(LHS, RHS), L);
Chris Lattner7980fb92004-04-17 18:36:24 +00001603 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1604 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001605 break;
Chris Lattnerdb25de42005-08-15 23:33:51 +00001606 case Instruction::SetLT:
1607 if (LHS->getType()->isInteger() &&
1608 ExitCond->getOperand(0)->getType()->isSigned()) {
1609 SCEVHandle TC = HowManyLessThans(LHS, RHS, L);
1610 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1611 }
1612 break;
1613 case Instruction::SetGT:
1614 if (LHS->getType()->isInteger() &&
1615 ExitCond->getOperand(0)->getType()->isSigned()) {
1616 SCEVHandle TC = HowManyLessThans(RHS, LHS, L);
1617 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1618 }
1619 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001620 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001621#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001622 cerr << "ComputeIterationCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00001623 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Bill Wendlinge8156192006-12-07 01:30:32 +00001624 cerr << "[unsigned] ";
1625 cerr << *LHS << " "
1626 << Instruction::getOpcodeName(Cond) << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001627#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00001628 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001629 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001630
1631 return ComputeIterationCountExhaustively(L, ExitCond,
1632 ExitBr->getSuccessor(0) == ExitBlock);
1633}
1634
Chris Lattner673e02b2004-10-12 01:49:27 +00001635static ConstantInt *
1636EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1637 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1638 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1639 assert(isa<SCEVConstant>(Val) &&
1640 "Evaluation of SCEV at constant didn't fold correctly?");
1641 return cast<SCEVConstant>(Val)->getValue();
1642}
1643
1644/// GetAddressedElementFromGlobal - Given a global variable with an initializer
1645/// and a GEP expression (missing the pointer index) indexing into it, return
1646/// the addressed element of the initializer or null if the index expression is
1647/// invalid.
1648static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001649GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00001650 const std::vector<ConstantInt*> &Indices) {
1651 Constant *Init = GV->getInitializer();
1652 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001653 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00001654 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1655 assert(Idx < CS->getNumOperands() && "Bad struct index!");
1656 Init = cast<Constant>(CS->getOperand(Idx));
1657 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1658 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
1659 Init = cast<Constant>(CA->getOperand(Idx));
1660 } else if (isa<ConstantAggregateZero>(Init)) {
1661 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1662 assert(Idx < STy->getNumElements() && "Bad struct index!");
1663 Init = Constant::getNullValue(STy->getElementType(Idx));
1664 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1665 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
1666 Init = Constant::getNullValue(ATy->getElementType());
1667 } else {
1668 assert(0 && "Unknown constant aggregate type!");
1669 }
1670 return 0;
1671 } else {
1672 return 0; // Unknown initializer type
1673 }
1674 }
1675 return Init;
1676}
1677
1678/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1679/// 'setcc load X, cst', try to se if we can compute the trip count.
1680SCEVHandle ScalarEvolutionsImpl::
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001681ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
Chris Lattner673e02b2004-10-12 01:49:27 +00001682 const Loop *L, unsigned SetCCOpcode) {
1683 if (LI->isVolatile()) return UnknownValue;
1684
1685 // Check to see if the loaded pointer is a getelementptr of a global.
1686 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1687 if (!GEP) return UnknownValue;
1688
1689 // Make sure that it is really a constant global we are gepping, with an
1690 // initializer, and make sure the first IDX is really 0.
1691 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1692 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1693 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1694 !cast<Constant>(GEP->getOperand(1))->isNullValue())
1695 return UnknownValue;
1696
1697 // Okay, we allow one non-constant index into the GEP instruction.
1698 Value *VarIdx = 0;
1699 std::vector<ConstantInt*> Indexes;
1700 unsigned VarIdxNum = 0;
1701 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1702 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1703 Indexes.push_back(CI);
1704 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1705 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
1706 VarIdx = GEP->getOperand(i);
1707 VarIdxNum = i-2;
1708 Indexes.push_back(0);
1709 }
1710
1711 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1712 // Check to see if X is a loop variant variable value now.
1713 SCEVHandle Idx = getSCEV(VarIdx);
1714 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1715 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1716
1717 // We can only recognize very limited forms of loop index expressions, in
1718 // particular, only affine AddRec's like {C1,+,C2}.
1719 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1720 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1721 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1722 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1723 return UnknownValue;
1724
1725 unsigned MaxSteps = MaxBruteForceIterations;
1726 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001727 ConstantInt *ItCst =
1728 ConstantInt::get(IdxExpr->getType()->getUnsignedVersion(), IterationNum);
Chris Lattner673e02b2004-10-12 01:49:27 +00001729 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst);
1730
1731 // Form the GEP offset.
1732 Indexes[VarIdxNum] = Val;
1733
1734 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
1735 if (Result == 0) break; // Cannot compute!
1736
1737 // Evaluate the condition for this iteration.
1738 Result = ConstantExpr::get(SetCCOpcode, Result, RHS);
1739 if (!isa<ConstantBool>(Result)) break; // Couldn't decide for sure
Chris Lattner003cbf32006-09-28 23:36:21 +00001740 if (cast<ConstantBool>(Result)->getValue() == false) {
Chris Lattner673e02b2004-10-12 01:49:27 +00001741#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001742 cerr << "\n***\n*** Computed loop count " << *ItCst
1743 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
1744 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00001745#endif
1746 ++NumArrayLenItCounts;
1747 return SCEVConstant::get(ItCst); // Found terminating iteration!
1748 }
1749 }
1750 return UnknownValue;
1751}
1752
1753
Chris Lattner3221ad02004-04-17 22:58:41 +00001754/// CanConstantFold - Return true if we can constant fold an instruction of the
1755/// specified type, assuming that all operands were constants.
1756static bool CanConstantFold(const Instruction *I) {
1757 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I) ||
1758 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1759 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001760
Chris Lattner3221ad02004-04-17 22:58:41 +00001761 if (const CallInst *CI = dyn_cast<CallInst>(I))
1762 if (const Function *F = CI->getCalledFunction())
1763 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1764 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00001765}
1766
Chris Lattner3221ad02004-04-17 22:58:41 +00001767/// ConstantFold - Constant fold an instruction of the specified type with the
1768/// specified constant operands. This function may modify the operands vector.
1769static Constant *ConstantFold(const Instruction *I,
1770 std::vector<Constant*> &Operands) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001771 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
1772 return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]);
1773
Reid Spencer3da59db2006-11-27 01:05:10 +00001774 if (isa<CastInst>(I))
1775 return ConstantExpr::getCast(I->getOpcode(), Operands[0], I->getType());
1776
Chris Lattner7980fb92004-04-17 18:36:24 +00001777 switch (I->getOpcode()) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001778 case Instruction::Select:
1779 return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]);
1780 case Instruction::Call:
Reid Spencere8404342004-07-18 00:18:30 +00001781 if (Function *GV = dyn_cast<Function>(Operands[0])) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001782 Operands.erase(Operands.begin());
Reid Spencere8404342004-07-18 00:18:30 +00001783 return ConstantFoldCall(cast<Function>(GV), Operands);
Chris Lattner7980fb92004-04-17 18:36:24 +00001784 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001785 return 0;
1786 case Instruction::GetElementPtr:
1787 Constant *Base = Operands[0];
1788 Operands.erase(Operands.begin());
1789 return ConstantExpr::getGetElementPtr(Base, Operands);
1790 }
1791 return 0;
1792}
1793
1794
Chris Lattner3221ad02004-04-17 22:58:41 +00001795/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1796/// in the loop that V is derived from. We allow arbitrary operations along the
1797/// way, but the operands of an operation must either be constants or a value
1798/// derived from a constant PHI. If this expression does not fit with these
1799/// constraints, return null.
1800static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1801 // If this is not an instruction, or if this is an instruction outside of the
1802 // loop, it can't be derived from a loop PHI.
1803 Instruction *I = dyn_cast<Instruction>(V);
1804 if (I == 0 || !L->contains(I->getParent())) return 0;
1805
1806 if (PHINode *PN = dyn_cast<PHINode>(I))
1807 if (L->getHeader() == I->getParent())
1808 return PN;
1809 else
1810 // We don't currently keep track of the control flow needed to evaluate
1811 // PHIs, so we cannot handle PHIs inside of loops.
1812 return 0;
1813
1814 // If we won't be able to constant fold this expression even if the operands
1815 // are constants, return early.
1816 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001817
Chris Lattner3221ad02004-04-17 22:58:41 +00001818 // Otherwise, we can evaluate this instruction if all of its operands are
1819 // constant or derived from a PHI node themselves.
1820 PHINode *PHI = 0;
1821 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1822 if (!(isa<Constant>(I->getOperand(Op)) ||
1823 isa<GlobalValue>(I->getOperand(Op)))) {
1824 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1825 if (P == 0) return 0; // Not evolving from PHI
1826 if (PHI == 0)
1827 PHI = P;
1828 else if (PHI != P)
1829 return 0; // Evolving from multiple different PHIs.
1830 }
1831
1832 // This is a expression evolving from a constant PHI!
1833 return PHI;
1834}
1835
1836/// EvaluateExpression - Given an expression that passes the
1837/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1838/// in the loop has the value PHIVal. If we can't fold this expression for some
1839/// reason, return null.
1840static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1841 if (isa<PHINode>(V)) return PHIVal;
Chris Lattner3221ad02004-04-17 22:58:41 +00001842 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
Reid Spencere8404342004-07-18 00:18:30 +00001843 return GV;
1844 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00001845 Instruction *I = cast<Instruction>(V);
1846
1847 std::vector<Constant*> Operands;
1848 Operands.resize(I->getNumOperands());
1849
1850 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1851 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1852 if (Operands[i] == 0) return 0;
1853 }
1854
1855 return ConstantFold(I, Operands);
1856}
1857
1858/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1859/// in the header of its containing loop, we know the loop executes a
1860/// constant number of times, and the PHI node is just a recurrence
1861/// involving constants, fold it.
1862Constant *ScalarEvolutionsImpl::
1863getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) {
1864 std::map<PHINode*, Constant*>::iterator I =
1865 ConstantEvolutionLoopExitValue.find(PN);
1866 if (I != ConstantEvolutionLoopExitValue.end())
1867 return I->second;
1868
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001869 if (Its > MaxBruteForceIterations)
Chris Lattner3221ad02004-04-17 22:58:41 +00001870 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1871
1872 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1873
1874 // Since the loop is canonicalized, the PHI node must have two entries. One
1875 // entry must be a constant (coming in from outside of the loop), and the
1876 // second must be derived from the same PHI.
1877 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1878 Constant *StartCST =
1879 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1880 if (StartCST == 0)
1881 return RetVal = 0; // Must be a constant.
1882
1883 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1884 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1885 if (PN2 != PN)
1886 return RetVal = 0; // Not derived from same PHI.
1887
1888 // Execute the loop symbolically to determine the exit value.
1889 unsigned IterationNum = 0;
1890 unsigned NumIterations = Its;
1891 if (NumIterations != Its)
1892 return RetVal = 0; // More than 2^32 iterations??
1893
1894 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1895 if (IterationNum == NumIterations)
1896 return RetVal = PHIVal; // Got exit value!
1897
1898 // Compute the value of the PHI node for the next iteration.
1899 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1900 if (NextPHI == PHIVal)
1901 return RetVal = NextPHI; // Stopped evolving!
1902 if (NextPHI == 0)
1903 return 0; // Couldn't evaluate!
1904 PHIVal = NextPHI;
1905 }
1906}
1907
Chris Lattner7980fb92004-04-17 18:36:24 +00001908/// ComputeIterationCountExhaustively - If the trip is known to execute a
1909/// constant number of times (the condition evolves only from constants),
1910/// try to evaluate a few iterations of the loop until we get the exit
1911/// condition gets a value of ExitWhen (true or false). If we cannot
1912/// evaluate the trip count of the loop, return UnknownValue.
1913SCEVHandle ScalarEvolutionsImpl::
1914ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1915 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1916 if (PN == 0) return UnknownValue;
1917
1918 // Since the loop is canonicalized, the PHI node must have two entries. One
1919 // entry must be a constant (coming in from outside of the loop), and the
1920 // second must be derived from the same PHI.
1921 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1922 Constant *StartCST =
1923 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1924 if (StartCST == 0) return UnknownValue; // Must be a constant.
1925
1926 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1927 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1928 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
1929
1930 // Okay, we find a PHI node that defines the trip count of this loop. Execute
1931 // the loop symbolically to determine when the condition gets a value of
1932 // "ExitWhen".
1933 unsigned IterationNum = 0;
1934 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
1935 for (Constant *PHIVal = StartCST;
1936 IterationNum != MaxIterations; ++IterationNum) {
1937 ConstantBool *CondVal =
1938 dyn_cast_or_null<ConstantBool>(EvaluateExpression(Cond, PHIVal));
1939 if (!CondVal) return UnknownValue; // Couldn't symbolically evaluate.
Chris Lattner3221ad02004-04-17 22:58:41 +00001940
Chris Lattner7980fb92004-04-17 18:36:24 +00001941 if (CondVal->getValue() == ExitWhen) {
Chris Lattner3221ad02004-04-17 22:58:41 +00001942 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00001943 ++NumBruteForceTripCountsComputed;
Reid Spencerb83eb642006-10-20 07:07:24 +00001944 return SCEVConstant::get(ConstantInt::get(Type::UIntTy, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00001945 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001946
Chris Lattner3221ad02004-04-17 22:58:41 +00001947 // Compute the value of the PHI node for the next iteration.
1948 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1949 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00001950 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00001951 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00001952 }
1953
1954 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00001955 return UnknownValue;
1956}
1957
1958/// getSCEVAtScope - Compute the value of the specified expression within the
1959/// indicated loop (which may be null to indicate in no loop). If the
1960/// expression cannot be evaluated, return UnknownValue.
1961SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1962 // FIXME: this should be turned into a virtual method on SCEV!
1963
Chris Lattner3221ad02004-04-17 22:58:41 +00001964 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001965
Chris Lattner3221ad02004-04-17 22:58:41 +00001966 // If this instruction is evolves from a constant-evolving PHI, compute the
1967 // exit value from the loop without using SCEVs.
1968 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
1969 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
1970 const Loop *LI = this->LI[I->getParent()];
1971 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
1972 if (PHINode *PN = dyn_cast<PHINode>(I))
1973 if (PN->getParent() == LI->getHeader()) {
1974 // Okay, there is no closed form solution for the PHI node. Check
1975 // to see if the loop that contains it has a known iteration count.
1976 // If so, we may be able to force computation of the exit value.
1977 SCEVHandle IterationCount = getIterationCount(LI);
1978 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
1979 // Okay, we know how many times the containing loop executes. If
1980 // this is a constant evolving PHI node, get the final value at
1981 // the specified iteration number.
1982 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Reid Spencerb83eb642006-10-20 07:07:24 +00001983 ICC->getValue()->getZExtValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00001984 LI);
1985 if (RV) return SCEVUnknown::get(RV);
1986 }
1987 }
1988
Reid Spencer09906f32006-12-04 21:33:23 +00001989 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00001990 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00001991 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00001992 // result. This is particularly useful for computing loop exit values.
1993 if (CanConstantFold(I)) {
1994 std::vector<Constant*> Operands;
1995 Operands.reserve(I->getNumOperands());
1996 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1997 Value *Op = I->getOperand(i);
1998 if (Constant *C = dyn_cast<Constant>(Op)) {
1999 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002000 } else {
2001 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2002 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
Reid Spencerd977d862006-12-12 23:36:14 +00002003 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2004 Op->getType(),
2005 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002006 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2007 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
Reid Spencerd977d862006-12-12 23:36:14 +00002008 Operands.push_back(ConstantExpr::getIntegerCast(C,
2009 Op->getType(),
2010 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002011 else
2012 return V;
2013 } else {
2014 return V;
2015 }
2016 }
2017 }
2018 return SCEVUnknown::get(ConstantFold(I, Operands));
2019 }
2020 }
2021
2022 // This is some other type of SCEVUnknown, just return it.
2023 return V;
2024 }
2025
Chris Lattner53e677a2004-04-02 20:23:17 +00002026 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2027 // Avoid performing the look-up in the common case where the specified
2028 // expression has no loop-variant portions.
2029 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2030 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2031 if (OpAtScope != Comm->getOperand(i)) {
2032 if (OpAtScope == UnknownValue) return UnknownValue;
2033 // Okay, at least one of these operands is loop variant but might be
2034 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00002035 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00002036 NewOps.push_back(OpAtScope);
2037
2038 for (++i; i != e; ++i) {
2039 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2040 if (OpAtScope == UnknownValue) return UnknownValue;
2041 NewOps.push_back(OpAtScope);
2042 }
2043 if (isa<SCEVAddExpr>(Comm))
2044 return SCEVAddExpr::get(NewOps);
2045 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
2046 return SCEVMulExpr::get(NewOps);
2047 }
2048 }
2049 // If we got here, all operands are loop invariant.
2050 return Comm;
2051 }
2052
Chris Lattner60a05cc2006-04-01 04:48:52 +00002053 if (SCEVSDivExpr *Div = dyn_cast<SCEVSDivExpr>(V)) {
2054 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002055 if (LHS == UnknownValue) return LHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002056 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002057 if (RHS == UnknownValue) return RHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002058 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2059 return Div; // must be loop invariant
2060 return SCEVSDivExpr::get(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00002061 }
2062
2063 // If this is a loop recurrence for a loop that does not contain L, then we
2064 // are dealing with the final value computed by the loop.
2065 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2066 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2067 // To evaluate this recurrence, we need to know how many times the AddRec
2068 // loop iterates. Compute this now.
2069 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2070 if (IterationCount == UnknownValue) return UnknownValue;
2071 IterationCount = getTruncateOrZeroExtend(IterationCount,
2072 AddRec->getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002073
Chris Lattner53e677a2004-04-02 20:23:17 +00002074 // If the value is affine, simplify the expression evaluation to just
2075 // Start + Step*IterationCount.
2076 if (AddRec->isAffine())
2077 return SCEVAddExpr::get(AddRec->getStart(),
2078 SCEVMulExpr::get(IterationCount,
2079 AddRec->getOperand(1)));
2080
2081 // Otherwise, evaluate it the hard way.
2082 return AddRec->evaluateAtIteration(IterationCount);
2083 }
2084 return UnknownValue;
2085 }
2086
2087 //assert(0 && "Unknown SCEV type!");
2088 return UnknownValue;
2089}
2090
2091
2092/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2093/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2094/// might be the same) or two SCEVCouldNotCompute objects.
2095///
2096static std::pair<SCEVHandle,SCEVHandle>
2097SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
2098 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2099 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2100 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2101 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002102
Chris Lattner53e677a2004-04-02 20:23:17 +00002103 // We currently can only solve this if the coefficients are constants.
2104 if (!L || !M || !N) {
2105 SCEV *CNC = new SCEVCouldNotCompute();
2106 return std::make_pair(CNC, CNC);
2107 }
2108
Reid Spencer1628cec2006-10-26 06:15:43 +00002109 Constant *C = L->getValue();
2110 Constant *Two = ConstantInt::get(C->getType(), 2);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002111
Chris Lattner53e677a2004-04-02 20:23:17 +00002112 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
Chris Lattner53e677a2004-04-02 20:23:17 +00002113 // The B coefficient is M-N/2
2114 Constant *B = ConstantExpr::getSub(M->getValue(),
Reid Spencer1628cec2006-10-26 06:15:43 +00002115 ConstantExpr::getSDiv(N->getValue(),
Chris Lattner53e677a2004-04-02 20:23:17 +00002116 Two));
2117 // The A coefficient is N/2
Reid Spencer1628cec2006-10-26 06:15:43 +00002118 Constant *A = ConstantExpr::getSDiv(N->getValue(), Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002119
Chris Lattner53e677a2004-04-02 20:23:17 +00002120 // Compute the B^2-4ac term.
2121 Constant *SqrtTerm =
2122 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
2123 ConstantExpr::getMul(A, C));
2124 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
2125
2126 // Compute floor(sqrt(B^2-4ac))
Reid Spencerb83eb642006-10-20 07:07:24 +00002127 ConstantInt *SqrtVal =
Reid Spencerd977d862006-12-12 23:36:14 +00002128 cast<ConstantInt>(ConstantExpr::getBitCast(SqrtTerm,
Chris Lattner53e677a2004-04-02 20:23:17 +00002129 SqrtTerm->getType()->getUnsignedVersion()));
Reid Spencerb83eb642006-10-20 07:07:24 +00002130 uint64_t SqrtValV = SqrtVal->getZExtValue();
Chris Lattner219c1412004-10-25 18:40:08 +00002131 uint64_t SqrtValV2 = (uint64_t)sqrt((double)SqrtValV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002132 // The square root might not be precise for arbitrary 64-bit integer
2133 // values. Do some sanity checks to ensure it's correct.
2134 if (SqrtValV2*SqrtValV2 > SqrtValV ||
2135 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
2136 SCEV *CNC = new SCEVCouldNotCompute();
2137 return std::make_pair(CNC, CNC);
2138 }
2139
Reid Spencerb83eb642006-10-20 07:07:24 +00002140 SqrtVal = ConstantInt::get(Type::ULongTy, SqrtValV2);
Reid Spencerd977d862006-12-12 23:36:14 +00002141 SqrtTerm = ConstantExpr::getTruncOrBitCast(SqrtVal, SqrtTerm->getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002142
Chris Lattner53e677a2004-04-02 20:23:17 +00002143 Constant *NegB = ConstantExpr::getNeg(B);
2144 Constant *TwoA = ConstantExpr::getMul(A, Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002145
Chris Lattner53e677a2004-04-02 20:23:17 +00002146 // The divisions must be performed as signed divisions.
2147 const Type *SignedTy = NegB->getType()->getSignedVersion();
Reid Spencerd977d862006-12-12 23:36:14 +00002148 NegB = ConstantExpr::getBitCast(NegB, SignedTy);
2149 TwoA = ConstantExpr::getBitCast(TwoA, SignedTy);
2150 SqrtTerm = ConstantExpr::getBitCast(SqrtTerm, SignedTy);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002151
Chris Lattner53e677a2004-04-02 20:23:17 +00002152 Constant *Solution1 =
Reid Spencer1628cec2006-10-26 06:15:43 +00002153 ConstantExpr::getSDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
Chris Lattner53e677a2004-04-02 20:23:17 +00002154 Constant *Solution2 =
Reid Spencer1628cec2006-10-26 06:15:43 +00002155 ConstantExpr::getSDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
Chris Lattner53e677a2004-04-02 20:23:17 +00002156 return std::make_pair(SCEVUnknown::get(Solution1),
2157 SCEVUnknown::get(Solution2));
2158}
2159
2160/// HowFarToZero - Return the number of times a backedge comparing the specified
2161/// value to zero will execute. If not computable, return UnknownValue
2162SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2163 // If the value is a constant
2164 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2165 // If the value is already zero, the branch will execute zero times.
2166 if (C->getValue()->isNullValue()) return C;
2167 return UnknownValue; // Otherwise it will loop infinitely.
2168 }
2169
2170 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2171 if (!AddRec || AddRec->getLoop() != L)
2172 return UnknownValue;
2173
2174 if (AddRec->isAffine()) {
2175 // If this is an affine expression the execution count of this branch is
2176 // equal to:
2177 //
2178 // (0 - Start/Step) iff Start % Step == 0
2179 //
2180 // Get the initial value for the loop.
2181 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00002182 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002183 SCEVHandle Step = AddRec->getOperand(1);
2184
2185 Step = getSCEVAtScope(Step, L->getParentLoop());
2186
2187 // Figure out if Start % Step == 0.
2188 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2189 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2190 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
Chris Lattnerbac5b462005-03-09 05:34:41 +00002191 return SCEV::getNegativeSCEV(Start); // 0 - Start/1 == -Start
Chris Lattner53e677a2004-04-02 20:23:17 +00002192 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2193 return Start; // 0 - Start/-1 == Start
2194
2195 // Check to see if Start is divisible by SC with no remainder.
2196 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2197 ConstantInt *StartCC = StartC->getValue();
2198 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
Reid Spencer0a783f72006-11-02 01:53:59 +00002199 Constant *Rem = ConstantExpr::getSRem(StartNegC, StepC->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +00002200 if (Rem->isNullValue()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002201 Constant *Result =ConstantExpr::getSDiv(StartNegC,StepC->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +00002202 return SCEVUnknown::get(Result);
2203 }
2204 }
2205 }
2206 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2207 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2208 // the quadratic equation to solve it.
2209 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
2210 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2211 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2212 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002213#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002214 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2215 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002216#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002217 // Pick the smallest positive root value.
2218 assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?");
2219 if (ConstantBool *CB =
2220 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2221 R2->getValue()))) {
Chris Lattner003cbf32006-09-28 23:36:21 +00002222 if (CB->getValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002223 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002224
Chris Lattner53e677a2004-04-02 20:23:17 +00002225 // We can only use this value if the chrec ends up with an exact zero
2226 // value at this index. When solving for "X*X != 5", for example, we
2227 // should not accept a root of 2.
2228 SCEVHandle Val = AddRec->evaluateAtIteration(R1);
2229 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
2230 if (EvalVal->getValue()->isNullValue())
2231 return R1; // We found a quadratic root!
2232 }
2233 }
2234 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002235
Chris Lattner53e677a2004-04-02 20:23:17 +00002236 return UnknownValue;
2237}
2238
2239/// HowFarToNonZero - Return the number of times a backedge checking the
2240/// specified value for nonzero will execute. If not computable, return
2241/// UnknownValue
2242SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2243 // Loops that look like: while (X == 0) are very strange indeed. We don't
2244 // handle them yet except for the trivial case. This could be expanded in the
2245 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002246
Chris Lattner53e677a2004-04-02 20:23:17 +00002247 // If the value is a constant, check to see if it is known to be non-zero
2248 // already. If so, the backedge will execute zero times.
2249 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2250 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
2251 Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero);
Chris Lattner003cbf32006-09-28 23:36:21 +00002252 if (NonZero == ConstantBool::getTrue())
Chris Lattner53e677a2004-04-02 20:23:17 +00002253 return getSCEV(Zero);
2254 return UnknownValue; // Otherwise it will loop infinitely.
2255 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002256
Chris Lattner53e677a2004-04-02 20:23:17 +00002257 // We could implement others, but I really doubt anyone writes loops like
2258 // this, and if they did, they would already be constant folded.
2259 return UnknownValue;
2260}
2261
Chris Lattnerdb25de42005-08-15 23:33:51 +00002262/// HowManyLessThans - Return the number of times a backedge containing the
2263/// specified less-than comparison will execute. If not computable, return
2264/// UnknownValue.
2265SCEVHandle ScalarEvolutionsImpl::
2266HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L) {
2267 // Only handle: "ADDREC < LoopInvariant".
2268 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2269
2270 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2271 if (!AddRec || AddRec->getLoop() != L)
2272 return UnknownValue;
2273
2274 if (AddRec->isAffine()) {
2275 // FORNOW: We only support unit strides.
2276 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, RHS->getType());
2277 if (AddRec->getOperand(1) != One)
2278 return UnknownValue;
2279
2280 // The number of iterations for "[n,+,1] < m", is m-n. However, we don't
2281 // know that m is >= n on input to the loop. If it is, the condition return
2282 // true zero times. What we really should return, for full generality, is
2283 // SMAX(0, m-n). Since we cannot check this, we will instead check for a
2284 // canonical loop form: most do-loops will have a check that dominates the
2285 // loop, that only enters the loop if [n-1]<m. If we can find this check,
2286 // we know that the SMAX will evaluate to m-n, because we know that m >= n.
2287
2288 // Search for the check.
2289 BasicBlock *Preheader = L->getLoopPreheader();
2290 BasicBlock *PreheaderDest = L->getHeader();
2291 if (Preheader == 0) return UnknownValue;
2292
2293 BranchInst *LoopEntryPredicate =
2294 dyn_cast<BranchInst>(Preheader->getTerminator());
2295 if (!LoopEntryPredicate) return UnknownValue;
2296
2297 // This might be a critical edge broken out. If the loop preheader ends in
2298 // an unconditional branch to the loop, check to see if the preheader has a
2299 // single predecessor, and if so, look for its terminator.
2300 while (LoopEntryPredicate->isUnconditional()) {
2301 PreheaderDest = Preheader;
2302 Preheader = Preheader->getSinglePredecessor();
2303 if (!Preheader) return UnknownValue; // Multiple preds.
2304
2305 LoopEntryPredicate =
2306 dyn_cast<BranchInst>(Preheader->getTerminator());
2307 if (!LoopEntryPredicate) return UnknownValue;
2308 }
2309
2310 // Now that we found a conditional branch that dominates the loop, check to
2311 // see if it is the comparison we are looking for.
2312 SetCondInst *SCI =dyn_cast<SetCondInst>(LoopEntryPredicate->getCondition());
2313 if (!SCI) return UnknownValue;
2314 Value *PreCondLHS = SCI->getOperand(0);
2315 Value *PreCondRHS = SCI->getOperand(1);
2316 Instruction::BinaryOps Cond;
2317 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2318 Cond = SCI->getOpcode();
2319 else
2320 Cond = SCI->getInverseCondition();
2321
2322 switch (Cond) {
2323 case Instruction::SetGT:
2324 std::swap(PreCondLHS, PreCondRHS);
2325 Cond = Instruction::SetLT;
2326 // Fall Through.
2327 case Instruction::SetLT:
2328 if (PreCondLHS->getType()->isInteger() &&
2329 PreCondLHS->getType()->isSigned()) {
2330 if (RHS != getSCEV(PreCondRHS))
2331 return UnknownValue; // Not a comparison against 'm'.
2332
2333 if (SCEV::getMinusSCEV(AddRec->getOperand(0), One)
2334 != getSCEV(PreCondLHS))
2335 return UnknownValue; // Not a comparison against 'n-1'.
2336 break;
2337 } else {
2338 return UnknownValue;
2339 }
2340 default: break;
2341 }
2342
Bill Wendlinge8156192006-12-07 01:30:32 +00002343 //cerr << "Computed Loop Trip Count as: "
2344 // << *SCEV::getMinusSCEV(RHS, AddRec->getOperand(0)) << "\n";
Chris Lattnerdb25de42005-08-15 23:33:51 +00002345 return SCEV::getMinusSCEV(RHS, AddRec->getOperand(0));
2346 }
2347
2348 return UnknownValue;
2349}
2350
Chris Lattner53e677a2004-04-02 20:23:17 +00002351/// getNumIterationsInRange - Return the number of iterations of this loop that
2352/// produce values in the specified constant range. Another way of looking at
2353/// this is that it returns the first iteration number where the value is not in
2354/// the condition, thus computing the exit count. If the iteration count can't
2355/// be computed, an instance of SCEVCouldNotCompute is returned.
2356SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const {
2357 if (Range.isFullSet()) // Infinite loop.
2358 return new SCEVCouldNotCompute();
2359
2360 // If the start is a non-zero constant, shift the range to simplify things.
2361 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2362 if (!SC->getValue()->isNullValue()) {
2363 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Chris Lattnerb06432c2004-04-23 21:29:03 +00002364 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002365 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2366 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2367 return ShiftedAddRec->getNumIterationsInRange(
2368 Range.subtract(SC->getValue()));
2369 // This is strange and shouldn't happen.
2370 return new SCEVCouldNotCompute();
2371 }
2372
2373 // The only time we can solve this is when we have all constant indices.
2374 // Otherwise, we cannot determine the overflow conditions.
2375 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2376 if (!isa<SCEVConstant>(getOperand(i)))
2377 return new SCEVCouldNotCompute();
2378
2379
2380 // Okay at this point we know that all elements of the chrec are constants and
2381 // that the start element is zero.
2382
2383 // First check to see if the range contains zero. If not, the first
2384 // iteration exits.
2385 ConstantInt *Zero = ConstantInt::get(getType(), 0);
2386 if (!Range.contains(Zero)) return SCEVConstant::get(Zero);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002387
Chris Lattner53e677a2004-04-02 20:23:17 +00002388 if (isAffine()) {
2389 // If this is an affine expression then we have this situation:
2390 // Solve {0,+,A} in Range === Ax in Range
2391
2392 // Since we know that zero is in the range, we know that the upper value of
2393 // the range must be the first possible exit value. Also note that we
2394 // already checked for a full range.
2395 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
2396 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue();
2397 ConstantInt *One = ConstantInt::get(getType(), 1);
2398
2399 // The exit value should be (Upper+A-1)/A.
2400 Constant *ExitValue = Upper;
2401 if (A != One) {
2402 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
Reid Spencer1628cec2006-10-26 06:15:43 +00002403 ExitValue = ConstantExpr::getSDiv(ExitValue, A);
Chris Lattner53e677a2004-04-02 20:23:17 +00002404 }
2405 assert(isa<ConstantInt>(ExitValue) &&
2406 "Constant folding of integers not implemented?");
2407
2408 // Evaluate at the exit value. If we really did fall out of the valid
2409 // range, then we computed our trip count, otherwise wrap around or other
2410 // things must have happened.
2411 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
2412 if (Range.contains(Val))
2413 return new SCEVCouldNotCompute(); // Something strange happened
2414
2415 // Ensure that the previous value is in the range. This is a sanity check.
2416 assert(Range.contains(EvaluateConstantChrecAtConstant(this,
2417 ConstantExpr::getSub(ExitValue, One))) &&
2418 "Linear scev computation is off in a bad way!");
2419 return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2420 } else if (isQuadratic()) {
2421 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2422 // quadratic equation to solve it. To do this, we must frame our problem in
2423 // terms of figuring out when zero is crossed, instead of when
2424 // Range.getUpper() is crossed.
2425 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Chris Lattnerbac5b462005-03-09 05:34:41 +00002426 NewOps[0] = SCEV::getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
Chris Lattner53e677a2004-04-02 20:23:17 +00002427 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2428
2429 // Next, solve the constructed addrec
2430 std::pair<SCEVHandle,SCEVHandle> Roots =
2431 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2432 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2433 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2434 if (R1) {
2435 // Pick the smallest positive root value.
2436 assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?");
2437 if (ConstantBool *CB =
2438 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2439 R2->getValue()))) {
Chris Lattner003cbf32006-09-28 23:36:21 +00002440 if (CB->getValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002441 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002442
Chris Lattner53e677a2004-04-02 20:23:17 +00002443 // Make sure the root is not off by one. The returned iteration should
2444 // not be in the range, but the previous one should be. When solving
2445 // for "X*X < 5", for example, we should not return a root of 2.
2446 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2447 R1->getValue());
2448 if (Range.contains(R1Val)) {
2449 // The next iteration must be out of the range...
2450 Constant *NextVal =
2451 ConstantExpr::getAdd(R1->getValue(),
2452 ConstantInt::get(R1->getType(), 1));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002453
Chris Lattner53e677a2004-04-02 20:23:17 +00002454 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2455 if (!Range.contains(R1Val))
2456 return SCEVUnknown::get(NextVal);
2457 return new SCEVCouldNotCompute(); // Something strange happened
2458 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002459
Chris Lattner53e677a2004-04-02 20:23:17 +00002460 // If R1 was not in the range, then it is a good return value. Make
2461 // sure that R1-1 WAS in the range though, just in case.
2462 Constant *NextVal =
2463 ConstantExpr::getSub(R1->getValue(),
2464 ConstantInt::get(R1->getType(), 1));
2465 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2466 if (Range.contains(R1Val))
2467 return R1;
2468 return new SCEVCouldNotCompute(); // Something strange happened
2469 }
2470 }
2471 }
2472
2473 // Fallback, if this is a general polynomial, figure out the progression
2474 // through brute force: evaluate until we find an iteration that fails the
2475 // test. This is likely to be slow, but getting an accurate trip count is
2476 // incredibly important, we will be able to simplify the exit test a lot, and
2477 // we are almost guaranteed to get a trip count in this case.
2478 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2479 ConstantInt *One = ConstantInt::get(getType(), 1);
2480 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2481 do {
2482 ++NumBruteForceEvaluations;
2483 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2484 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2485 return new SCEVCouldNotCompute();
2486
2487 // Check to see if we found the value!
2488 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()))
2489 return SCEVConstant::get(TestVal);
2490
2491 // Increment to test the next index.
2492 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
2493 } while (TestVal != EndVal);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002494
Chris Lattner53e677a2004-04-02 20:23:17 +00002495 return new SCEVCouldNotCompute();
2496}
2497
2498
2499
2500//===----------------------------------------------------------------------===//
2501// ScalarEvolution Class Implementation
2502//===----------------------------------------------------------------------===//
2503
2504bool ScalarEvolution::runOnFunction(Function &F) {
2505 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2506 return false;
2507}
2508
2509void ScalarEvolution::releaseMemory() {
2510 delete (ScalarEvolutionsImpl*)Impl;
2511 Impl = 0;
2512}
2513
2514void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2515 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00002516 AU.addRequiredTransitive<LoopInfo>();
2517}
2518
2519SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2520 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2521}
2522
Chris Lattnera0740fb2005-08-09 23:36:33 +00002523/// hasSCEV - Return true if the SCEV for this value has already been
2524/// computed.
2525bool ScalarEvolution::hasSCEV(Value *V) const {
Chris Lattner05bd3742005-08-10 00:59:40 +00002526 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
Chris Lattnera0740fb2005-08-09 23:36:33 +00002527}
2528
2529
2530/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2531/// the specified value.
2532void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2533 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2534}
2535
2536
Chris Lattner53e677a2004-04-02 20:23:17 +00002537SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2538 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2539}
2540
2541bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2542 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2543}
2544
2545SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2546 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2547}
2548
2549void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2550 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2551}
2552
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002553static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00002554 const Loop *L) {
2555 // Print all inner loops first
2556 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2557 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002558
Bill Wendlinge8156192006-12-07 01:30:32 +00002559 cerr << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002560
2561 std::vector<BasicBlock*> ExitBlocks;
2562 L->getExitBlocks(ExitBlocks);
2563 if (ExitBlocks.size() != 1)
Bill Wendlinge8156192006-12-07 01:30:32 +00002564 cerr << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002565
2566 if (SE->hasLoopInvariantIterationCount(L)) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002567 cerr << *SE->getIterationCount(L) << " iterations! ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002568 } else {
Bill Wendlinge8156192006-12-07 01:30:32 +00002569 cerr << "Unpredictable iteration count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002570 }
2571
Bill Wendlinge8156192006-12-07 01:30:32 +00002572 cerr << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00002573}
2574
Reid Spencerce9653c2004-12-07 04:03:45 +00002575void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002576 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2577 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2578
2579 OS << "Classifying expressions for: " << F.getName() << "\n";
2580 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner6ffe5512004-04-27 15:13:33 +00002581 if (I->getType()->isInteger()) {
2582 OS << *I;
Chris Lattner53e677a2004-04-02 20:23:17 +00002583 OS << " --> ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002584 SCEVHandle SV = getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00002585 SV->print(OS);
2586 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002587
Chris Lattner6ffe5512004-04-27 15:13:33 +00002588 if ((*I).getType()->isIntegral()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002589 ConstantRange Bounds = SV->getValueRange();
2590 if (!Bounds.isFullSet())
2591 OS << "Bounds: " << Bounds << " ";
2592 }
2593
Chris Lattner6ffe5512004-04-27 15:13:33 +00002594 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002595 OS << "Exits: ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002596 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002597 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2598 OS << "<<Unknown>>";
2599 } else {
2600 OS << *ExitValue;
2601 }
2602 }
2603
2604
2605 OS << "\n";
2606 }
2607
2608 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2609 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2610 PrintLoopInfo(OS, this, *I);
2611}
2612