blob: 0507b39b7d9feefacbc98e013c6090b68c59cfa8 [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();
Chris Lattner42a75512007-01-15 02:27:26 +0000125 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
Chris Lattner53e677a2004-04-02 20:23:17 +0000126 // Default to a full range if no better information is available.
127 return ConstantRange(getType());
128}
129
130
131SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
132
133bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
134 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000135 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000136}
137
138const Type *SCEVCouldNotCompute::getType() const {
139 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000140 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000141}
142
143bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
144 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
145 return false;
146}
147
Chris Lattner4dc534c2005-02-13 04:37:18 +0000148SCEVHandle SCEVCouldNotCompute::
149replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
150 const SCEVHandle &Conc) const {
151 return this;
152}
153
Chris Lattner53e677a2004-04-02 20:23:17 +0000154void SCEVCouldNotCompute::print(std::ostream &OS) const {
155 OS << "***COULDNOTCOMPUTE***";
156}
157
158bool SCEVCouldNotCompute::classof(const SCEV *S) {
159 return S->getSCEVType() == scCouldNotCompute;
160}
161
162
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000163// SCEVConstants - Only allow the creation of one SCEVConstant for any
164// particular value. Don't use a SCEVHandle here, or else the object will
165// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000166static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000167
Chris Lattner53e677a2004-04-02 20:23:17 +0000168
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000169SCEVConstant::~SCEVConstant() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000170 SCEVConstants->erase(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000171}
Chris Lattner53e677a2004-04-02 20:23:17 +0000172
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000173SCEVHandle SCEVConstant::get(ConstantInt *V) {
Chris Lattnerb3364092006-10-04 21:49:37 +0000174 SCEVConstant *&R = (*SCEVConstants)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000175 if (R == 0) R = new SCEVConstant(V);
176 return R;
177}
Chris Lattner53e677a2004-04-02 20:23:17 +0000178
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000179ConstantRange SCEVConstant::getValueRange() const {
Reid Spencerdc5c1592007-02-28 18:57:32 +0000180 return ConstantRange(V->getValue());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000181}
Chris Lattner53e677a2004-04-02 20:23:17 +0000182
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000183const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000184
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000185void SCEVConstant::print(std::ostream &OS) const {
186 WriteAsOperand(OS, V, false);
187}
Chris Lattner53e677a2004-04-02 20:23:17 +0000188
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000189// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
190// particular input. Don't use a SCEVHandle here, or else the object will
191// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000192static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
193 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000194
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000195SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
196 : SCEV(scTruncate), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000197 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000198 "Cannot truncate non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000199 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
200 && "This is not a truncating conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000201}
Chris Lattner53e677a2004-04-02 20:23:17 +0000202
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000203SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000204 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000205}
Chris Lattner53e677a2004-04-02 20:23:17 +0000206
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000207ConstantRange SCEVTruncateExpr::getValueRange() const {
208 return getOperand()->getValueRange().truncate(getType());
209}
Chris Lattner53e677a2004-04-02 20:23:17 +0000210
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000211void SCEVTruncateExpr::print(std::ostream &OS) const {
212 OS << "(truncate " << *Op << " to " << *Ty << ")";
213}
214
215// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
216// particular input. Don't use a SCEVHandle here, or else the object will never
217// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000218static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
219 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000220
221SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Reid Spencer48d8a702006-11-01 21:53:12 +0000222 : SCEV(scZeroExtend), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000223 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000224 "Cannot zero extend non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000225 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
226 && "This is not an extending conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000227}
228
229SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000230 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000231}
232
233ConstantRange SCEVZeroExtendExpr::getValueRange() const {
234 return getOperand()->getValueRange().zeroExtend(getType());
235}
236
237void SCEVZeroExtendExpr::print(std::ostream &OS) const {
238 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
239}
240
241// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
242// particular input. Don't use a SCEVHandle here, or else the object will never
243// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000244static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
245 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000246
247SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000248 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
249 std::vector<SCEV*>(Operands.begin(),
250 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000251}
252
253void SCEVCommutativeExpr::print(std::ostream &OS) const {
254 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
255 const char *OpStr = getOperationStr();
256 OS << "(" << *Operands[0];
257 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
258 OS << OpStr << *Operands[i];
259 OS << ")";
260}
261
Chris Lattner4dc534c2005-02-13 04:37:18 +0000262SCEVHandle SCEVCommutativeExpr::
263replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
264 const SCEVHandle &Conc) const {
265 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
266 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
267 if (H != getOperand(i)) {
268 std::vector<SCEVHandle> NewOps;
269 NewOps.reserve(getNumOperands());
270 for (unsigned j = 0; j != i; ++j)
271 NewOps.push_back(getOperand(j));
272 NewOps.push_back(H);
273 for (++i; i != e; ++i)
274 NewOps.push_back(getOperand(i)->
275 replaceSymbolicValuesWithConcrete(Sym, Conc));
276
277 if (isa<SCEVAddExpr>(this))
278 return SCEVAddExpr::get(NewOps);
279 else if (isa<SCEVMulExpr>(this))
280 return SCEVMulExpr::get(NewOps);
281 else
282 assert(0 && "Unknown commutative expr!");
283 }
284 }
285 return this;
286}
287
288
Chris Lattner60a05cc2006-04-01 04:48:52 +0000289// SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000290// input. Don't use a SCEVHandle here, or else the object will never be
291// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000292static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
293 SCEVSDivExpr*> > SCEVSDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000294
Chris Lattner60a05cc2006-04-01 04:48:52 +0000295SCEVSDivExpr::~SCEVSDivExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000296 SCEVSDivs->erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000297}
298
Chris Lattner60a05cc2006-04-01 04:48:52 +0000299void SCEVSDivExpr::print(std::ostream &OS) const {
300 OS << "(" << *LHS << " /s " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000301}
302
Chris Lattner60a05cc2006-04-01 04:48:52 +0000303const Type *SCEVSDivExpr::getType() const {
Reid Spencerc5b206b2006-12-31 05:48:39 +0000304 return LHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000305}
306
307// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
308// particular input. Don't use a SCEVHandle here, or else the object will never
309// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000310static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
311 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000312
313SCEVAddRecExpr::~SCEVAddRecExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000314 SCEVAddRecExprs->erase(std::make_pair(L,
315 std::vector<SCEV*>(Operands.begin(),
316 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000317}
318
Chris Lattner4dc534c2005-02-13 04:37:18 +0000319SCEVHandle SCEVAddRecExpr::
320replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
321 const SCEVHandle &Conc) const {
322 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
323 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
324 if (H != getOperand(i)) {
325 std::vector<SCEVHandle> NewOps;
326 NewOps.reserve(getNumOperands());
327 for (unsigned j = 0; j != i; ++j)
328 NewOps.push_back(getOperand(j));
329 NewOps.push_back(H);
330 for (++i; i != e; ++i)
331 NewOps.push_back(getOperand(i)->
332 replaceSymbolicValuesWithConcrete(Sym, Conc));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000333
Chris Lattner4dc534c2005-02-13 04:37:18 +0000334 return get(NewOps, L);
335 }
336 }
337 return this;
338}
339
340
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000341bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
342 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000343 // contain L and if the start is invariant.
344 return !QueryLoop->contains(L->getHeader()) &&
345 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000346}
347
348
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000349void SCEVAddRecExpr::print(std::ostream &OS) const {
350 OS << "{" << *Operands[0];
351 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
352 OS << ",+," << *Operands[i];
353 OS << "}<" << L->getHeader()->getName() + ">";
354}
Chris Lattner53e677a2004-04-02 20:23:17 +0000355
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000356// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
357// value. Don't use a SCEVHandle here, or else the object will never be
358// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000359static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000360
Chris Lattnerb3364092006-10-04 21:49:37 +0000361SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000362
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000363bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
364 // All non-instruction values are loop invariant. All instructions are loop
365 // invariant if they are not contained in the specified loop.
366 if (Instruction *I = dyn_cast<Instruction>(V))
367 return !L->contains(I->getParent());
368 return true;
369}
Chris Lattner53e677a2004-04-02 20:23:17 +0000370
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000371const Type *SCEVUnknown::getType() const {
372 return V->getType();
373}
Chris Lattner53e677a2004-04-02 20:23:17 +0000374
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000375void SCEVUnknown::print(std::ostream &OS) const {
376 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000377}
378
Chris Lattner8d741b82004-06-20 06:23:15 +0000379//===----------------------------------------------------------------------===//
380// SCEV Utilities
381//===----------------------------------------------------------------------===//
382
383namespace {
384 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
385 /// than the complexity of the RHS. This comparator is used to canonicalize
386 /// expressions.
Chris Lattner95255282006-06-28 23:17:24 +0000387 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Chris Lattner8d741b82004-06-20 06:23:15 +0000388 bool operator()(SCEV *LHS, SCEV *RHS) {
389 return LHS->getSCEVType() < RHS->getSCEVType();
390 }
391 };
392}
393
394/// GroupByComplexity - Given a list of SCEV objects, order them by their
395/// complexity, and group objects of the same complexity together by value.
396/// When this routine is finished, we know that any duplicates in the vector are
397/// consecutive and that complexity is monotonically increasing.
398///
399/// Note that we go take special precautions to ensure that we get determinstic
400/// results from this routine. In other words, we don't want the results of
401/// this to depend on where the addresses of various SCEV objects happened to
402/// land in memory.
403///
404static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
405 if (Ops.size() < 2) return; // Noop
406 if (Ops.size() == 2) {
407 // This is the common case, which also happens to be trivially simple.
408 // Special case it.
409 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
410 std::swap(Ops[0], Ops[1]);
411 return;
412 }
413
414 // Do the rough sort by complexity.
415 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
416
417 // Now that we are sorted by complexity, group elements of the same
418 // complexity. Note that this is, at worst, N^2, but the vector is likely to
419 // be extremely short in practice. Note that we take this approach because we
420 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000421 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000422 SCEV *S = Ops[i];
423 unsigned Complexity = S->getSCEVType();
424
425 // If there are any objects of the same complexity and same value as this
426 // one, group them.
427 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
428 if (Ops[j] == S) { // Found a duplicate.
429 // Move it to immediately after i'th element.
430 std::swap(Ops[i+1], Ops[j]);
431 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000432 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000433 }
434 }
435 }
436}
437
Chris Lattner53e677a2004-04-02 20:23:17 +0000438
Chris Lattner53e677a2004-04-02 20:23:17 +0000439
440//===----------------------------------------------------------------------===//
441// Simple SCEV method implementations
442//===----------------------------------------------------------------------===//
443
444/// getIntegerSCEV - Given an integer or FP type, create a constant for the
445/// specified signed integer value and return a SCEV for the constant.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000446SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000447 Constant *C;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000448 if (Val == 0)
Chris Lattner53e677a2004-04-02 20:23:17 +0000449 C = Constant::getNullValue(Ty);
450 else if (Ty->isFloatingPoint())
451 C = ConstantFP::get(Ty, Val);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000452 else
Reid Spencerb83eb642006-10-20 07:07:24 +0000453 C = ConstantInt::get(Ty, Val);
Chris Lattner53e677a2004-04-02 20:23:17 +0000454 return SCEVUnknown::get(C);
455}
456
457/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
458/// input value to the specified type. If the type must be extended, it is zero
459/// extended.
460static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
461 const Type *SrcTy = V->getType();
Chris Lattner42a75512007-01-15 02:27:26 +0000462 assert(SrcTy->isInteger() && Ty->isInteger() &&
Chris Lattner53e677a2004-04-02 20:23:17 +0000463 "Cannot truncate or zero extend with non-integer arguments!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000464 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
Chris Lattner53e677a2004-04-02 20:23:17 +0000465 return V; // No conversion
Reid Spencere7ca0422007-01-08 01:26:33 +0000466 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
Chris Lattner53e677a2004-04-02 20:23:17 +0000467 return SCEVTruncateExpr::get(V, Ty);
468 return SCEVZeroExtendExpr::get(V, Ty);
469}
470
471/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
472///
Chris Lattnerbac5b462005-03-09 05:34:41 +0000473SCEVHandle SCEV::getNegativeSCEV(const SCEVHandle &V) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000474 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
475 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000476
Chris Lattnerb06432c2004-04-23 21:29:03 +0000477 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
Chris Lattner53e677a2004-04-02 20:23:17 +0000478}
479
480/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
481///
Chris Lattnerbac5b462005-03-09 05:34:41 +0000482SCEVHandle SCEV::getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000483 // X - Y --> X + -Y
Chris Lattnerbac5b462005-03-09 05:34:41 +0000484 return SCEVAddExpr::get(LHS, SCEV::getNegativeSCEV(RHS));
Chris Lattner53e677a2004-04-02 20:23:17 +0000485}
486
487
Chris Lattner53e677a2004-04-02 20:23:17 +0000488/// PartialFact - Compute V!/(V-NumSteps)!
489static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
490 // Handle this case efficiently, it is common to have constant iteration
491 // counts while computing loop exit values.
492 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
Reid Spencerdc5c1592007-02-28 18:57:32 +0000493 APInt Val = SC->getValue()->getValue();
494 APInt Result(Val.getBitWidth(), 1);
Chris Lattner53e677a2004-04-02 20:23:17 +0000495 for (; NumSteps; --NumSteps)
496 Result *= Val-(NumSteps-1);
Reid Spencerdc5c1592007-02-28 18:57:32 +0000497 return SCEVUnknown::get(ConstantInt::get(V->getType(), Result));
Chris Lattner53e677a2004-04-02 20:23:17 +0000498 }
499
500 const Type *Ty = V->getType();
501 if (NumSteps == 0)
Chris Lattnerb06432c2004-04-23 21:29:03 +0000502 return SCEVUnknown::getIntegerSCEV(1, Ty);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000503
Chris Lattner53e677a2004-04-02 20:23:17 +0000504 SCEVHandle Result = V;
505 for (unsigned i = 1; i != NumSteps; ++i)
Chris Lattnerbac5b462005-03-09 05:34:41 +0000506 Result = SCEVMulExpr::get(Result, SCEV::getMinusSCEV(V,
Chris Lattnerb06432c2004-04-23 21:29:03 +0000507 SCEVUnknown::getIntegerSCEV(i, Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000508 return Result;
509}
510
511
512/// evaluateAtIteration - Return the value of this chain of recurrences at
513/// the specified iteration number. We can evaluate this recurrence by
514/// multiplying each element in the chain by the binomial coefficient
515/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
516///
517/// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
518///
519/// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
520/// Is the binomial equation safe using modular arithmetic??
521///
522SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
523 SCEVHandle Result = getStart();
524 int Divisor = 1;
525 const Type *Ty = It->getType();
526 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
527 SCEVHandle BC = PartialFact(It, i);
528 Divisor *= i;
Chris Lattner60a05cc2006-04-01 04:48:52 +0000529 SCEVHandle Val = SCEVSDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
Chris Lattnerb06432c2004-04-23 21:29:03 +0000530 SCEVUnknown::getIntegerSCEV(Divisor,Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000531 Result = SCEVAddExpr::get(Result, Val);
532 }
533 return Result;
534}
535
536
537//===----------------------------------------------------------------------===//
538// SCEV Expression folder implementations
539//===----------------------------------------------------------------------===//
540
541SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
542 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Reid Spencer7858b332006-12-05 19:14:13 +0000543 return SCEVUnknown::get(
Reid Spencer315d0552006-12-05 22:39:58 +0000544 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000545
546 // If the input value is a chrec scev made out of constants, truncate
547 // all of the constants.
548 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
549 std::vector<SCEVHandle> Operands;
550 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
551 // FIXME: This should allow truncation of other expression types!
552 if (isa<SCEVConstant>(AddRec->getOperand(i)))
553 Operands.push_back(get(AddRec->getOperand(i), Ty));
554 else
555 break;
556 if (Operands.size() == AddRec->getNumOperands())
557 return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
558 }
559
Chris Lattnerb3364092006-10-04 21:49:37 +0000560 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000561 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
562 return Result;
563}
564
565SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
566 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Reid Spencer7858b332006-12-05 19:14:13 +0000567 return SCEVUnknown::get(
Reid Spencerd977d862006-12-12 23:36:14 +0000568 ConstantExpr::getZExt(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000569
570 // FIXME: If the input value is a chrec scev, and we can prove that the value
571 // did not overflow the old, smaller, value, we can zero extend all of the
572 // operands (often constants). This would allow analysis of something like
573 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
574
Chris Lattnerb3364092006-10-04 21:49:37 +0000575 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000576 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
577 return Result;
578}
579
580// get - Get a canonical add expression, or something simpler if possible.
581SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
582 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000583 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000584
585 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000586 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000587
588 // If there are any constants, fold them together.
589 unsigned Idx = 0;
590 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
591 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000592 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000593 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
594 // We found two constants, fold them together!
595 Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue());
596 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
597 Ops[0] = SCEVConstant::get(CI);
598 Ops.erase(Ops.begin()+1); // Erase the folded element
599 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000600 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000601 } else {
602 // If we couldn't fold the expression, move to the next constant. Note
603 // that this is impossible to happen in practice because we always
604 // constant fold constant ints to constant ints.
605 ++Idx;
606 }
607 }
608
609 // If we are left with a constant zero being added, strip it off.
610 if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
611 Ops.erase(Ops.begin());
612 --Idx;
613 }
614 }
615
Chris Lattner627018b2004-04-07 16:16:11 +0000616 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000617
Chris Lattner53e677a2004-04-02 20:23:17 +0000618 // Okay, check to see if the same value occurs in the operand list twice. If
619 // so, merge them together into an multiply expression. Since we sorted the
620 // list, these values are required to be adjacent.
621 const Type *Ty = Ops[0]->getType();
622 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
623 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
624 // Found a match, merge the two values into a multiply, and add any
625 // remaining values to the result.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000626 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000627 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
628 if (Ops.size() == 2)
629 return Mul;
630 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
631 Ops.push_back(Mul);
632 return SCEVAddExpr::get(Ops);
633 }
634
635 // Okay, now we know the first non-constant operand. If there are add
636 // operands they would be next.
637 if (Idx < Ops.size()) {
638 bool DeletedAdd = false;
639 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
640 // If we have an add, expand the add operands onto the end of the operands
641 // list.
642 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
643 Ops.erase(Ops.begin()+Idx);
644 DeletedAdd = true;
645 }
646
647 // If we deleted at least one add, we added operands to the end of the list,
648 // and they are not necessarily sorted. Recurse to resort and resimplify
649 // any operands we just aquired.
650 if (DeletedAdd)
651 return get(Ops);
652 }
653
654 // Skip over the add expression until we get to a multiply.
655 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
656 ++Idx;
657
658 // If we are adding something to a multiply expression, make sure the
659 // something is not already an operand of the multiply. If so, merge it into
660 // the multiply.
661 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
662 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
663 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
664 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
665 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000666 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000667 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
668 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
669 if (Mul->getNumOperands() != 2) {
670 // If the multiply has more than two operands, we must get the
671 // Y*Z term.
672 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
673 MulOps.erase(MulOps.begin()+MulOp);
674 InnerMul = SCEVMulExpr::get(MulOps);
675 }
Chris Lattnerb06432c2004-04-23 21:29:03 +0000676 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000677 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
678 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
679 if (Ops.size() == 2) return OuterMul;
680 if (AddOp < Idx) {
681 Ops.erase(Ops.begin()+AddOp);
682 Ops.erase(Ops.begin()+Idx-1);
683 } else {
684 Ops.erase(Ops.begin()+Idx);
685 Ops.erase(Ops.begin()+AddOp-1);
686 }
687 Ops.push_back(OuterMul);
688 return SCEVAddExpr::get(Ops);
689 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000690
Chris Lattner53e677a2004-04-02 20:23:17 +0000691 // Check this multiply against other multiplies being added together.
692 for (unsigned OtherMulIdx = Idx+1;
693 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
694 ++OtherMulIdx) {
695 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
696 // If MulOp occurs in OtherMul, we can fold the two multiplies
697 // together.
698 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
699 OMulOp != e; ++OMulOp)
700 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
701 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
702 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
703 if (Mul->getNumOperands() != 2) {
704 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
705 MulOps.erase(MulOps.begin()+MulOp);
706 InnerMul1 = SCEVMulExpr::get(MulOps);
707 }
708 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
709 if (OtherMul->getNumOperands() != 2) {
710 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
711 OtherMul->op_end());
712 MulOps.erase(MulOps.begin()+OMulOp);
713 InnerMul2 = SCEVMulExpr::get(MulOps);
714 }
715 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
716 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
717 if (Ops.size() == 2) return OuterMul;
718 Ops.erase(Ops.begin()+Idx);
719 Ops.erase(Ops.begin()+OtherMulIdx-1);
720 Ops.push_back(OuterMul);
721 return SCEVAddExpr::get(Ops);
722 }
723 }
724 }
725 }
726
727 // If there are any add recurrences in the operands list, see if any other
728 // added values are loop invariant. If so, we can fold them into the
729 // recurrence.
730 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
731 ++Idx;
732
733 // Scan over all recurrences, trying to fold loop invariants into them.
734 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
735 // Scan all of the other operands to this add and add them to the vector if
736 // they are loop invariant w.r.t. the recurrence.
737 std::vector<SCEVHandle> LIOps;
738 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
739 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
740 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
741 LIOps.push_back(Ops[i]);
742 Ops.erase(Ops.begin()+i);
743 --i; --e;
744 }
745
746 // If we found some loop invariants, fold them into the recurrence.
747 if (!LIOps.empty()) {
748 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
749 LIOps.push_back(AddRec->getStart());
750
751 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
752 AddRecOps[0] = SCEVAddExpr::get(LIOps);
753
754 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
755 // If all of the other operands were loop invariant, we are done.
756 if (Ops.size() == 1) return NewRec;
757
758 // Otherwise, add the folded AddRec by the non-liv parts.
759 for (unsigned i = 0;; ++i)
760 if (Ops[i] == AddRec) {
761 Ops[i] = NewRec;
762 break;
763 }
764 return SCEVAddExpr::get(Ops);
765 }
766
767 // Okay, if there weren't any loop invariants to be folded, check to see if
768 // there are multiple AddRec's with the same loop induction variable being
769 // added together. If so, we can fold them.
770 for (unsigned OtherIdx = Idx+1;
771 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
772 if (OtherIdx != Idx) {
773 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
774 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
775 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
776 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
777 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
778 if (i >= NewOps.size()) {
779 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
780 OtherAddRec->op_end());
781 break;
782 }
783 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
784 }
785 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
786
787 if (Ops.size() == 2) return NewAddRec;
788
789 Ops.erase(Ops.begin()+Idx);
790 Ops.erase(Ops.begin()+OtherIdx-1);
791 Ops.push_back(NewAddRec);
792 return SCEVAddExpr::get(Ops);
793 }
794 }
795
796 // Otherwise couldn't fold anything into this recurrence. Move onto the
797 // next one.
798 }
799
800 // Okay, it looks like we really DO need an add expr. Check to see if we
801 // already have one, otherwise create a new one.
802 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000803 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
804 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000805 if (Result == 0) Result = new SCEVAddExpr(Ops);
806 return Result;
807}
808
809
810SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
811 assert(!Ops.empty() && "Cannot get empty mul!");
812
813 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000814 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000815
816 // If there are any constants, fold them together.
817 unsigned Idx = 0;
818 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
819
820 // C1*(C2+V) -> C1*C2 + C1*V
821 if (Ops.size() == 2)
822 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
823 if (Add->getNumOperands() == 2 &&
824 isa<SCEVConstant>(Add->getOperand(0)))
825 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
826 SCEVMulExpr::get(LHSC, Add->getOperand(1)));
827
828
829 ++Idx;
830 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
831 // We found two constants, fold them together!
832 Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue());
833 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
834 Ops[0] = SCEVConstant::get(CI);
835 Ops.erase(Ops.begin()+1); // Erase the folded element
836 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000837 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000838 } else {
839 // If we couldn't fold the expression, move to the next constant. Note
840 // that this is impossible to happen in practice because we always
841 // constant fold constant ints to constant ints.
842 ++Idx;
843 }
844 }
845
846 // If we are left with a constant one being multiplied, strip it off.
847 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
848 Ops.erase(Ops.begin());
849 --Idx;
850 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
851 // If we have a multiply of zero, it will always be zero.
852 return Ops[0];
853 }
854 }
855
856 // Skip over the add expression until we get to a multiply.
857 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
858 ++Idx;
859
860 if (Ops.size() == 1)
861 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000862
Chris Lattner53e677a2004-04-02 20:23:17 +0000863 // If there are mul operands inline them all into this expression.
864 if (Idx < Ops.size()) {
865 bool DeletedMul = false;
866 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
867 // If we have an mul, expand the mul operands onto the end of the operands
868 // list.
869 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
870 Ops.erase(Ops.begin()+Idx);
871 DeletedMul = true;
872 }
873
874 // If we deleted at least one mul, we added operands to the end of the list,
875 // and they are not necessarily sorted. Recurse to resort and resimplify
876 // any operands we just aquired.
877 if (DeletedMul)
878 return get(Ops);
879 }
880
881 // If there are any add recurrences in the operands list, see if any other
882 // added values are loop invariant. If so, we can fold them into the
883 // recurrence.
884 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
885 ++Idx;
886
887 // Scan over all recurrences, trying to fold loop invariants into them.
888 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
889 // Scan all of the other operands to this mul and add them to the vector if
890 // they are loop invariant w.r.t. the recurrence.
891 std::vector<SCEVHandle> LIOps;
892 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
893 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
894 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
895 LIOps.push_back(Ops[i]);
896 Ops.erase(Ops.begin()+i);
897 --i; --e;
898 }
899
900 // If we found some loop invariants, fold them into the recurrence.
901 if (!LIOps.empty()) {
902 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
903 std::vector<SCEVHandle> NewOps;
904 NewOps.reserve(AddRec->getNumOperands());
905 if (LIOps.size() == 1) {
906 SCEV *Scale = LIOps[0];
907 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
908 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
909 } else {
910 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
911 std::vector<SCEVHandle> MulOps(LIOps);
912 MulOps.push_back(AddRec->getOperand(i));
913 NewOps.push_back(SCEVMulExpr::get(MulOps));
914 }
915 }
916
917 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
918
919 // If all of the other operands were loop invariant, we are done.
920 if (Ops.size() == 1) return NewRec;
921
922 // Otherwise, multiply the folded AddRec by the non-liv parts.
923 for (unsigned i = 0;; ++i)
924 if (Ops[i] == AddRec) {
925 Ops[i] = NewRec;
926 break;
927 }
928 return SCEVMulExpr::get(Ops);
929 }
930
931 // Okay, if there weren't any loop invariants to be folded, check to see if
932 // there are multiple AddRec's with the same loop induction variable being
933 // multiplied together. If so, we can fold them.
934 for (unsigned OtherIdx = Idx+1;
935 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
936 if (OtherIdx != Idx) {
937 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
938 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
939 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
940 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
941 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
942 G->getStart());
943 SCEVHandle B = F->getStepRecurrence();
944 SCEVHandle D = G->getStepRecurrence();
945 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
946 SCEVMulExpr::get(G, B),
947 SCEVMulExpr::get(B, D));
948 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
949 F->getLoop());
950 if (Ops.size() == 2) return NewAddRec;
951
952 Ops.erase(Ops.begin()+Idx);
953 Ops.erase(Ops.begin()+OtherIdx-1);
954 Ops.push_back(NewAddRec);
955 return SCEVMulExpr::get(Ops);
956 }
957 }
958
959 // Otherwise couldn't fold anything into this recurrence. Move onto the
960 // next one.
961 }
962
963 // Okay, it looks like we really DO need an mul expr. Check to see if we
964 // already have one, otherwise create a new one.
965 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000966 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
967 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000968 if (Result == 0)
969 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000970 return Result;
971}
972
Chris Lattner60a05cc2006-04-01 04:48:52 +0000973SCEVHandle SCEVSDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000974 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
975 if (RHSC->getValue()->equalsInt(1))
Reid Spencer1628cec2006-10-26 06:15:43 +0000976 return LHS; // X sdiv 1 --> x
Chris Lattner53e677a2004-04-02 20:23:17 +0000977 if (RHSC->getValue()->isAllOnesValue())
Reid Spencer1628cec2006-10-26 06:15:43 +0000978 return SCEV::getNegativeSCEV(LHS); // X sdiv -1 --> -x
Chris Lattner53e677a2004-04-02 20:23:17 +0000979
980 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
981 Constant *LHSCV = LHSC->getValue();
982 Constant *RHSCV = RHSC->getValue();
Reid Spencer1628cec2006-10-26 06:15:43 +0000983 return SCEVUnknown::get(ConstantExpr::getSDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +0000984 }
985 }
986
987 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
988
Chris Lattnerb3364092006-10-04 21:49:37 +0000989 SCEVSDivExpr *&Result = (*SCEVSDivs)[std::make_pair(LHS, RHS)];
Chris Lattner60a05cc2006-04-01 04:48:52 +0000990 if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +0000991 return Result;
992}
993
994
995/// SCEVAddRecExpr::get - Get a add recurrence expression for the
996/// specified loop. Simplify the expression as much as possible.
997SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
998 const SCEVHandle &Step, const Loop *L) {
999 std::vector<SCEVHandle> Operands;
1000 Operands.push_back(Start);
1001 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1002 if (StepChrec->getLoop() == L) {
1003 Operands.insert(Operands.end(), StepChrec->op_begin(),
1004 StepChrec->op_end());
1005 return get(Operands, L);
1006 }
1007
1008 Operands.push_back(Step);
1009 return get(Operands, L);
1010}
1011
1012/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1013/// specified loop. Simplify the expression as much as possible.
1014SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
1015 const Loop *L) {
1016 if (Operands.size() == 1) return Operands[0];
1017
1018 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
1019 if (StepC->getValue()->isNullValue()) {
1020 Operands.pop_back();
1021 return get(Operands, L); // { X,+,0 } --> X
1022 }
1023
1024 SCEVAddRecExpr *&Result =
Chris Lattnerb3364092006-10-04 21:49:37 +00001025 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1026 Operands.end()))];
Chris Lattner53e677a2004-04-02 20:23:17 +00001027 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1028 return Result;
1029}
1030
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001031SCEVHandle SCEVUnknown::get(Value *V) {
1032 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1033 return SCEVConstant::get(CI);
Chris Lattnerb3364092006-10-04 21:49:37 +00001034 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001035 if (Result == 0) Result = new SCEVUnknown(V);
1036 return Result;
1037}
1038
Chris Lattner53e677a2004-04-02 20:23:17 +00001039
1040//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001041// ScalarEvolutionsImpl Definition and Implementation
1042//===----------------------------------------------------------------------===//
1043//
1044/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1045/// evolution code.
1046///
1047namespace {
Chris Lattner95255282006-06-28 23:17:24 +00001048 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Chris Lattner53e677a2004-04-02 20:23:17 +00001049 /// F - The function we are analyzing.
1050 ///
1051 Function &F;
1052
1053 /// LI - The loop information for the function we are currently analyzing.
1054 ///
1055 LoopInfo &LI;
1056
1057 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1058 /// things.
1059 SCEVHandle UnknownValue;
1060
1061 /// Scalars - This is a cache of the scalars we have analyzed so far.
1062 ///
1063 std::map<Value*, SCEVHandle> Scalars;
1064
1065 /// IterationCounts - Cache the iteration count of the loops for this
1066 /// function as they are computed.
1067 std::map<const Loop*, SCEVHandle> IterationCounts;
1068
Chris Lattner3221ad02004-04-17 22:58:41 +00001069 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1070 /// the PHI instructions that we attempt to compute constant evolutions for.
1071 /// This allows us to avoid potentially expensive recomputation of these
1072 /// properties. An instruction maps to null if we are unable to compute its
1073 /// exit value.
1074 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001075
Chris Lattner53e677a2004-04-02 20:23:17 +00001076 public:
1077 ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1078 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1079
1080 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1081 /// expression and create a new one.
1082 SCEVHandle getSCEV(Value *V);
1083
Chris Lattnera0740fb2005-08-09 23:36:33 +00001084 /// hasSCEV - Return true if the SCEV for this value has already been
1085 /// computed.
1086 bool hasSCEV(Value *V) const {
1087 return Scalars.count(V);
1088 }
1089
1090 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1091 /// the specified value.
1092 void setSCEV(Value *V, const SCEVHandle &H) {
1093 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1094 assert(isNew && "This entry already existed!");
1095 }
1096
1097
Chris Lattner53e677a2004-04-02 20:23:17 +00001098 /// getSCEVAtScope - Compute the value of the specified expression within
1099 /// the indicated loop (which may be null to indicate in no loop). If the
1100 /// expression cannot be evaluated, return UnknownValue itself.
1101 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1102
1103
1104 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1105 /// an analyzable loop-invariant iteration count.
1106 bool hasLoopInvariantIterationCount(const Loop *L);
1107
1108 /// getIterationCount - If the specified loop has a predictable iteration
1109 /// count, return it. Note that it is not valid to call this method on a
1110 /// loop without a loop-invariant iteration count.
1111 SCEVHandle getIterationCount(const Loop *L);
1112
1113 /// deleteInstructionFromRecords - This method should be called by the
1114 /// client before it removes an instruction from the program, to make sure
1115 /// that no dangling references are left around.
1116 void deleteInstructionFromRecords(Instruction *I);
1117
1118 private:
1119 /// createSCEV - We know that there is no SCEV for the specified value.
1120 /// Analyze the expression.
1121 SCEVHandle createSCEV(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001122
1123 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1124 /// SCEVs.
1125 SCEVHandle createNodeForPHI(PHINode *PN);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001126
1127 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1128 /// for the specified instruction and replaces any references to the
1129 /// symbolic value SymName with the specified value. This is used during
1130 /// PHI resolution.
1131 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1132 const SCEVHandle &SymName,
1133 const SCEVHandle &NewVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00001134
1135 /// ComputeIterationCount - Compute the number of times the specified loop
1136 /// will iterate.
1137 SCEVHandle ComputeIterationCount(const Loop *L);
1138
Chris Lattner673e02b2004-10-12 01:49:27 +00001139 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1140 /// 'setcc load X, cst', try to se if we can compute the trip count.
1141 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1142 Constant *RHS,
1143 const Loop *L,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001144 ICmpInst::Predicate p);
Chris Lattner673e02b2004-10-12 01:49:27 +00001145
Chris Lattner7980fb92004-04-17 18:36:24 +00001146 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1147 /// constant number of times (the condition evolves only from constants),
1148 /// try to evaluate a few iterations of the loop until we get the exit
1149 /// condition gets a value of ExitWhen (true or false). If we cannot
1150 /// evaluate the trip count of the loop, return UnknownValue.
1151 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1152 bool ExitWhen);
1153
Chris Lattner53e677a2004-04-02 20:23:17 +00001154 /// HowFarToZero - Return the number of times a backedge comparing the
1155 /// specified value to zero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001156 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001157 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1158
1159 /// HowFarToNonZero - Return the number of times a backedge checking the
1160 /// specified value for nonzero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001161 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001162 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattner3221ad02004-04-17 22:58:41 +00001163
Chris Lattnerdb25de42005-08-15 23:33:51 +00001164 /// HowManyLessThans - Return the number of times a backedge containing the
1165 /// specified less-than comparison will execute. If not computable, return
1166 /// UnknownValue.
1167 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L);
1168
Chris Lattner3221ad02004-04-17 22:58:41 +00001169 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1170 /// in the header of its containing loop, we know the loop executes a
1171 /// constant number of times, and the PHI node is just a recurrence
1172 /// involving constants, fold it.
1173 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its,
1174 const Loop *L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001175 };
1176}
1177
1178//===----------------------------------------------------------------------===//
1179// Basic SCEV Analysis and PHI Idiom Recognition Code
1180//
1181
1182/// deleteInstructionFromRecords - This method should be called by the
1183/// client before it removes an instruction from the program, to make sure
1184/// that no dangling references are left around.
1185void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
1186 Scalars.erase(I);
Chris Lattner3221ad02004-04-17 22:58:41 +00001187 if (PHINode *PN = dyn_cast<PHINode>(I))
1188 ConstantEvolutionLoopExitValue.erase(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001189}
1190
1191
1192/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1193/// expression and create a new one.
1194SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1195 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1196
1197 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1198 if (I != Scalars.end()) return I->second;
1199 SCEVHandle S = createSCEV(V);
1200 Scalars.insert(std::make_pair(V, S));
1201 return S;
1202}
1203
Chris Lattner4dc534c2005-02-13 04:37:18 +00001204/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1205/// the specified instruction and replaces any references to the symbolic value
1206/// SymName with the specified value. This is used during PHI resolution.
1207void ScalarEvolutionsImpl::
1208ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1209 const SCEVHandle &NewVal) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001210 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001211 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001212
Chris Lattner4dc534c2005-02-13 04:37:18 +00001213 SCEVHandle NV =
1214 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal);
1215 if (NV == SI->second) return; // No change.
1216
1217 SI->second = NV; // Update the scalars map!
1218
1219 // Any instruction values that use this instruction might also need to be
1220 // updated!
1221 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1222 UI != E; ++UI)
1223 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1224}
Chris Lattner53e677a2004-04-02 20:23:17 +00001225
1226/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1227/// a loop header, making it a potential recurrence, or it doesn't.
1228///
1229SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1230 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1231 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1232 if (L->getHeader() == PN->getParent()) {
1233 // If it lives in the loop header, it has two incoming values, one
1234 // from outside the loop, and one from inside.
1235 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1236 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001237
Chris Lattner53e677a2004-04-02 20:23:17 +00001238 // While we are analyzing this PHI node, handle its value symbolically.
1239 SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1240 assert(Scalars.find(PN) == Scalars.end() &&
1241 "PHI node already processed?");
1242 Scalars.insert(std::make_pair(PN, SymbolicName));
1243
1244 // Using this symbolic name for the PHI, analyze the value coming around
1245 // the back-edge.
1246 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1247
1248 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1249 // has a special value for the first iteration of the loop.
1250
1251 // If the value coming around the backedge is an add with the symbolic
1252 // value we just inserted, then we found a simple induction variable!
1253 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1254 // If there is a single occurrence of the symbolic value, replace it
1255 // with a recurrence.
1256 unsigned FoundIndex = Add->getNumOperands();
1257 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1258 if (Add->getOperand(i) == SymbolicName)
1259 if (FoundIndex == e) {
1260 FoundIndex = i;
1261 break;
1262 }
1263
1264 if (FoundIndex != Add->getNumOperands()) {
1265 // Create an add with everything but the specified operand.
1266 std::vector<SCEVHandle> Ops;
1267 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1268 if (i != FoundIndex)
1269 Ops.push_back(Add->getOperand(i));
1270 SCEVHandle Accum = SCEVAddExpr::get(Ops);
1271
1272 // This is not a valid addrec if the step amount is varying each
1273 // loop iteration, but is not itself an addrec in this loop.
1274 if (Accum->isLoopInvariant(L) ||
1275 (isa<SCEVAddRecExpr>(Accum) &&
1276 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1277 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1278 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L);
1279
1280 // Okay, for the entire analysis of this edge we assumed the PHI
1281 // to be symbolic. We now need to go back and update all of the
1282 // entries for the scalars that use the PHI (except for the PHI
1283 // itself) to use the new analyzed value instead of the "symbolic"
1284 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001285 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001286 return PHISCEV;
1287 }
1288 }
Chris Lattner97156e72006-04-26 18:34:07 +00001289 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1290 // Otherwise, this could be a loop like this:
1291 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1292 // In this case, j = {1,+,1} and BEValue is j.
1293 // Because the other in-value of i (0) fits the evolution of BEValue
1294 // i really is an addrec evolution.
1295 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1296 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1297
1298 // If StartVal = j.start - j.stride, we can use StartVal as the
1299 // initial step of the addrec evolution.
1300 if (StartVal == SCEV::getMinusSCEV(AddRec->getOperand(0),
1301 AddRec->getOperand(1))) {
1302 SCEVHandle PHISCEV =
1303 SCEVAddRecExpr::get(StartVal, AddRec->getOperand(1), L);
1304
1305 // Okay, for the entire analysis of this edge we assumed the PHI
1306 // to be symbolic. We now need to go back and update all of the
1307 // entries for the scalars that use the PHI (except for the PHI
1308 // itself) to use the new analyzed value instead of the "symbolic"
1309 // value.
1310 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1311 return PHISCEV;
1312 }
1313 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001314 }
1315
1316 return SymbolicName;
1317 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001318
Chris Lattner53e677a2004-04-02 20:23:17 +00001319 // If it's not a loop phi, we can't handle it yet.
1320 return SCEVUnknown::get(PN);
1321}
1322
Chris Lattnera17f0392006-12-12 02:26:09 +00001323/// GetConstantFactor - Determine the largest constant factor that S has. For
1324/// example, turn {4,+,8} -> 4. (S umod result) should always equal zero.
1325static uint64_t GetConstantFactor(SCEVHandle S) {
1326 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
1327 if (uint64_t V = C->getValue()->getZExtValue())
1328 return V;
1329 else // Zero is a multiple of everything.
1330 return 1ULL << (S->getType()->getPrimitiveSizeInBits()-1);
1331 }
1332
1333 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
1334 return GetConstantFactor(T->getOperand()) &
Reid Spencerc1030572007-01-19 21:13:56 +00001335 cast<IntegerType>(T->getType())->getBitMask();
Chris Lattnera17f0392006-12-12 02:26:09 +00001336 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S))
1337 return GetConstantFactor(E->getOperand());
1338
1339 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1340 // The result is the min of all operands.
1341 uint64_t Res = GetConstantFactor(A->getOperand(0));
1342 for (unsigned i = 1, e = A->getNumOperands(); i != e && Res > 1; ++i)
1343 Res = std::min(Res, GetConstantFactor(A->getOperand(i)));
1344 return Res;
1345 }
1346
1347 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
1348 // The result is the product of all the operands.
1349 uint64_t Res = GetConstantFactor(M->getOperand(0));
1350 for (unsigned i = 1, e = M->getNumOperands(); i != e; ++i)
1351 Res *= GetConstantFactor(M->getOperand(i));
1352 return Res;
1353 }
1354
1355 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Chris Lattner75de5ab2006-12-19 01:16:02 +00001356 // For now, we just handle linear expressions.
1357 if (A->getNumOperands() == 2) {
1358 // We want the GCD between the start and the stride value.
1359 uint64_t Start = GetConstantFactor(A->getOperand(0));
1360 if (Start == 1) return 1;
1361 uint64_t Stride = GetConstantFactor(A->getOperand(1));
1362 return GreatestCommonDivisor64(Start, Stride);
1363 }
Chris Lattnera17f0392006-12-12 02:26:09 +00001364 }
1365
1366 // SCEVSDivExpr, SCEVUnknown.
1367 return 1;
1368}
Chris Lattner53e677a2004-04-02 20:23:17 +00001369
1370/// createSCEV - We know that there is no SCEV for the specified value.
1371/// Analyze the expression.
1372///
1373SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1374 if (Instruction *I = dyn_cast<Instruction>(V)) {
1375 switch (I->getOpcode()) {
1376 case Instruction::Add:
1377 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1378 getSCEV(I->getOperand(1)));
1379 case Instruction::Mul:
1380 return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1381 getSCEV(I->getOperand(1)));
Reid Spencer1628cec2006-10-26 06:15:43 +00001382 case Instruction::SDiv:
1383 return SCEVSDivExpr::get(getSCEV(I->getOperand(0)),
1384 getSCEV(I->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001385 break;
1386
1387 case Instruction::Sub:
Chris Lattnerbac5b462005-03-09 05:34:41 +00001388 return SCEV::getMinusSCEV(getSCEV(I->getOperand(0)),
1389 getSCEV(I->getOperand(1)));
Chris Lattnera17f0392006-12-12 02:26:09 +00001390 case Instruction::Or:
1391 // If the RHS of the Or is a constant, we may have something like:
1392 // X*4+1 which got turned into X*4|1. Handle this as an add so loop
1393 // optimizations will transparently handle this case.
1394 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1395 SCEVHandle LHS = getSCEV(I->getOperand(0));
1396 uint64_t CommonFact = GetConstantFactor(LHS);
1397 assert(CommonFact && "Common factor should at least be 1!");
1398 if (CommonFact > CI->getZExtValue()) {
1399 // If the LHS is a multiple that is larger than the RHS, use +.
1400 return SCEVAddExpr::get(LHS,
1401 getSCEV(I->getOperand(1)));
1402 }
1403 }
1404 break;
1405
Chris Lattner53e677a2004-04-02 20:23:17 +00001406 case Instruction::Shl:
1407 // Turn shift left of a constant amount into a multiply.
1408 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1409 Constant *X = ConstantInt::get(V->getType(), 1);
1410 X = ConstantExpr::getShl(X, SA);
1411 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1412 }
1413 break;
1414
Reid Spencer3da59db2006-11-27 01:05:10 +00001415 case Instruction::Trunc:
Chris Lattnerb2f3e702007-01-15 01:58:56 +00001416 return SCEVTruncateExpr::get(getSCEV(I->getOperand(0)), I->getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00001417
1418 case Instruction::ZExt:
Chris Lattnerb2f3e702007-01-15 01:58:56 +00001419 return SCEVZeroExtendExpr::get(getSCEV(I->getOperand(0)), I->getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00001420
1421 case Instruction::BitCast:
1422 // BitCasts are no-op casts so we just eliminate the cast.
Chris Lattner42a75512007-01-15 02:27:26 +00001423 if (I->getType()->isInteger() &&
1424 I->getOperand(0)->getType()->isInteger())
Chris Lattner82e8a8f2006-12-11 00:12:31 +00001425 return getSCEV(I->getOperand(0));
1426 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001427
1428 case Instruction::PHI:
1429 return createNodeForPHI(cast<PHINode>(I));
1430
1431 default: // We cannot analyze this expression.
1432 break;
1433 }
1434 }
1435
1436 return SCEVUnknown::get(V);
1437}
1438
1439
1440
1441//===----------------------------------------------------------------------===//
1442// Iteration Count Computation Code
1443//
1444
1445/// getIterationCount - If the specified loop has a predictable iteration
1446/// count, return it. Note that it is not valid to call this method on a
1447/// loop without a loop-invariant iteration count.
1448SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1449 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1450 if (I == IterationCounts.end()) {
1451 SCEVHandle ItCount = ComputeIterationCount(L);
1452 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1453 if (ItCount != UnknownValue) {
1454 assert(ItCount->isLoopInvariant(L) &&
1455 "Computed trip count isn't loop invariant for loop!");
1456 ++NumTripCountsComputed;
1457 } else if (isa<PHINode>(L->getHeader()->begin())) {
1458 // Only count loops that have phi nodes as not being computable.
1459 ++NumTripCountsNotComputed;
1460 }
1461 }
1462 return I->second;
1463}
1464
1465/// ComputeIterationCount - Compute the number of times the specified loop
1466/// will iterate.
1467SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1468 // If the loop has a non-one exit block count, we can't analyze it.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001469 std::vector<BasicBlock*> ExitBlocks;
1470 L->getExitBlocks(ExitBlocks);
1471 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001472
1473 // Okay, there is one exit block. Try to find the condition that causes the
1474 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001475 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001476
1477 BasicBlock *ExitingBlock = 0;
1478 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1479 PI != E; ++PI)
1480 if (L->contains(*PI)) {
1481 if (ExitingBlock == 0)
1482 ExitingBlock = *PI;
1483 else
1484 return UnknownValue; // More than one block exiting!
1485 }
1486 assert(ExitingBlock && "No exits from loop, something is broken!");
1487
1488 // Okay, we've computed the exiting block. See what condition causes us to
1489 // exit.
1490 //
1491 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00001492 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1493 if (ExitBr == 0) return UnknownValue;
1494 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Chris Lattner8b0e3602007-01-07 02:24:26 +00001495
1496 // At this point, we know we have a conditional branch that determines whether
1497 // the loop is exited. However, we don't know if the branch is executed each
1498 // time through the loop. If not, then the execution count of the branch will
1499 // not be equal to the trip count of the loop.
1500 //
1501 // Currently we check for this by checking to see if the Exit branch goes to
1502 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00001503 // times as the loop. We also handle the case where the exit block *is* the
1504 // loop header. This is common for un-rotated loops. More extensive analysis
1505 // could be done to handle more cases here.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001506 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00001507 ExitBr->getSuccessor(1) != L->getHeader() &&
1508 ExitBr->getParent() != L->getHeader())
Chris Lattner8b0e3602007-01-07 02:24:26 +00001509 return UnknownValue;
1510
Reid Spencere4d87aa2006-12-23 06:05:41 +00001511 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
1512
1513 // If its not an integer comparison then compute it the hard way.
1514 // Note that ICmpInst deals with pointer comparisons too so we must check
1515 // the type of the operand.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001516 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Chris Lattner7980fb92004-04-17 18:36:24 +00001517 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1518 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00001519
Reid Spencere4d87aa2006-12-23 06:05:41 +00001520 // If the condition was exit on true, convert the condition to exit on false
1521 ICmpInst::Predicate Cond;
Chris Lattner673e02b2004-10-12 01:49:27 +00001522 if (ExitBr->getSuccessor(1) == ExitBlock)
Reid Spencere4d87aa2006-12-23 06:05:41 +00001523 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00001524 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00001525 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00001526
1527 // Handle common loops like: for (X = "string"; *X; ++X)
1528 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1529 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1530 SCEVHandle ItCnt =
1531 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1532 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1533 }
1534
Chris Lattner53e677a2004-04-02 20:23:17 +00001535 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1536 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1537
1538 // Try to evaluate any dependencies out of the loop.
1539 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1540 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1541 Tmp = getSCEVAtScope(RHS, L);
1542 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1543
Reid Spencere4d87aa2006-12-23 06:05:41 +00001544 // At this point, we would like to compute how many iterations of the
1545 // loop the predicate will return true for these inputs.
Chris Lattner53e677a2004-04-02 20:23:17 +00001546 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1547 // If there is a constant, force it into the RHS.
1548 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001549 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00001550 }
1551
1552 // FIXME: think about handling pointer comparisons! i.e.:
1553 // while (P != P+100) ++P;
1554
1555 // If we have a comparison of a chrec against a constant, try to use value
1556 // ranges to answer this query.
1557 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1558 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1559 if (AddRec->getLoop() == L) {
1560 // Form the comparison range using the constant of the correct type so
1561 // that the ConstantRange class knows to do a signed or unsigned
1562 // comparison.
1563 ConstantInt *CompVal = RHSC->getValue();
1564 const Type *RealTy = ExitCond->getOperand(0)->getType();
Reid Spencer4da49122006-12-12 05:05:00 +00001565 CompVal = dyn_cast<ConstantInt>(
Reid Spencerb6ba3e62006-12-12 09:17:50 +00001566 ConstantExpr::getBitCast(CompVal, RealTy));
Chris Lattner53e677a2004-04-02 20:23:17 +00001567 if (CompVal) {
1568 // Form the constant range.
Reid Spencerdc5c1592007-02-28 18:57:32 +00001569 ConstantRange CompRange(Cond, CompVal->getValue());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001570
Reid Spencere4d87aa2006-12-23 06:05:41 +00001571 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange,
Reid Spencerc5b206b2006-12-31 05:48:39 +00001572 false /*Always treat as unsigned range*/);
Chris Lattner53e677a2004-04-02 20:23:17 +00001573 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1574 }
1575 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001576
Chris Lattner53e677a2004-04-02 20:23:17 +00001577 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001578 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00001579 // Convert to: while (X-Y != 0)
Reid Spencere4d87aa2006-12-23 06:05:41 +00001580 SCEVHandle TC = HowFarToZero(SCEV::getMinusSCEV(LHS, RHS), L);
1581 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00001582 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001583 }
1584 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00001585 // Convert to: while (X-Y == 0) // while (X == Y)
Reid Spencere4d87aa2006-12-23 06:05:41 +00001586 SCEVHandle TC = HowFarToNonZero(SCEV::getMinusSCEV(LHS, RHS), L);
1587 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00001588 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001589 }
1590 case ICmpInst::ICMP_SLT: {
1591 SCEVHandle TC = HowManyLessThans(LHS, RHS, L);
1592 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00001593 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001594 }
1595 case ICmpInst::ICMP_SGT: {
1596 SCEVHandle TC = HowManyLessThans(RHS, LHS, L);
1597 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00001598 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001599 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001600 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001601#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001602 cerr << "ComputeIterationCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00001603 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Bill Wendlinge8156192006-12-07 01:30:32 +00001604 cerr << "[unsigned] ";
1605 cerr << *LHS << " "
Reid Spencere4d87aa2006-12-23 06:05:41 +00001606 << Instruction::getOpcodeName(Instruction::ICmp)
1607 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001608#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00001609 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001610 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001611 return ComputeIterationCountExhaustively(L, ExitCond,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001612 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner7980fb92004-04-17 18:36:24 +00001613}
1614
Chris Lattner673e02b2004-10-12 01:49:27 +00001615static ConstantInt *
1616EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1617 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1618 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1619 assert(isa<SCEVConstant>(Val) &&
1620 "Evaluation of SCEV at constant didn't fold correctly?");
1621 return cast<SCEVConstant>(Val)->getValue();
1622}
1623
1624/// GetAddressedElementFromGlobal - Given a global variable with an initializer
1625/// and a GEP expression (missing the pointer index) indexing into it, return
1626/// the addressed element of the initializer or null if the index expression is
1627/// invalid.
1628static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001629GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00001630 const std::vector<ConstantInt*> &Indices) {
1631 Constant *Init = GV->getInitializer();
1632 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001633 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00001634 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1635 assert(Idx < CS->getNumOperands() && "Bad struct index!");
1636 Init = cast<Constant>(CS->getOperand(Idx));
1637 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1638 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
1639 Init = cast<Constant>(CA->getOperand(Idx));
1640 } else if (isa<ConstantAggregateZero>(Init)) {
1641 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1642 assert(Idx < STy->getNumElements() && "Bad struct index!");
1643 Init = Constant::getNullValue(STy->getElementType(Idx));
1644 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1645 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
1646 Init = Constant::getNullValue(ATy->getElementType());
1647 } else {
1648 assert(0 && "Unknown constant aggregate type!");
1649 }
1650 return 0;
1651 } else {
1652 return 0; // Unknown initializer type
1653 }
1654 }
1655 return Init;
1656}
1657
1658/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1659/// 'setcc load X, cst', try to se if we can compute the trip count.
1660SCEVHandle ScalarEvolutionsImpl::
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001661ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001662 const Loop *L,
1663 ICmpInst::Predicate predicate) {
Chris Lattner673e02b2004-10-12 01:49:27 +00001664 if (LI->isVolatile()) return UnknownValue;
1665
1666 // Check to see if the loaded pointer is a getelementptr of a global.
1667 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1668 if (!GEP) return UnknownValue;
1669
1670 // Make sure that it is really a constant global we are gepping, with an
1671 // initializer, and make sure the first IDX is really 0.
1672 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1673 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1674 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1675 !cast<Constant>(GEP->getOperand(1))->isNullValue())
1676 return UnknownValue;
1677
1678 // Okay, we allow one non-constant index into the GEP instruction.
1679 Value *VarIdx = 0;
1680 std::vector<ConstantInt*> Indexes;
1681 unsigned VarIdxNum = 0;
1682 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1683 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1684 Indexes.push_back(CI);
1685 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1686 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
1687 VarIdx = GEP->getOperand(i);
1688 VarIdxNum = i-2;
1689 Indexes.push_back(0);
1690 }
1691
1692 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1693 // Check to see if X is a loop variant variable value now.
1694 SCEVHandle Idx = getSCEV(VarIdx);
1695 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1696 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1697
1698 // We can only recognize very limited forms of loop index expressions, in
1699 // particular, only affine AddRec's like {C1,+,C2}.
1700 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1701 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1702 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1703 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1704 return UnknownValue;
1705
1706 unsigned MaxSteps = MaxBruteForceIterations;
1707 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001708 ConstantInt *ItCst =
Reid Spencerc5b206b2006-12-31 05:48:39 +00001709 ConstantInt::get(IdxExpr->getType(), IterationNum);
Chris Lattner673e02b2004-10-12 01:49:27 +00001710 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst);
1711
1712 // Form the GEP offset.
1713 Indexes[VarIdxNum] = Val;
1714
1715 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
1716 if (Result == 0) break; // Cannot compute!
1717
1718 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001719 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001720 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencer579dca12007-01-12 04:24:46 +00001721 if (cast<ConstantInt>(Result)->getZExtValue() == false) {
Chris Lattner673e02b2004-10-12 01:49:27 +00001722#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001723 cerr << "\n***\n*** Computed loop count " << *ItCst
1724 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
1725 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00001726#endif
1727 ++NumArrayLenItCounts;
1728 return SCEVConstant::get(ItCst); // Found terminating iteration!
1729 }
1730 }
1731 return UnknownValue;
1732}
1733
1734
Chris Lattner3221ad02004-04-17 22:58:41 +00001735/// CanConstantFold - Return true if we can constant fold an instruction of the
1736/// specified type, assuming that all operands were constants.
1737static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00001738 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00001739 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1740 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001741
Chris Lattner3221ad02004-04-17 22:58:41 +00001742 if (const CallInst *CI = dyn_cast<CallInst>(I))
1743 if (const Function *F = CI->getCalledFunction())
1744 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1745 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00001746}
1747
Chris Lattner3221ad02004-04-17 22:58:41 +00001748/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1749/// in the loop that V is derived from. We allow arbitrary operations along the
1750/// way, but the operands of an operation must either be constants or a value
1751/// derived from a constant PHI. If this expression does not fit with these
1752/// constraints, return null.
1753static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1754 // If this is not an instruction, or if this is an instruction outside of the
1755 // loop, it can't be derived from a loop PHI.
1756 Instruction *I = dyn_cast<Instruction>(V);
1757 if (I == 0 || !L->contains(I->getParent())) return 0;
1758
1759 if (PHINode *PN = dyn_cast<PHINode>(I))
1760 if (L->getHeader() == I->getParent())
1761 return PN;
1762 else
1763 // We don't currently keep track of the control flow needed to evaluate
1764 // PHIs, so we cannot handle PHIs inside of loops.
1765 return 0;
1766
1767 // If we won't be able to constant fold this expression even if the operands
1768 // are constants, return early.
1769 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001770
Chris Lattner3221ad02004-04-17 22:58:41 +00001771 // Otherwise, we can evaluate this instruction if all of its operands are
1772 // constant or derived from a PHI node themselves.
1773 PHINode *PHI = 0;
1774 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1775 if (!(isa<Constant>(I->getOperand(Op)) ||
1776 isa<GlobalValue>(I->getOperand(Op)))) {
1777 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1778 if (P == 0) return 0; // Not evolving from PHI
1779 if (PHI == 0)
1780 PHI = P;
1781 else if (PHI != P)
1782 return 0; // Evolving from multiple different PHIs.
1783 }
1784
1785 // This is a expression evolving from a constant PHI!
1786 return PHI;
1787}
1788
1789/// EvaluateExpression - Given an expression that passes the
1790/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1791/// in the loop has the value PHIVal. If we can't fold this expression for some
1792/// reason, return null.
1793static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1794 if (isa<PHINode>(V)) return PHIVal;
Chris Lattner3221ad02004-04-17 22:58:41 +00001795 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
Reid Spencere8404342004-07-18 00:18:30 +00001796 return GV;
1797 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00001798 Instruction *I = cast<Instruction>(V);
1799
1800 std::vector<Constant*> Operands;
1801 Operands.resize(I->getNumOperands());
1802
1803 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1804 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1805 if (Operands[i] == 0) return 0;
1806 }
1807
Chris Lattner2e3a1d12007-01-30 23:52:44 +00001808 return ConstantFoldInstOperands(I, &Operands[0], Operands.size());
Chris Lattner3221ad02004-04-17 22:58:41 +00001809}
1810
1811/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1812/// in the header of its containing loop, we know the loop executes a
1813/// constant number of times, and the PHI node is just a recurrence
1814/// involving constants, fold it.
1815Constant *ScalarEvolutionsImpl::
1816getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) {
1817 std::map<PHINode*, Constant*>::iterator I =
1818 ConstantEvolutionLoopExitValue.find(PN);
1819 if (I != ConstantEvolutionLoopExitValue.end())
1820 return I->second;
1821
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001822 if (Its > MaxBruteForceIterations)
Chris Lattner3221ad02004-04-17 22:58:41 +00001823 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1824
1825 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1826
1827 // Since the loop is canonicalized, the PHI node must have two entries. One
1828 // entry must be a constant (coming in from outside of the loop), and the
1829 // second must be derived from the same PHI.
1830 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1831 Constant *StartCST =
1832 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1833 if (StartCST == 0)
1834 return RetVal = 0; // Must be a constant.
1835
1836 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1837 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1838 if (PN2 != PN)
1839 return RetVal = 0; // Not derived from same PHI.
1840
1841 // Execute the loop symbolically to determine the exit value.
1842 unsigned IterationNum = 0;
1843 unsigned NumIterations = Its;
1844 if (NumIterations != Its)
1845 return RetVal = 0; // More than 2^32 iterations??
1846
1847 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1848 if (IterationNum == NumIterations)
1849 return RetVal = PHIVal; // Got exit value!
1850
1851 // Compute the value of the PHI node for the next iteration.
1852 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1853 if (NextPHI == PHIVal)
1854 return RetVal = NextPHI; // Stopped evolving!
1855 if (NextPHI == 0)
1856 return 0; // Couldn't evaluate!
1857 PHIVal = NextPHI;
1858 }
1859}
1860
Chris Lattner7980fb92004-04-17 18:36:24 +00001861/// ComputeIterationCountExhaustively - If the trip is known to execute a
1862/// constant number of times (the condition evolves only from constants),
1863/// try to evaluate a few iterations of the loop until we get the exit
1864/// condition gets a value of ExitWhen (true or false). If we cannot
1865/// evaluate the trip count of the loop, return UnknownValue.
1866SCEVHandle ScalarEvolutionsImpl::
1867ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1868 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1869 if (PN == 0) return UnknownValue;
1870
1871 // Since the loop is canonicalized, the PHI node must have two entries. One
1872 // entry must be a constant (coming in from outside of the loop), and the
1873 // second must be derived from the same PHI.
1874 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1875 Constant *StartCST =
1876 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1877 if (StartCST == 0) return UnknownValue; // Must be a constant.
1878
1879 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1880 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1881 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
1882
1883 // Okay, we find a PHI node that defines the trip count of this loop. Execute
1884 // the loop symbolically to determine when the condition gets a value of
1885 // "ExitWhen".
1886 unsigned IterationNum = 0;
1887 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
1888 for (Constant *PHIVal = StartCST;
1889 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001890 ConstantInt *CondVal =
1891 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00001892
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001893 // Couldn't symbolically evaluate.
Chris Lattneref3baf02007-01-12 18:28:58 +00001894 if (!CondVal) return UnknownValue;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001895
Jeff Cohen1b307542007-01-15 20:27:18 +00001896 if (CondVal->getZExtValue() == uint64_t(ExitWhen)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00001897 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00001898 ++NumBruteForceTripCountsComputed;
Reid Spencerc5b206b2006-12-31 05:48:39 +00001899 return SCEVConstant::get(ConstantInt::get(Type::Int32Ty, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00001900 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001901
Chris Lattner3221ad02004-04-17 22:58:41 +00001902 // Compute the value of the PHI node for the next iteration.
1903 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1904 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00001905 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00001906 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00001907 }
1908
1909 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00001910 return UnknownValue;
1911}
1912
1913/// getSCEVAtScope - Compute the value of the specified expression within the
1914/// indicated loop (which may be null to indicate in no loop). If the
1915/// expression cannot be evaluated, return UnknownValue.
1916SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1917 // FIXME: this should be turned into a virtual method on SCEV!
1918
Chris Lattner3221ad02004-04-17 22:58:41 +00001919 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001920
Chris Lattner3221ad02004-04-17 22:58:41 +00001921 // If this instruction is evolves from a constant-evolving PHI, compute the
1922 // exit value from the loop without using SCEVs.
1923 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
1924 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
1925 const Loop *LI = this->LI[I->getParent()];
1926 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
1927 if (PHINode *PN = dyn_cast<PHINode>(I))
1928 if (PN->getParent() == LI->getHeader()) {
1929 // Okay, there is no closed form solution for the PHI node. Check
1930 // to see if the loop that contains it has a known iteration count.
1931 // If so, we may be able to force computation of the exit value.
1932 SCEVHandle IterationCount = getIterationCount(LI);
1933 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
1934 // Okay, we know how many times the containing loop executes. If
1935 // this is a constant evolving PHI node, get the final value at
1936 // the specified iteration number.
1937 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Reid Spencerb83eb642006-10-20 07:07:24 +00001938 ICC->getValue()->getZExtValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00001939 LI);
1940 if (RV) return SCEVUnknown::get(RV);
1941 }
1942 }
1943
Reid Spencer09906f32006-12-04 21:33:23 +00001944 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00001945 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00001946 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00001947 // result. This is particularly useful for computing loop exit values.
1948 if (CanConstantFold(I)) {
1949 std::vector<Constant*> Operands;
1950 Operands.reserve(I->getNumOperands());
1951 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1952 Value *Op = I->getOperand(i);
1953 if (Constant *C = dyn_cast<Constant>(Op)) {
1954 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00001955 } else {
1956 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
1957 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
Reid Spencerd977d862006-12-12 23:36:14 +00001958 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
1959 Op->getType(),
1960 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00001961 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
1962 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
Reid Spencerd977d862006-12-12 23:36:14 +00001963 Operands.push_back(ConstantExpr::getIntegerCast(C,
1964 Op->getType(),
1965 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00001966 else
1967 return V;
1968 } else {
1969 return V;
1970 }
1971 }
1972 }
Chris Lattner2e3a1d12007-01-30 23:52:44 +00001973 Constant *C =ConstantFoldInstOperands(I, &Operands[0], Operands.size());
1974 return SCEVUnknown::get(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00001975 }
1976 }
1977
1978 // This is some other type of SCEVUnknown, just return it.
1979 return V;
1980 }
1981
Chris Lattner53e677a2004-04-02 20:23:17 +00001982 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
1983 // Avoid performing the look-up in the common case where the specified
1984 // expression has no loop-variant portions.
1985 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
1986 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1987 if (OpAtScope != Comm->getOperand(i)) {
1988 if (OpAtScope == UnknownValue) return UnknownValue;
1989 // Okay, at least one of these operands is loop variant but might be
1990 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00001991 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00001992 NewOps.push_back(OpAtScope);
1993
1994 for (++i; i != e; ++i) {
1995 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1996 if (OpAtScope == UnknownValue) return UnknownValue;
1997 NewOps.push_back(OpAtScope);
1998 }
1999 if (isa<SCEVAddExpr>(Comm))
2000 return SCEVAddExpr::get(NewOps);
2001 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
2002 return SCEVMulExpr::get(NewOps);
2003 }
2004 }
2005 // If we got here, all operands are loop invariant.
2006 return Comm;
2007 }
2008
Chris Lattner60a05cc2006-04-01 04:48:52 +00002009 if (SCEVSDivExpr *Div = dyn_cast<SCEVSDivExpr>(V)) {
2010 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002011 if (LHS == UnknownValue) return LHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002012 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002013 if (RHS == UnknownValue) return RHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002014 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2015 return Div; // must be loop invariant
2016 return SCEVSDivExpr::get(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00002017 }
2018
2019 // If this is a loop recurrence for a loop that does not contain L, then we
2020 // are dealing with the final value computed by the loop.
2021 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2022 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2023 // To evaluate this recurrence, we need to know how many times the AddRec
2024 // loop iterates. Compute this now.
2025 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2026 if (IterationCount == UnknownValue) return UnknownValue;
2027 IterationCount = getTruncateOrZeroExtend(IterationCount,
2028 AddRec->getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002029
Chris Lattner53e677a2004-04-02 20:23:17 +00002030 // If the value is affine, simplify the expression evaluation to just
2031 // Start + Step*IterationCount.
2032 if (AddRec->isAffine())
2033 return SCEVAddExpr::get(AddRec->getStart(),
2034 SCEVMulExpr::get(IterationCount,
2035 AddRec->getOperand(1)));
2036
2037 // Otherwise, evaluate it the hard way.
2038 return AddRec->evaluateAtIteration(IterationCount);
2039 }
2040 return UnknownValue;
2041 }
2042
2043 //assert(0 && "Unknown SCEV type!");
2044 return UnknownValue;
2045}
2046
2047
2048/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2049/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2050/// might be the same) or two SCEVCouldNotCompute objects.
2051///
2052static std::pair<SCEVHandle,SCEVHandle>
2053SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
2054 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2055 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2056 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2057 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002058
Chris Lattner53e677a2004-04-02 20:23:17 +00002059 // We currently can only solve this if the coefficients are constants.
2060 if (!L || !M || !N) {
2061 SCEV *CNC = new SCEVCouldNotCompute();
2062 return std::make_pair(CNC, CNC);
2063 }
2064
Reid Spencer1628cec2006-10-26 06:15:43 +00002065 Constant *C = L->getValue();
2066 Constant *Two = ConstantInt::get(C->getType(), 2);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002067
Chris Lattner53e677a2004-04-02 20:23:17 +00002068 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
Chris Lattner53e677a2004-04-02 20:23:17 +00002069 // The B coefficient is M-N/2
2070 Constant *B = ConstantExpr::getSub(M->getValue(),
Reid Spencer1628cec2006-10-26 06:15:43 +00002071 ConstantExpr::getSDiv(N->getValue(),
Chris Lattner53e677a2004-04-02 20:23:17 +00002072 Two));
2073 // The A coefficient is N/2
Reid Spencer1628cec2006-10-26 06:15:43 +00002074 Constant *A = ConstantExpr::getSDiv(N->getValue(), Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002075
Chris Lattner53e677a2004-04-02 20:23:17 +00002076 // Compute the B^2-4ac term.
2077 Constant *SqrtTerm =
2078 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
2079 ConstantExpr::getMul(A, C));
2080 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
2081
2082 // Compute floor(sqrt(B^2-4ac))
Reid Spencerc5b206b2006-12-31 05:48:39 +00002083 uint64_t SqrtValV = cast<ConstantInt>(SqrtTerm)->getZExtValue();
Chris Lattner219c1412004-10-25 18:40:08 +00002084 uint64_t SqrtValV2 = (uint64_t)sqrt((double)SqrtValV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002085 // The square root might not be precise for arbitrary 64-bit integer
2086 // values. Do some sanity checks to ensure it's correct.
2087 if (SqrtValV2*SqrtValV2 > SqrtValV ||
2088 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
2089 SCEV *CNC = new SCEVCouldNotCompute();
2090 return std::make_pair(CNC, CNC);
2091 }
2092
Reid Spencerc5b206b2006-12-31 05:48:39 +00002093 ConstantInt *SqrtVal = ConstantInt::get(Type::Int64Ty, SqrtValV2);
Reid Spencerd977d862006-12-12 23:36:14 +00002094 SqrtTerm = ConstantExpr::getTruncOrBitCast(SqrtVal, SqrtTerm->getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002095
Chris Lattner53e677a2004-04-02 20:23:17 +00002096 Constant *NegB = ConstantExpr::getNeg(B);
2097 Constant *TwoA = ConstantExpr::getMul(A, Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002098
Chris Lattner53e677a2004-04-02 20:23:17 +00002099 // The divisions must be performed as signed divisions.
Chris Lattner53e677a2004-04-02 20:23:17 +00002100 Constant *Solution1 =
Reid Spencer1628cec2006-10-26 06:15:43 +00002101 ConstantExpr::getSDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
Chris Lattner53e677a2004-04-02 20:23:17 +00002102 Constant *Solution2 =
Reid Spencer1628cec2006-10-26 06:15:43 +00002103 ConstantExpr::getSDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
Chris Lattner53e677a2004-04-02 20:23:17 +00002104 return std::make_pair(SCEVUnknown::get(Solution1),
2105 SCEVUnknown::get(Solution2));
2106}
2107
2108/// HowFarToZero - Return the number of times a backedge comparing the specified
2109/// value to zero will execute. If not computable, return UnknownValue
2110SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2111 // If the value is a constant
2112 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2113 // If the value is already zero, the branch will execute zero times.
2114 if (C->getValue()->isNullValue()) return C;
2115 return UnknownValue; // Otherwise it will loop infinitely.
2116 }
2117
2118 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2119 if (!AddRec || AddRec->getLoop() != L)
2120 return UnknownValue;
2121
2122 if (AddRec->isAffine()) {
2123 // If this is an affine expression the execution count of this branch is
2124 // equal to:
2125 //
2126 // (0 - Start/Step) iff Start % Step == 0
2127 //
2128 // Get the initial value for the loop.
2129 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00002130 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002131 SCEVHandle Step = AddRec->getOperand(1);
2132
2133 Step = getSCEVAtScope(Step, L->getParentLoop());
2134
2135 // Figure out if Start % Step == 0.
2136 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2137 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2138 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
Chris Lattnerbac5b462005-03-09 05:34:41 +00002139 return SCEV::getNegativeSCEV(Start); // 0 - Start/1 == -Start
Chris Lattner53e677a2004-04-02 20:23:17 +00002140 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2141 return Start; // 0 - Start/-1 == Start
2142
2143 // Check to see if Start is divisible by SC with no remainder.
2144 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2145 ConstantInt *StartCC = StartC->getValue();
2146 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
Reid Spencer0a783f72006-11-02 01:53:59 +00002147 Constant *Rem = ConstantExpr::getSRem(StartNegC, StepC->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +00002148 if (Rem->isNullValue()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002149 Constant *Result =ConstantExpr::getSDiv(StartNegC,StepC->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +00002150 return SCEVUnknown::get(Result);
2151 }
2152 }
2153 }
Chris Lattner42a75512007-01-15 02:27:26 +00002154 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002155 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2156 // the quadratic equation to solve it.
2157 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
2158 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2159 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2160 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002161#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002162 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2163 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002164#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002165 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002166 if (ConstantInt *CB =
2167 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002168 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002169 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002170 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002171
Chris Lattner53e677a2004-04-02 20:23:17 +00002172 // We can only use this value if the chrec ends up with an exact zero
2173 // value at this index. When solving for "X*X != 5", for example, we
2174 // should not accept a root of 2.
2175 SCEVHandle Val = AddRec->evaluateAtIteration(R1);
2176 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
2177 if (EvalVal->getValue()->isNullValue())
2178 return R1; // We found a quadratic root!
2179 }
2180 }
2181 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002182
Chris Lattner53e677a2004-04-02 20:23:17 +00002183 return UnknownValue;
2184}
2185
2186/// HowFarToNonZero - Return the number of times a backedge checking the
2187/// specified value for nonzero will execute. If not computable, return
2188/// UnknownValue
2189SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2190 // Loops that look like: while (X == 0) are very strange indeed. We don't
2191 // handle them yet except for the trivial case. This could be expanded in the
2192 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002193
Chris Lattner53e677a2004-04-02 20:23:17 +00002194 // If the value is a constant, check to see if it is known to be non-zero
2195 // already. If so, the backedge will execute zero times.
2196 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2197 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002198 Constant *NonZero =
2199 ConstantExpr::getICmp(ICmpInst::ICMP_NE, C->getValue(), Zero);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002200 if (NonZero == ConstantInt::getTrue())
Chris Lattner53e677a2004-04-02 20:23:17 +00002201 return getSCEV(Zero);
2202 return UnknownValue; // Otherwise it will loop infinitely.
2203 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002204
Chris Lattner53e677a2004-04-02 20:23:17 +00002205 // We could implement others, but I really doubt anyone writes loops like
2206 // this, and if they did, they would already be constant folded.
2207 return UnknownValue;
2208}
2209
Chris Lattnerdb25de42005-08-15 23:33:51 +00002210/// HowManyLessThans - Return the number of times a backedge containing the
2211/// specified less-than comparison will execute. If not computable, return
2212/// UnknownValue.
2213SCEVHandle ScalarEvolutionsImpl::
2214HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L) {
2215 // Only handle: "ADDREC < LoopInvariant".
2216 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2217
2218 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2219 if (!AddRec || AddRec->getLoop() != L)
2220 return UnknownValue;
2221
2222 if (AddRec->isAffine()) {
2223 // FORNOW: We only support unit strides.
2224 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, RHS->getType());
2225 if (AddRec->getOperand(1) != One)
2226 return UnknownValue;
2227
2228 // The number of iterations for "[n,+,1] < m", is m-n. However, we don't
2229 // know that m is >= n on input to the loop. If it is, the condition return
2230 // true zero times. What we really should return, for full generality, is
2231 // SMAX(0, m-n). Since we cannot check this, we will instead check for a
2232 // canonical loop form: most do-loops will have a check that dominates the
2233 // loop, that only enters the loop if [n-1]<m. If we can find this check,
2234 // we know that the SMAX will evaluate to m-n, because we know that m >= n.
2235
2236 // Search for the check.
2237 BasicBlock *Preheader = L->getLoopPreheader();
2238 BasicBlock *PreheaderDest = L->getHeader();
2239 if (Preheader == 0) return UnknownValue;
2240
2241 BranchInst *LoopEntryPredicate =
2242 dyn_cast<BranchInst>(Preheader->getTerminator());
2243 if (!LoopEntryPredicate) return UnknownValue;
2244
2245 // This might be a critical edge broken out. If the loop preheader ends in
2246 // an unconditional branch to the loop, check to see if the preheader has a
2247 // single predecessor, and if so, look for its terminator.
2248 while (LoopEntryPredicate->isUnconditional()) {
2249 PreheaderDest = Preheader;
2250 Preheader = Preheader->getSinglePredecessor();
2251 if (!Preheader) return UnknownValue; // Multiple preds.
2252
2253 LoopEntryPredicate =
2254 dyn_cast<BranchInst>(Preheader->getTerminator());
2255 if (!LoopEntryPredicate) return UnknownValue;
2256 }
2257
2258 // Now that we found a conditional branch that dominates the loop, check to
2259 // see if it is the comparison we are looking for.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002260 if (ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition())){
2261 Value *PreCondLHS = ICI->getOperand(0);
2262 Value *PreCondRHS = ICI->getOperand(1);
2263 ICmpInst::Predicate Cond;
2264 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2265 Cond = ICI->getPredicate();
2266 else
2267 Cond = ICI->getInversePredicate();
Chris Lattnerdb25de42005-08-15 23:33:51 +00002268
Reid Spencere4d87aa2006-12-23 06:05:41 +00002269 switch (Cond) {
2270 case ICmpInst::ICMP_UGT:
2271 std::swap(PreCondLHS, PreCondRHS);
2272 Cond = ICmpInst::ICMP_ULT;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002273 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002274 case ICmpInst::ICMP_SGT:
2275 std::swap(PreCondLHS, PreCondRHS);
2276 Cond = ICmpInst::ICMP_SLT;
2277 break;
2278 default: break;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002279 }
Chris Lattnerdb25de42005-08-15 23:33:51 +00002280
Reid Spencere4d87aa2006-12-23 06:05:41 +00002281 if (Cond == ICmpInst::ICMP_SLT) {
Chris Lattner42a75512007-01-15 02:27:26 +00002282 if (PreCondLHS->getType()->isInteger()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002283 if (RHS != getSCEV(PreCondRHS))
2284 return UnknownValue; // Not a comparison against 'm'.
2285
2286 if (SCEV::getMinusSCEV(AddRec->getOperand(0), One)
2287 != getSCEV(PreCondLHS))
2288 return UnknownValue; // Not a comparison against 'n-1'.
2289 }
2290 else return UnknownValue;
2291 } else if (Cond == ICmpInst::ICMP_ULT)
2292 return UnknownValue;
2293
2294 // cerr << "Computed Loop Trip Count as: "
2295 // << // *SCEV::getMinusSCEV(RHS, AddRec->getOperand(0)) << "\n";
2296 return SCEV::getMinusSCEV(RHS, AddRec->getOperand(0));
2297 }
2298 else
2299 return UnknownValue;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002300 }
2301
2302 return UnknownValue;
2303}
2304
Chris Lattner53e677a2004-04-02 20:23:17 +00002305/// getNumIterationsInRange - Return the number of iterations of this loop that
2306/// produce values in the specified constant range. Another way of looking at
2307/// this is that it returns the first iteration number where the value is not in
2308/// the condition, thus computing the exit count. If the iteration count can't
2309/// be computed, an instance of SCEVCouldNotCompute is returned.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002310SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2311 bool isSigned) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002312 if (Range.isFullSet()) // Infinite loop.
2313 return new SCEVCouldNotCompute();
2314
2315 // If the start is a non-zero constant, shift the range to simplify things.
2316 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2317 if (!SC->getValue()->isNullValue()) {
2318 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Chris Lattnerb06432c2004-04-23 21:29:03 +00002319 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002320 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2321 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2322 return ShiftedAddRec->getNumIterationsInRange(
Reid Spencere4d87aa2006-12-23 06:05:41 +00002323 Range.subtract(SC->getValue()),isSigned);
Chris Lattner53e677a2004-04-02 20:23:17 +00002324 // This is strange and shouldn't happen.
2325 return new SCEVCouldNotCompute();
2326 }
2327
2328 // The only time we can solve this is when we have all constant indices.
2329 // Otherwise, we cannot determine the overflow conditions.
2330 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2331 if (!isa<SCEVConstant>(getOperand(i)))
2332 return new SCEVCouldNotCompute();
2333
2334
2335 // Okay at this point we know that all elements of the chrec are constants and
2336 // that the start element is zero.
2337
2338 // First check to see if the range contains zero. If not, the first
2339 // iteration exits.
2340 ConstantInt *Zero = ConstantInt::get(getType(), 0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002341 if (!Range.contains(Zero, isSigned)) return SCEVConstant::get(Zero);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002342
Chris Lattner53e677a2004-04-02 20:23:17 +00002343 if (isAffine()) {
2344 // If this is an affine expression then we have this situation:
2345 // Solve {0,+,A} in Range === Ax in Range
2346
2347 // Since we know that zero is in the range, we know that the upper value of
2348 // the range must be the first possible exit value. Also note that we
2349 // already checked for a full range.
2350 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
2351 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue();
2352 ConstantInt *One = ConstantInt::get(getType(), 1);
2353
2354 // The exit value should be (Upper+A-1)/A.
2355 Constant *ExitValue = Upper;
2356 if (A != One) {
2357 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
Reid Spencer1628cec2006-10-26 06:15:43 +00002358 ExitValue = ConstantExpr::getSDiv(ExitValue, A);
Chris Lattner53e677a2004-04-02 20:23:17 +00002359 }
2360 assert(isa<ConstantInt>(ExitValue) &&
2361 "Constant folding of integers not implemented?");
2362
2363 // Evaluate at the exit value. If we really did fall out of the valid
2364 // range, then we computed our trip count, otherwise wrap around or other
2365 // things must have happened.
2366 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002367 if (Range.contains(Val, isSigned))
Chris Lattner53e677a2004-04-02 20:23:17 +00002368 return new SCEVCouldNotCompute(); // Something strange happened
2369
2370 // Ensure that the previous value is in the range. This is a sanity check.
2371 assert(Range.contains(EvaluateConstantChrecAtConstant(this,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002372 ConstantExpr::getSub(ExitValue, One)), isSigned) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002373 "Linear scev computation is off in a bad way!");
2374 return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2375 } else if (isQuadratic()) {
2376 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2377 // quadratic equation to solve it. To do this, we must frame our problem in
2378 // terms of figuring out when zero is crossed, instead of when
2379 // Range.getUpper() is crossed.
2380 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Chris Lattnerbac5b462005-03-09 05:34:41 +00002381 NewOps[0] = SCEV::getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
Chris Lattner53e677a2004-04-02 20:23:17 +00002382 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2383
2384 // Next, solve the constructed addrec
2385 std::pair<SCEVHandle,SCEVHandle> Roots =
2386 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2387 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2388 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2389 if (R1) {
2390 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002391 if (ConstantInt *CB =
2392 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002393 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002394 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002395 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002396
Chris Lattner53e677a2004-04-02 20:23:17 +00002397 // Make sure the root is not off by one. The returned iteration should
2398 // not be in the range, but the previous one should be. When solving
2399 // for "X*X < 5", for example, we should not return a root of 2.
2400 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2401 R1->getValue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002402 if (Range.contains(R1Val, isSigned)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002403 // The next iteration must be out of the range...
2404 Constant *NextVal =
2405 ConstantExpr::getAdd(R1->getValue(),
2406 ConstantInt::get(R1->getType(), 1));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002407
Chris Lattner53e677a2004-04-02 20:23:17 +00002408 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002409 if (!Range.contains(R1Val, isSigned))
Chris Lattner53e677a2004-04-02 20:23:17 +00002410 return SCEVUnknown::get(NextVal);
2411 return new SCEVCouldNotCompute(); // Something strange happened
2412 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002413
Chris Lattner53e677a2004-04-02 20:23:17 +00002414 // If R1 was not in the range, then it is a good return value. Make
2415 // sure that R1-1 WAS in the range though, just in case.
2416 Constant *NextVal =
2417 ConstantExpr::getSub(R1->getValue(),
2418 ConstantInt::get(R1->getType(), 1));
2419 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002420 if (Range.contains(R1Val, isSigned))
Chris Lattner53e677a2004-04-02 20:23:17 +00002421 return R1;
2422 return new SCEVCouldNotCompute(); // Something strange happened
2423 }
2424 }
2425 }
2426
2427 // Fallback, if this is a general polynomial, figure out the progression
2428 // through brute force: evaluate until we find an iteration that fails the
2429 // test. This is likely to be slow, but getting an accurate trip count is
2430 // incredibly important, we will be able to simplify the exit test a lot, and
2431 // we are almost guaranteed to get a trip count in this case.
2432 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2433 ConstantInt *One = ConstantInt::get(getType(), 1);
2434 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2435 do {
2436 ++NumBruteForceEvaluations;
2437 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2438 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2439 return new SCEVCouldNotCompute();
2440
2441 // Check to see if we found the value!
Reid Spencere4d87aa2006-12-23 06:05:41 +00002442 if (!Range.contains(cast<SCEVConstant>(Val)->getValue(), isSigned))
Chris Lattner53e677a2004-04-02 20:23:17 +00002443 return SCEVConstant::get(TestVal);
2444
2445 // Increment to test the next index.
2446 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
2447 } while (TestVal != EndVal);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002448
Chris Lattner53e677a2004-04-02 20:23:17 +00002449 return new SCEVCouldNotCompute();
2450}
2451
2452
2453
2454//===----------------------------------------------------------------------===//
2455// ScalarEvolution Class Implementation
2456//===----------------------------------------------------------------------===//
2457
2458bool ScalarEvolution::runOnFunction(Function &F) {
2459 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2460 return false;
2461}
2462
2463void ScalarEvolution::releaseMemory() {
2464 delete (ScalarEvolutionsImpl*)Impl;
2465 Impl = 0;
2466}
2467
2468void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2469 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00002470 AU.addRequiredTransitive<LoopInfo>();
2471}
2472
2473SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2474 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2475}
2476
Chris Lattnera0740fb2005-08-09 23:36:33 +00002477/// hasSCEV - Return true if the SCEV for this value has already been
2478/// computed.
2479bool ScalarEvolution::hasSCEV(Value *V) const {
Chris Lattner05bd3742005-08-10 00:59:40 +00002480 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
Chris Lattnera0740fb2005-08-09 23:36:33 +00002481}
2482
2483
2484/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2485/// the specified value.
2486void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2487 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2488}
2489
2490
Chris Lattner53e677a2004-04-02 20:23:17 +00002491SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2492 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2493}
2494
2495bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2496 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2497}
2498
2499SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2500 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2501}
2502
2503void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2504 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2505}
2506
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002507static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00002508 const Loop *L) {
2509 // Print all inner loops first
2510 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2511 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002512
Bill Wendlinge8156192006-12-07 01:30:32 +00002513 cerr << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002514
2515 std::vector<BasicBlock*> ExitBlocks;
2516 L->getExitBlocks(ExitBlocks);
2517 if (ExitBlocks.size() != 1)
Bill Wendlinge8156192006-12-07 01:30:32 +00002518 cerr << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002519
2520 if (SE->hasLoopInvariantIterationCount(L)) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002521 cerr << *SE->getIterationCount(L) << " iterations! ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002522 } else {
Bill Wendlinge8156192006-12-07 01:30:32 +00002523 cerr << "Unpredictable iteration count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002524 }
2525
Bill Wendlinge8156192006-12-07 01:30:32 +00002526 cerr << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00002527}
2528
Reid Spencerce9653c2004-12-07 04:03:45 +00002529void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002530 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2531 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2532
2533 OS << "Classifying expressions for: " << F.getName() << "\n";
2534 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner42a75512007-01-15 02:27:26 +00002535 if (I->getType()->isInteger()) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00002536 OS << *I;
Chris Lattner53e677a2004-04-02 20:23:17 +00002537 OS << " --> ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002538 SCEVHandle SV = getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00002539 SV->print(OS);
2540 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002541
Chris Lattner42a75512007-01-15 02:27:26 +00002542 if ((*I).getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002543 ConstantRange Bounds = SV->getValueRange();
2544 if (!Bounds.isFullSet())
2545 OS << "Bounds: " << Bounds << " ";
2546 }
2547
Chris Lattner6ffe5512004-04-27 15:13:33 +00002548 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002549 OS << "Exits: ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002550 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002551 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2552 OS << "<<Unknown>>";
2553 } else {
2554 OS << *ExitValue;
2555 }
2556 }
2557
2558
2559 OS << "\n";
2560 }
2561
2562 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2563 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2564 PrintLoopInfo(OS, this, *I);
2565}
2566