blob: 59e76c0538f67eeb49d83358b141a979f71bf957 [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//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// 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(NumArrayLenItCounts,
87 "Number of trip counts computed with array length");
88STATISTIC(NumTripCountsComputed,
89 "Number of loops with predictable loop counts");
90STATISTIC(NumTripCountsNotComputed,
91 "Number of loops without predictable loop counts");
92STATISTIC(NumBruteForceTripCountsComputed,
93 "Number of loops with trip counts computed by force");
94
Dan Gohman844731a2008-05-13 00:00:25 +000095static cl::opt<unsigned>
Chris Lattner3b27d682006-12-19 22:30:33 +000096MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
97 cl::desc("Maximum number of iterations SCEV will "
98 "symbolically execute a constant derived loop"),
99 cl::init(100));
100
Dan Gohman844731a2008-05-13 00:00:25 +0000101static RegisterPass<ScalarEvolution>
102R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Devang Patel19974732007-05-03 01:11:54 +0000103char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000104
105//===----------------------------------------------------------------------===//
106// SCEV class definitions
107//===----------------------------------------------------------------------===//
108
109//===----------------------------------------------------------------------===//
110// Implementation of the SCEV class.
111//
Chris Lattner53e677a2004-04-02 20:23:17 +0000112SCEV::~SCEV() {}
113void SCEV::dump() const {
Bill Wendlinge8156192006-12-07 01:30:32 +0000114 print(cerr);
Nick Lewyckyd1f5fab2009-01-16 17:07:22 +0000115 cerr << '\n';
Chris Lattner53e677a2004-04-02 20:23:17 +0000116}
117
Reid Spencer581b0d42007-02-28 19:57:34 +0000118uint32_t SCEV::getBitWidth() const {
119 if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
120 return ITy->getBitWidth();
121 return 0;
122}
123
Dan Gohmancfeb6a42008-06-18 16:23:07 +0000124bool SCEV::isZero() const {
125 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
126 return SC->getValue()->isZero();
127 return false;
128}
129
Chris Lattner53e677a2004-04-02 20:23:17 +0000130
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,
Dan Gohman246b2562007-10-22 18:31:58 +0000150 const SCEVHandle &Conc,
151 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000152 return this;
153}
154
Chris Lattner53e677a2004-04-02 20:23:17 +0000155void SCEVCouldNotCompute::print(std::ostream &OS) const {
156 OS << "***COULDNOTCOMPUTE***";
157}
158
159bool SCEVCouldNotCompute::classof(const SCEV *S) {
160 return S->getSCEVType() == scCouldNotCompute;
161}
162
163
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000164// SCEVConstants - Only allow the creation of one SCEVConstant for any
165// particular value. Don't use a SCEVHandle here, or else the object will
166// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000167static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000168
Chris Lattner53e677a2004-04-02 20:23:17 +0000169
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000170SCEVConstant::~SCEVConstant() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000171 SCEVConstants->erase(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000172}
Chris Lattner53e677a2004-04-02 20:23:17 +0000173
Dan Gohman246b2562007-10-22 18:31:58 +0000174SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Chris Lattnerb3364092006-10-04 21:49:37 +0000175 SCEVConstant *&R = (*SCEVConstants)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000176 if (R == 0) R = new SCEVConstant(V);
177 return R;
178}
Chris Lattner53e677a2004-04-02 20:23:17 +0000179
Dan Gohman246b2562007-10-22 18:31:58 +0000180SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
181 return getConstant(ConstantInt::get(Val));
Dan Gohman9a6ae962007-07-09 15:25:17 +0000182}
183
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000184const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000185
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000186void SCEVConstant::print(std::ostream &OS) const {
187 WriteAsOperand(OS, V, false);
188}
Chris Lattner53e677a2004-04-02 20:23:17 +0000189
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000190// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
191// particular input. Don't use a SCEVHandle here, or else the object will
192// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000193static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
194 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000195
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000196SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
197 : SCEV(scTruncate), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000198 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000199 "Cannot truncate non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000200 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
201 && "This is not a truncating conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000202}
Chris Lattner53e677a2004-04-02 20:23:17 +0000203
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000204SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000205 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000206}
Chris Lattner53e677a2004-04-02 20:23:17 +0000207
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000208void SCEVTruncateExpr::print(std::ostream &OS) const {
209 OS << "(truncate " << *Op << " to " << *Ty << ")";
210}
211
212// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
213// particular input. Don't use a SCEVHandle here, or else the object will never
214// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000215static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
216 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000217
218SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Reid Spencer48d8a702006-11-01 21:53:12 +0000219 : SCEV(scZeroExtend), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000220 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000221 "Cannot zero extend non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000222 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
223 && "This is not an extending conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000224}
225
226SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000227 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000228}
229
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000230void SCEVZeroExtendExpr::print(std::ostream &OS) const {
231 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
232}
233
Dan Gohmand19534a2007-06-15 14:38:12 +0000234// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
235// particular input. Don't use a SCEVHandle here, or else the object will never
236// be deleted!
237static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
238 SCEVSignExtendExpr*> > SCEVSignExtends;
239
240SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
241 : SCEV(scSignExtend), Op(op), Ty(ty) {
242 assert(Op->getType()->isInteger() && Ty->isInteger() &&
243 "Cannot sign extend non-integer value!");
244 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
245 && "This is not an extending conversion!");
246}
247
248SCEVSignExtendExpr::~SCEVSignExtendExpr() {
249 SCEVSignExtends->erase(std::make_pair(Op, Ty));
250}
251
Dan Gohmand19534a2007-06-15 14:38:12 +0000252void SCEVSignExtendExpr::print(std::ostream &OS) const {
253 OS << "(signextend " << *Op << " to " << *Ty << ")";
254}
255
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000256// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
257// particular input. Don't use a SCEVHandle here, or else the object will never
258// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000259static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
260 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000261
262SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000263 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
264 std::vector<SCEV*>(Operands.begin(),
265 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000266}
267
268void SCEVCommutativeExpr::print(std::ostream &OS) const {
269 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
270 const char *OpStr = getOperationStr();
271 OS << "(" << *Operands[0];
272 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
273 OS << OpStr << *Operands[i];
274 OS << ")";
275}
276
Chris Lattner4dc534c2005-02-13 04:37:18 +0000277SCEVHandle SCEVCommutativeExpr::
278replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000279 const SCEVHandle &Conc,
280 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000281 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000282 SCEVHandle H =
283 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000284 if (H != getOperand(i)) {
285 std::vector<SCEVHandle> NewOps;
286 NewOps.reserve(getNumOperands());
287 for (unsigned j = 0; j != i; ++j)
288 NewOps.push_back(getOperand(j));
289 NewOps.push_back(H);
290 for (++i; i != e; ++i)
291 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000292 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Chris Lattner4dc534c2005-02-13 04:37:18 +0000293
294 if (isa<SCEVAddExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000295 return SE.getAddExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000296 else if (isa<SCEVMulExpr>(this))
Dan Gohman246b2562007-10-22 18:31:58 +0000297 return SE.getMulExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +0000298 else if (isa<SCEVSMaxExpr>(this))
299 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +0000300 else if (isa<SCEVUMaxExpr>(this))
301 return SE.getUMaxExpr(NewOps);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000302 else
303 assert(0 && "Unknown commutative expr!");
304 }
305 }
306 return this;
307}
308
309
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000310// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000311// input. Don't use a SCEVHandle here, or else the object will never be
312// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000313static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000314 SCEVUDivExpr*> > SCEVUDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000315
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000316SCEVUDivExpr::~SCEVUDivExpr() {
317 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000318}
319
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000320void SCEVUDivExpr::print(std::ostream &OS) const {
321 OS << "(" << *LHS << " /u " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000322}
323
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000324const Type *SCEVUDivExpr::getType() const {
Reid Spencerc5b206b2006-12-31 05:48:39 +0000325 return LHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000326}
327
328// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
329// particular input. Don't use a SCEVHandle here, or else the object will never
330// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000331static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
332 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000333
334SCEVAddRecExpr::~SCEVAddRecExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000335 SCEVAddRecExprs->erase(std::make_pair(L,
336 std::vector<SCEV*>(Operands.begin(),
337 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000338}
339
Chris Lattner4dc534c2005-02-13 04:37:18 +0000340SCEVHandle SCEVAddRecExpr::
341replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000342 const SCEVHandle &Conc,
343 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000344 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000345 SCEVHandle H =
346 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000347 if (H != getOperand(i)) {
348 std::vector<SCEVHandle> NewOps;
349 NewOps.reserve(getNumOperands());
350 for (unsigned j = 0; j != i; ++j)
351 NewOps.push_back(getOperand(j));
352 NewOps.push_back(H);
353 for (++i; i != e; ++i)
354 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000355 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000356
Dan Gohman246b2562007-10-22 18:31:58 +0000357 return SE.getAddRecExpr(NewOps, L);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000358 }
359 }
360 return this;
361}
362
363
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000364bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
365 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000366 // contain L and if the start is invariant.
367 return !QueryLoop->contains(L->getHeader()) &&
368 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000369}
370
371
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000372void SCEVAddRecExpr::print(std::ostream &OS) const {
373 OS << "{" << *Operands[0];
374 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
375 OS << ",+," << *Operands[i];
376 OS << "}<" << L->getHeader()->getName() + ">";
377}
Chris Lattner53e677a2004-04-02 20:23:17 +0000378
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000379// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
380// value. Don't use a SCEVHandle here, or else the object will never be
381// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000382static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000383
Chris Lattnerb3364092006-10-04 21:49:37 +0000384SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000385
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000386bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
387 // All non-instruction values are loop invariant. All instructions are loop
388 // invariant if they are not contained in the specified loop.
389 if (Instruction *I = dyn_cast<Instruction>(V))
390 return !L->contains(I->getParent());
391 return true;
392}
Chris Lattner53e677a2004-04-02 20:23:17 +0000393
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000394const Type *SCEVUnknown::getType() const {
395 return V->getType();
396}
Chris Lattner53e677a2004-04-02 20:23:17 +0000397
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000398void SCEVUnknown::print(std::ostream &OS) const {
399 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000400}
401
Chris Lattner8d741b82004-06-20 06:23:15 +0000402//===----------------------------------------------------------------------===//
403// SCEV Utilities
404//===----------------------------------------------------------------------===//
405
406namespace {
407 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
408 /// than the complexity of the RHS. This comparator is used to canonicalize
409 /// expressions.
Chris Lattner95255282006-06-28 23:17:24 +0000410 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000411 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Chris Lattner8d741b82004-06-20 06:23:15 +0000412 return LHS->getSCEVType() < RHS->getSCEVType();
413 }
414 };
415}
416
417/// GroupByComplexity - Given a list of SCEV objects, order them by their
418/// complexity, and group objects of the same complexity together by value.
419/// When this routine is finished, we know that any duplicates in the vector are
420/// consecutive and that complexity is monotonically increasing.
421///
422/// Note that we go take special precautions to ensure that we get determinstic
423/// results from this routine. In other words, we don't want the results of
424/// this to depend on where the addresses of various SCEV objects happened to
425/// land in memory.
426///
427static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
428 if (Ops.size() < 2) return; // Noop
429 if (Ops.size() == 2) {
430 // This is the common case, which also happens to be trivially simple.
431 // Special case it.
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000432 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000433 std::swap(Ops[0], Ops[1]);
434 return;
435 }
436
437 // Do the rough sort by complexity.
438 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
439
440 // Now that we are sorted by complexity, group elements of the same
441 // complexity. Note that this is, at worst, N^2, but the vector is likely to
442 // be extremely short in practice. Note that we take this approach because we
443 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000444 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000445 SCEV *S = Ops[i];
446 unsigned Complexity = S->getSCEVType();
447
448 // If there are any objects of the same complexity and same value as this
449 // one, group them.
450 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
451 if (Ops[j] == S) { // Found a duplicate.
452 // Move it to immediately after i'th element.
453 std::swap(Ops[i+1], Ops[j]);
454 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000455 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000456 }
457 }
458 }
459}
460
Chris Lattner53e677a2004-04-02 20:23:17 +0000461
Chris Lattner53e677a2004-04-02 20:23:17 +0000462
463//===----------------------------------------------------------------------===//
464// Simple SCEV method implementations
465//===----------------------------------------------------------------------===//
466
467/// getIntegerSCEV - Given an integer or FP type, create a constant for the
468/// specified signed integer value and return a SCEV for the constant.
Dan Gohman246b2562007-10-22 18:31:58 +0000469SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000470 Constant *C;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000471 if (Val == 0)
Chris Lattner53e677a2004-04-02 20:23:17 +0000472 C = Constant::getNullValue(Ty);
473 else if (Ty->isFloatingPoint())
Chris Lattner02a260a2008-04-20 00:41:09 +0000474 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
475 APFloat::IEEEdouble, Val));
Reid Spencere4d87aa2006-12-23 06:05:41 +0000476 else
Reid Spencerb83eb642006-10-20 07:07:24 +0000477 C = ConstantInt::get(Ty, Val);
Dan Gohman246b2562007-10-22 18:31:58 +0000478 return getUnknown(C);
Chris Lattner53e677a2004-04-02 20:23:17 +0000479}
480
Chris Lattner53e677a2004-04-02 20:23:17 +0000481/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
482///
Dan Gohman246b2562007-10-22 18:31:58 +0000483SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000484 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman246b2562007-10-22 18:31:58 +0000485 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000486
Nick Lewycky178f20a2008-02-20 06:58:55 +0000487 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(V->getType())));
Nick Lewycky3e630762008-02-20 06:48:22 +0000488}
489
490/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
491SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
492 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
493 return getUnknown(ConstantExpr::getNot(VC->getValue()));
494
Nick Lewycky178f20a2008-02-20 06:58:55 +0000495 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(V->getType()));
Nick Lewycky3e630762008-02-20 06:48:22 +0000496 return getMinusSCEV(AllOnes, V);
Chris Lattner53e677a2004-04-02 20:23:17 +0000497}
498
499/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
500///
Dan Gohman246b2562007-10-22 18:31:58 +0000501SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
502 const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000503 // X - Y --> X + -Y
Dan Gohman246b2562007-10-22 18:31:58 +0000504 return getAddExpr(LHS, getNegativeSCEV(RHS));
Chris Lattner53e677a2004-04-02 20:23:17 +0000505}
506
507
Eli Friedmanb42a6262008-08-04 23:49:06 +0000508/// BinomialCoefficient - Compute BC(It, K). The result has width W.
509// Assume, K > 0.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000510static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedmanb42a6262008-08-04 23:49:06 +0000511 ScalarEvolution &SE,
512 const IntegerType* ResultTy) {
513 // Handle the simplest case efficiently.
514 if (K == 1)
515 return SE.getTruncateOrZeroExtend(It, ResultTy);
516
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000517 // We are using the following formula for BC(It, K):
518 //
519 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
520 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000521 // Suppose, W is the bitwidth of the return value. We must be prepared for
522 // overflow. Hence, we must assure that the result of our computation is
523 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
524 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000525 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000526 // However, this code doesn't use exactly that formula; the formula it uses
527 // is something like the following, where T is the number of factors of 2 in
528 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
529 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000530 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000531 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000532 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000533 // This formula is trivially equivalent to the previous formula. However,
534 // this formula can be implemented much more efficiently. The trick is that
535 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
536 // arithmetic. To do exact division in modular arithmetic, all we have
537 // to do is multiply by the inverse. Therefore, this step can be done at
538 // width W.
539 //
540 // The next issue is how to safely do the division by 2^T. The way this
541 // is done is by doing the multiplication step at a width of at least W + T
542 // bits. This way, the bottom W+T bits of the product are accurate. Then,
543 // when we perform the division by 2^T (which is equivalent to a right shift
544 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
545 // truncated out after the division by 2^T.
546 //
547 // In comparison to just directly using the first formula, this technique
548 // is much more efficient; using the first formula requires W * K bits,
549 // but this formula less than W + K bits. Also, the first formula requires
550 // a division step, whereas this formula only requires multiplies and shifts.
551 //
552 // It doesn't matter whether the subtraction step is done in the calculation
553 // width or the input iteration count's width; if the subtraction overflows,
554 // the result must be zero anyway. We prefer here to do it in the width of
555 // the induction variable because it helps a lot for certain cases; CodeGen
556 // isn't smart enough to ignore the overflow, which leads to much less
557 // efficient code if the width of the subtraction is wider than the native
558 // register width.
559 //
560 // (It's possible to not widen at all by pulling out factors of 2 before
561 // the multiplication; for example, K=2 can be calculated as
562 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
563 // extra arithmetic, so it's not an obvious win, and it gets
564 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000565
Eli Friedmanb42a6262008-08-04 23:49:06 +0000566 // Protection from insane SCEVs; this bound is conservative,
567 // but it probably doesn't matter.
568 if (K > 1000)
569 return new SCEVCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000570
Eli Friedmanb42a6262008-08-04 23:49:06 +0000571 unsigned W = ResultTy->getBitWidth();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000572
Eli Friedmanb42a6262008-08-04 23:49:06 +0000573 // Calculate K! / 2^T and T; we divide out the factors of two before
574 // multiplying for calculating K! / 2^T to avoid overflow.
575 // Other overflow doesn't matter because we only care about the bottom
576 // W bits of the result.
577 APInt OddFactorial(W, 1);
578 unsigned T = 1;
579 for (unsigned i = 3; i <= K; ++i) {
580 APInt Mult(W, i);
581 unsigned TwoFactors = Mult.countTrailingZeros();
582 T += TwoFactors;
583 Mult = Mult.lshr(TwoFactors);
584 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000585 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000586
Eli Friedmanb42a6262008-08-04 23:49:06 +0000587 // We need at least W + T bits for the multiplication step
Nick Lewycky237d8732009-01-25 08:16:27 +0000588 unsigned CalculationBits = W + T;
Eli Friedmanb42a6262008-08-04 23:49:06 +0000589
590 // Calcuate 2^T, at width T+W.
591 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
592
593 // Calculate the multiplicative inverse of K! / 2^T;
594 // this multiplication factor will perform the exact division by
595 // K! / 2^T.
596 APInt Mod = APInt::getSignedMinValue(W+1);
597 APInt MultiplyFactor = OddFactorial.zext(W+1);
598 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
599 MultiplyFactor = MultiplyFactor.trunc(W);
600
601 // Calculate the product, at width T+W
602 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
603 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
604 for (unsigned i = 1; i != K; ++i) {
605 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
606 Dividend = SE.getMulExpr(Dividend,
607 SE.getTruncateOrZeroExtend(S, CalculationTy));
608 }
609
610 // Divide by 2^T
611 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
612
613 // Truncate the result, and divide by K! / 2^T.
614
615 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
616 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000617}
618
Chris Lattner53e677a2004-04-02 20:23:17 +0000619/// evaluateAtIteration - Return the value of this chain of recurrences at
620/// the specified iteration number. We can evaluate this recurrence by
621/// multiplying each element in the chain by the binomial coefficient
622/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
623///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000624/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000625///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000626/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000627///
Dan Gohman246b2562007-10-22 18:31:58 +0000628SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
629 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000630 SCEVHandle Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000631 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000632 // The computation is correct in the face of overflow provided that the
633 // multiplication is performed _after_ the evaluation of the binomial
634 // coefficient.
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000635 SCEVHandle Coeff = BinomialCoefficient(It, i, SE,
636 cast<IntegerType>(getType()));
637 if (isa<SCEVCouldNotCompute>(Coeff))
638 return Coeff;
639
640 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000641 }
642 return Result;
643}
644
Chris Lattner53e677a2004-04-02 20:23:17 +0000645//===----------------------------------------------------------------------===//
646// SCEV Expression folder implementations
647//===----------------------------------------------------------------------===//
648
Dan Gohman246b2562007-10-22 18:31:58 +0000649SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000650 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000651 return getUnknown(
Reid Spencer315d0552006-12-05 22:39:58 +0000652 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000653
654 // If the input value is a chrec scev made out of constants, truncate
655 // all of the constants.
656 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
657 std::vector<SCEVHandle> Operands;
658 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
659 // FIXME: This should allow truncation of other expression types!
660 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman246b2562007-10-22 18:31:58 +0000661 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000662 else
663 break;
664 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman246b2562007-10-22 18:31:58 +0000665 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000666 }
667
Chris Lattnerb3364092006-10-04 21:49:37 +0000668 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000669 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
670 return Result;
671}
672
Dan Gohman246b2562007-10-22 18:31:58 +0000673SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000674 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000675 return getUnknown(
Reid Spencerd977d862006-12-12 23:36:14 +0000676 ConstantExpr::getZExt(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000677
678 // FIXME: If the input value is a chrec scev, and we can prove that the value
679 // did not overflow the old, smaller, value, we can zero extend all of the
680 // operands (often constants). This would allow analysis of something like
681 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
682
Chris Lattnerb3364092006-10-04 21:49:37 +0000683 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000684 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
685 return Result;
686}
687
Dan Gohman246b2562007-10-22 18:31:58 +0000688SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmand19534a2007-06-15 14:38:12 +0000689 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000690 return getUnknown(
Dan Gohmand19534a2007-06-15 14:38:12 +0000691 ConstantExpr::getSExt(SC->getValue(), Ty));
692
693 // FIXME: If the input value is a chrec scev, and we can prove that the value
694 // did not overflow the old, smaller, value, we can sign extend all of the
695 // operands (often constants). This would allow analysis of something like
696 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
697
698 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
699 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
700 return Result;
701}
702
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000703/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
704/// of the input value to the specified type. If the type must be
705/// extended, it is zero extended.
706SCEVHandle ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
707 const Type *Ty) {
708 const Type *SrcTy = V->getType();
709 assert(SrcTy->isInteger() && Ty->isInteger() &&
710 "Cannot truncate or zero extend with non-integer arguments!");
711 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
712 return V; // No conversion
713 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
714 return getTruncateExpr(V, Ty);
715 return getZeroExtendExpr(V, Ty);
716}
717
Chris Lattner53e677a2004-04-02 20:23:17 +0000718// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman246b2562007-10-22 18:31:58 +0000719SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000720 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000721 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000722
723 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000724 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000725
726 // If there are any constants, fold them together.
727 unsigned Idx = 0;
728 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
729 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000730 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000731 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
732 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +0000733 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
734 RHSC->getValue()->getValue());
735 Ops[0] = getConstant(Fold);
736 Ops.erase(Ops.begin()+1); // Erase the folded element
737 if (Ops.size() == 1) return Ops[0];
738 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000739 }
740
741 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +0000742 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000743 Ops.erase(Ops.begin());
744 --Idx;
745 }
746 }
747
Chris Lattner627018b2004-04-07 16:16:11 +0000748 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000749
Chris Lattner53e677a2004-04-02 20:23:17 +0000750 // Okay, check to see if the same value occurs in the operand list twice. If
751 // so, merge them together into an multiply expression. Since we sorted the
752 // list, these values are required to be adjacent.
753 const Type *Ty = Ops[0]->getType();
754 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
755 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
756 // Found a match, merge the two values into a multiply, and add any
757 // remaining values to the result.
Dan Gohman246b2562007-10-22 18:31:58 +0000758 SCEVHandle Two = getIntegerSCEV(2, Ty);
759 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +0000760 if (Ops.size() == 2)
761 return Mul;
762 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
763 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +0000764 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000765 }
766
Dan Gohmanf50cd742007-06-18 19:30:09 +0000767 // Now we know the first non-constant operand. Skip past any cast SCEVs.
768 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
769 ++Idx;
770
771 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +0000772 if (Idx < Ops.size()) {
773 bool DeletedAdd = false;
774 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
775 // If we have an add, expand the add operands onto the end of the operands
776 // list.
777 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
778 Ops.erase(Ops.begin()+Idx);
779 DeletedAdd = true;
780 }
781
782 // If we deleted at least one add, we added operands to the end of the list,
783 // and they are not necessarily sorted. Recurse to resort and resimplify
784 // any operands we just aquired.
785 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +0000786 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000787 }
788
789 // Skip over the add expression until we get to a multiply.
790 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
791 ++Idx;
792
793 // If we are adding something to a multiply expression, make sure the
794 // something is not already an operand of the multiply. If so, merge it into
795 // the multiply.
796 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
797 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
798 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
799 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
800 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000801 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000802 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
803 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
804 if (Mul->getNumOperands() != 2) {
805 // If the multiply has more than two operands, we must get the
806 // Y*Z term.
807 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
808 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000809 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000810 }
Dan Gohman246b2562007-10-22 18:31:58 +0000811 SCEVHandle One = getIntegerSCEV(1, Ty);
812 SCEVHandle AddOne = getAddExpr(InnerMul, One);
813 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000814 if (Ops.size() == 2) return OuterMul;
815 if (AddOp < Idx) {
816 Ops.erase(Ops.begin()+AddOp);
817 Ops.erase(Ops.begin()+Idx-1);
818 } else {
819 Ops.erase(Ops.begin()+Idx);
820 Ops.erase(Ops.begin()+AddOp-1);
821 }
822 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000823 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000824 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000825
Chris Lattner53e677a2004-04-02 20:23:17 +0000826 // Check this multiply against other multiplies being added together.
827 for (unsigned OtherMulIdx = Idx+1;
828 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
829 ++OtherMulIdx) {
830 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
831 // If MulOp occurs in OtherMul, we can fold the two multiplies
832 // together.
833 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
834 OMulOp != e; ++OMulOp)
835 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
836 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
837 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
838 if (Mul->getNumOperands() != 2) {
839 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
840 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000841 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000842 }
843 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
844 if (OtherMul->getNumOperands() != 2) {
845 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
846 OtherMul->op_end());
847 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000848 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000849 }
Dan Gohman246b2562007-10-22 18:31:58 +0000850 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
851 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +0000852 if (Ops.size() == 2) return OuterMul;
853 Ops.erase(Ops.begin()+Idx);
854 Ops.erase(Ops.begin()+OtherMulIdx-1);
855 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000856 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000857 }
858 }
859 }
860 }
861
862 // If there are any add recurrences in the operands list, see if any other
863 // added values are loop invariant. If so, we can fold them into the
864 // recurrence.
865 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
866 ++Idx;
867
868 // Scan over all recurrences, trying to fold loop invariants into them.
869 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
870 // Scan all of the other operands to this add and add them to the vector if
871 // they are loop invariant w.r.t. the recurrence.
872 std::vector<SCEVHandle> LIOps;
873 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
874 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
875 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
876 LIOps.push_back(Ops[i]);
877 Ops.erase(Ops.begin()+i);
878 --i; --e;
879 }
880
881 // If we found some loop invariants, fold them into the recurrence.
882 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +0000883 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +0000884 LIOps.push_back(AddRec->getStart());
885
886 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +0000887 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000888
Dan Gohman246b2562007-10-22 18:31:58 +0000889 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000890 // If all of the other operands were loop invariant, we are done.
891 if (Ops.size() == 1) return NewRec;
892
893 // Otherwise, add the folded AddRec by the non-liv parts.
894 for (unsigned i = 0;; ++i)
895 if (Ops[i] == AddRec) {
896 Ops[i] = NewRec;
897 break;
898 }
Dan Gohman246b2562007-10-22 18:31:58 +0000899 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000900 }
901
902 // Okay, if there weren't any loop invariants to be folded, check to see if
903 // there are multiple AddRec's with the same loop induction variable being
904 // added together. If so, we can fold them.
905 for (unsigned OtherIdx = Idx+1;
906 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
907 if (OtherIdx != Idx) {
908 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
909 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
910 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
911 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
912 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
913 if (i >= NewOps.size()) {
914 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
915 OtherAddRec->op_end());
916 break;
917 }
Dan Gohman246b2562007-10-22 18:31:58 +0000918 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +0000919 }
Dan Gohman246b2562007-10-22 18:31:58 +0000920 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000921
922 if (Ops.size() == 2) return NewAddRec;
923
924 Ops.erase(Ops.begin()+Idx);
925 Ops.erase(Ops.begin()+OtherIdx-1);
926 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +0000927 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000928 }
929 }
930
931 // Otherwise couldn't fold anything into this recurrence. Move onto the
932 // next one.
933 }
934
935 // Okay, it looks like we really DO need an add expr. Check to see if we
936 // already have one, otherwise create a new one.
937 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000938 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
939 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000940 if (Result == 0) Result = new SCEVAddExpr(Ops);
941 return Result;
942}
943
944
Dan Gohman246b2562007-10-22 18:31:58 +0000945SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000946 assert(!Ops.empty() && "Cannot get empty mul!");
947
948 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000949 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000950
951 // If there are any constants, fold them together.
952 unsigned Idx = 0;
953 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
954
955 // C1*(C2+V) -> C1*C2 + C1*V
956 if (Ops.size() == 2)
957 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
958 if (Add->getNumOperands() == 2 &&
959 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +0000960 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
961 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000962
963
964 ++Idx;
965 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
966 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +0000967 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
968 RHSC->getValue()->getValue());
969 Ops[0] = getConstant(Fold);
970 Ops.erase(Ops.begin()+1); // Erase the folded element
971 if (Ops.size() == 1) return Ops[0];
972 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000973 }
974
975 // If we are left with a constant one being multiplied, strip it off.
976 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
977 Ops.erase(Ops.begin());
978 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +0000979 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000980 // If we have a multiply of zero, it will always be zero.
981 return Ops[0];
982 }
983 }
984
985 // Skip over the add expression until we get to a multiply.
986 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
987 ++Idx;
988
989 if (Ops.size() == 1)
990 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000991
Chris Lattner53e677a2004-04-02 20:23:17 +0000992 // If there are mul operands inline them all into this expression.
993 if (Idx < Ops.size()) {
994 bool DeletedMul = false;
995 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
996 // If we have an mul, expand the mul operands onto the end of the operands
997 // list.
998 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
999 Ops.erase(Ops.begin()+Idx);
1000 DeletedMul = true;
1001 }
1002
1003 // If we deleted at least one mul, we added operands to the end of the list,
1004 // and they are not necessarily sorted. Recurse to resort and resimplify
1005 // any operands we just aquired.
1006 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001007 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001008 }
1009
1010 // If there are any add recurrences in the operands list, see if any other
1011 // added values are loop invariant. If so, we can fold them into the
1012 // recurrence.
1013 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1014 ++Idx;
1015
1016 // Scan over all recurrences, trying to fold loop invariants into them.
1017 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1018 // Scan all of the other operands to this mul and add them to the vector if
1019 // they are loop invariant w.r.t. the recurrence.
1020 std::vector<SCEVHandle> LIOps;
1021 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1022 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1023 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1024 LIOps.push_back(Ops[i]);
1025 Ops.erase(Ops.begin()+i);
1026 --i; --e;
1027 }
1028
1029 // If we found some loop invariants, fold them into the recurrence.
1030 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001031 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001032 std::vector<SCEVHandle> NewOps;
1033 NewOps.reserve(AddRec->getNumOperands());
1034 if (LIOps.size() == 1) {
1035 SCEV *Scale = LIOps[0];
1036 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001037 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001038 } else {
1039 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1040 std::vector<SCEVHandle> MulOps(LIOps);
1041 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001042 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001043 }
1044 }
1045
Dan Gohman246b2562007-10-22 18:31:58 +00001046 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001047
1048 // If all of the other operands were loop invariant, we are done.
1049 if (Ops.size() == 1) return NewRec;
1050
1051 // Otherwise, multiply the folded AddRec by the non-liv parts.
1052 for (unsigned i = 0;; ++i)
1053 if (Ops[i] == AddRec) {
1054 Ops[i] = NewRec;
1055 break;
1056 }
Dan Gohman246b2562007-10-22 18:31:58 +00001057 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001058 }
1059
1060 // Okay, if there weren't any loop invariants to be folded, check to see if
1061 // there are multiple AddRec's with the same loop induction variable being
1062 // multiplied together. If so, we can fold them.
1063 for (unsigned OtherIdx = Idx+1;
1064 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1065 if (OtherIdx != Idx) {
1066 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1067 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1068 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1069 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman246b2562007-10-22 18:31:58 +00001070 SCEVHandle NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001071 G->getStart());
Dan Gohman246b2562007-10-22 18:31:58 +00001072 SCEVHandle B = F->getStepRecurrence(*this);
1073 SCEVHandle D = G->getStepRecurrence(*this);
1074 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1075 getMulExpr(G, B),
1076 getMulExpr(B, D));
1077 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1078 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001079 if (Ops.size() == 2) return NewAddRec;
1080
1081 Ops.erase(Ops.begin()+Idx);
1082 Ops.erase(Ops.begin()+OtherIdx-1);
1083 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001084 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001085 }
1086 }
1087
1088 // Otherwise couldn't fold anything into this recurrence. Move onto the
1089 // next one.
1090 }
1091
1092 // Okay, it looks like we really DO need an mul expr. Check to see if we
1093 // already have one, otherwise create a new one.
1094 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +00001095 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1096 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +00001097 if (Result == 0)
1098 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001099 return Result;
1100}
1101
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001102SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001103 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1104 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky789558d2009-01-13 09:18:58 +00001105 return LHS; // X udiv 1 --> x
Chris Lattner53e677a2004-04-02 20:23:17 +00001106
1107 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1108 Constant *LHSCV = LHSC->getValue();
1109 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001110 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001111 }
1112 }
1113
Nick Lewycky789558d2009-01-13 09:18:58 +00001114 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1115
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001116 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1117 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001118 return Result;
1119}
1120
1121
1122/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1123/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001124SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Chris Lattner53e677a2004-04-02 20:23:17 +00001125 const SCEVHandle &Step, const Loop *L) {
1126 std::vector<SCEVHandle> Operands;
1127 Operands.push_back(Start);
1128 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1129 if (StepChrec->getLoop() == L) {
1130 Operands.insert(Operands.end(), StepChrec->op_begin(),
1131 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001132 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001133 }
1134
1135 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001136 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001137}
1138
1139/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1140/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001141SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Chris Lattner53e677a2004-04-02 20:23:17 +00001142 const Loop *L) {
1143 if (Operands.size() == 1) return Operands[0];
1144
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001145 if (Operands.back()->isZero()) {
1146 Operands.pop_back();
Dan Gohman8dae1382008-09-14 17:21:12 +00001147 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001148 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001149
Dan Gohmand9cc7492008-08-08 18:33:12 +00001150 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1151 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1152 const Loop* NestedLoop = NestedAR->getLoop();
1153 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1154 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1155 NestedAR->op_end());
1156 SCEVHandle NestedARHandle(NestedAR);
1157 Operands[0] = NestedAR->getStart();
1158 NestedOperands[0] = getAddRecExpr(Operands, L);
1159 return getAddRecExpr(NestedOperands, NestedLoop);
1160 }
1161 }
1162
Chris Lattner53e677a2004-04-02 20:23:17 +00001163 SCEVAddRecExpr *&Result =
Chris Lattnerb3364092006-10-04 21:49:37 +00001164 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1165 Operands.end()))];
Chris Lattner53e677a2004-04-02 20:23:17 +00001166 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1167 return Result;
1168}
1169
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001170SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1171 const SCEVHandle &RHS) {
1172 std::vector<SCEVHandle> Ops;
1173 Ops.push_back(LHS);
1174 Ops.push_back(RHS);
1175 return getSMaxExpr(Ops);
1176}
1177
1178SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1179 assert(!Ops.empty() && "Cannot get empty smax!");
1180 if (Ops.size() == 1) return Ops[0];
1181
1182 // Sort by complexity, this groups all similar expression types together.
1183 GroupByComplexity(Ops);
1184
1185 // If there are any constants, fold them together.
1186 unsigned Idx = 0;
1187 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1188 ++Idx;
1189 assert(Idx < Ops.size());
1190 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1191 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001192 ConstantInt *Fold = ConstantInt::get(
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001193 APIntOps::smax(LHSC->getValue()->getValue(),
1194 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001195 Ops[0] = getConstant(Fold);
1196 Ops.erase(Ops.begin()+1); // Erase the folded element
1197 if (Ops.size() == 1) return Ops[0];
1198 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001199 }
1200
1201 // If we are left with a constant -inf, strip it off.
1202 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1203 Ops.erase(Ops.begin());
1204 --Idx;
1205 }
1206 }
1207
1208 if (Ops.size() == 1) return Ops[0];
1209
1210 // Find the first SMax
1211 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1212 ++Idx;
1213
1214 // Check to see if one of the operands is an SMax. If so, expand its operands
1215 // onto our operand list, and recurse to simplify.
1216 if (Idx < Ops.size()) {
1217 bool DeletedSMax = false;
1218 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1219 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1220 Ops.erase(Ops.begin()+Idx);
1221 DeletedSMax = true;
1222 }
1223
1224 if (DeletedSMax)
1225 return getSMaxExpr(Ops);
1226 }
1227
1228 // Okay, check to see if the same value occurs in the operand list twice. If
1229 // so, delete one. Since we sorted the list, these values are required to
1230 // be adjacent.
1231 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1232 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1233 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1234 --i; --e;
1235 }
1236
1237 if (Ops.size() == 1) return Ops[0];
1238
1239 assert(!Ops.empty() && "Reduced smax down to nothing!");
1240
Nick Lewycky3e630762008-02-20 06:48:22 +00001241 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001242 // already have one, otherwise create a new one.
1243 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1244 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1245 SCEVOps)];
1246 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1247 return Result;
1248}
1249
Nick Lewycky3e630762008-02-20 06:48:22 +00001250SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1251 const SCEVHandle &RHS) {
1252 std::vector<SCEVHandle> Ops;
1253 Ops.push_back(LHS);
1254 Ops.push_back(RHS);
1255 return getUMaxExpr(Ops);
1256}
1257
1258SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1259 assert(!Ops.empty() && "Cannot get empty umax!");
1260 if (Ops.size() == 1) return Ops[0];
1261
1262 // Sort by complexity, this groups all similar expression types together.
1263 GroupByComplexity(Ops);
1264
1265 // If there are any constants, fold them together.
1266 unsigned Idx = 0;
1267 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1268 ++Idx;
1269 assert(Idx < Ops.size());
1270 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1271 // We found two constants, fold them together!
1272 ConstantInt *Fold = ConstantInt::get(
1273 APIntOps::umax(LHSC->getValue()->getValue(),
1274 RHSC->getValue()->getValue()));
1275 Ops[0] = getConstant(Fold);
1276 Ops.erase(Ops.begin()+1); // Erase the folded element
1277 if (Ops.size() == 1) return Ops[0];
1278 LHSC = cast<SCEVConstant>(Ops[0]);
1279 }
1280
1281 // If we are left with a constant zero, strip it off.
1282 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1283 Ops.erase(Ops.begin());
1284 --Idx;
1285 }
1286 }
1287
1288 if (Ops.size() == 1) return Ops[0];
1289
1290 // Find the first UMax
1291 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1292 ++Idx;
1293
1294 // Check to see if one of the operands is a UMax. If so, expand its operands
1295 // onto our operand list, and recurse to simplify.
1296 if (Idx < Ops.size()) {
1297 bool DeletedUMax = false;
1298 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1299 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1300 Ops.erase(Ops.begin()+Idx);
1301 DeletedUMax = true;
1302 }
1303
1304 if (DeletedUMax)
1305 return getUMaxExpr(Ops);
1306 }
1307
1308 // Okay, check to see if the same value occurs in the operand list twice. If
1309 // so, delete one. Since we sorted the list, these values are required to
1310 // be adjacent.
1311 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1312 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1313 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1314 --i; --e;
1315 }
1316
1317 if (Ops.size() == 1) return Ops[0];
1318
1319 assert(!Ops.empty() && "Reduced umax down to nothing!");
1320
1321 // Okay, it looks like we really DO need a umax expr. Check to see if we
1322 // already have one, otherwise create a new one.
1323 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1324 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1325 SCEVOps)];
1326 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1327 return Result;
1328}
1329
Dan Gohman246b2562007-10-22 18:31:58 +00001330SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001331 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman246b2562007-10-22 18:31:58 +00001332 return getConstant(CI);
Chris Lattnerb3364092006-10-04 21:49:37 +00001333 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001334 if (Result == 0) Result = new SCEVUnknown(V);
1335 return Result;
1336}
1337
Chris Lattner53e677a2004-04-02 20:23:17 +00001338
1339//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001340// ScalarEvolutionsImpl Definition and Implementation
1341//===----------------------------------------------------------------------===//
1342//
1343/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1344/// evolution code.
1345///
1346namespace {
Chris Lattner95255282006-06-28 23:17:24 +00001347 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Dan Gohman246b2562007-10-22 18:31:58 +00001348 /// SE - A reference to the public ScalarEvolution object.
1349 ScalarEvolution &SE;
1350
Chris Lattner53e677a2004-04-02 20:23:17 +00001351 /// F - The function we are analyzing.
1352 ///
1353 Function &F;
1354
1355 /// LI - The loop information for the function we are currently analyzing.
1356 ///
1357 LoopInfo &LI;
1358
1359 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1360 /// things.
1361 SCEVHandle UnknownValue;
1362
1363 /// Scalars - This is a cache of the scalars we have analyzed so far.
1364 ///
1365 std::map<Value*, SCEVHandle> Scalars;
1366
1367 /// IterationCounts - Cache the iteration count of the loops for this
1368 /// function as they are computed.
1369 std::map<const Loop*, SCEVHandle> IterationCounts;
1370
Chris Lattner3221ad02004-04-17 22:58:41 +00001371 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1372 /// the PHI instructions that we attempt to compute constant evolutions for.
1373 /// This allows us to avoid potentially expensive recomputation of these
1374 /// properties. An instruction maps to null if we are unable to compute its
1375 /// exit value.
1376 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001377
Chris Lattner53e677a2004-04-02 20:23:17 +00001378 public:
Dan Gohman246b2562007-10-22 18:31:58 +00001379 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li)
1380 : SE(se), F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
Chris Lattner53e677a2004-04-02 20:23:17 +00001381
1382 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1383 /// expression and create a new one.
1384 SCEVHandle getSCEV(Value *V);
1385
Chris Lattnera0740fb2005-08-09 23:36:33 +00001386 /// hasSCEV - Return true if the SCEV for this value has already been
1387 /// computed.
1388 bool hasSCEV(Value *V) const {
1389 return Scalars.count(V);
1390 }
1391
1392 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1393 /// the specified value.
1394 void setSCEV(Value *V, const SCEVHandle &H) {
1395 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1396 assert(isNew && "This entry already existed!");
Devang Patel89d0a4d2008-11-11 19:17:41 +00001397 isNew = false;
Chris Lattnera0740fb2005-08-09 23:36:33 +00001398 }
1399
1400
Chris Lattner53e677a2004-04-02 20:23:17 +00001401 /// getSCEVAtScope - Compute the value of the specified expression within
1402 /// the indicated loop (which may be null to indicate in no loop). If the
1403 /// expression cannot be evaluated, return UnknownValue itself.
1404 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1405
1406
Dan Gohmanc2390b12009-02-12 22:19:27 +00001407 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
1408 /// a conditional between LHS and RHS.
1409 bool isLoopGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
1410 SCEV *LHS, SCEV *RHS);
1411
Chris Lattner53e677a2004-04-02 20:23:17 +00001412 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1413 /// an analyzable loop-invariant iteration count.
1414 bool hasLoopInvariantIterationCount(const Loop *L);
1415
1416 /// getIterationCount - If the specified loop has a predictable iteration
1417 /// count, return it. Note that it is not valid to call this method on a
1418 /// loop without a loop-invariant iteration count.
1419 SCEVHandle getIterationCount(const Loop *L);
1420
Dan Gohman5cec4db2007-06-19 14:28:31 +00001421 /// deleteValueFromRecords - This method should be called by the
1422 /// client before it removes a value from the program, to make sure
Chris Lattner53e677a2004-04-02 20:23:17 +00001423 /// that no dangling references are left around.
Dan Gohman5cec4db2007-06-19 14:28:31 +00001424 void deleteValueFromRecords(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001425
1426 private:
1427 /// createSCEV - We know that there is no SCEV for the specified value.
1428 /// Analyze the expression.
1429 SCEVHandle createSCEV(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001430
1431 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1432 /// SCEVs.
1433 SCEVHandle createNodeForPHI(PHINode *PN);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001434
1435 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1436 /// for the specified instruction and replaces any references to the
1437 /// symbolic value SymName with the specified value. This is used during
1438 /// PHI resolution.
1439 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1440 const SCEVHandle &SymName,
1441 const SCEVHandle &NewVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00001442
1443 /// ComputeIterationCount - Compute the number of times the specified loop
1444 /// will iterate.
1445 SCEVHandle ComputeIterationCount(const Loop *L);
1446
Chris Lattner673e02b2004-10-12 01:49:27 +00001447 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky6e801dc2007-11-20 08:44:50 +00001448 /// 'icmp op load X, cst', try to see if we can compute the trip count.
Chris Lattner673e02b2004-10-12 01:49:27 +00001449 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1450 Constant *RHS,
1451 const Loop *L,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001452 ICmpInst::Predicate p);
Chris Lattner673e02b2004-10-12 01:49:27 +00001453
Chris Lattner7980fb92004-04-17 18:36:24 +00001454 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1455 /// constant number of times (the condition evolves only from constants),
1456 /// try to evaluate a few iterations of the loop until we get the exit
1457 /// condition gets a value of ExitWhen (true or false). If we cannot
1458 /// evaluate the trip count of the loop, return UnknownValue.
1459 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1460 bool ExitWhen);
1461
Chris Lattner53e677a2004-04-02 20:23:17 +00001462 /// HowFarToZero - Return the number of times a backedge comparing the
1463 /// specified value to zero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001464 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001465 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1466
1467 /// HowFarToNonZero - Return the number of times a backedge checking the
1468 /// specified value for nonzero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001469 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001470 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattner3221ad02004-04-17 22:58:41 +00001471
Chris Lattnerdb25de42005-08-15 23:33:51 +00001472 /// HowManyLessThans - Return the number of times a backedge containing the
1473 /// specified less-than comparison will execute. If not computable, return
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00001474 /// UnknownValue. isSigned specifies whether the less-than is signed.
1475 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
Nick Lewycky789558d2009-01-13 09:18:58 +00001476 bool isSigned);
Chris Lattnerdb25de42005-08-15 23:33:51 +00001477
Dan Gohmanfd6edef2008-09-15 22:18:04 +00001478 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
1479 /// (which may not be an immediate predecessor) which has exactly one
1480 /// successor from which BB is reachable, or null if no such block is
1481 /// found.
1482 BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
1483
Chris Lattner3221ad02004-04-17 22:58:41 +00001484 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1485 /// in the header of its containing loop, we know the loop executes a
1486 /// constant number of times, and the PHI node is just a recurrence
1487 /// involving constants, fold it.
Reid Spencere8019bb2007-03-01 07:25:48 +00001488 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
Chris Lattner3221ad02004-04-17 22:58:41 +00001489 const Loop *L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001490 };
1491}
1492
1493//===----------------------------------------------------------------------===//
1494// Basic SCEV Analysis and PHI Idiom Recognition Code
1495//
1496
Dan Gohman5cec4db2007-06-19 14:28:31 +00001497/// deleteValueFromRecords - This method should be called by the
Chris Lattner53e677a2004-04-02 20:23:17 +00001498/// client before it removes an instruction from the program, to make sure
1499/// that no dangling references are left around.
Dan Gohman5cec4db2007-06-19 14:28:31 +00001500void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1501 SmallVector<Value *, 16> Worklist;
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001502
Dan Gohman5cec4db2007-06-19 14:28:31 +00001503 if (Scalars.erase(V)) {
1504 if (PHINode *PN = dyn_cast<PHINode>(V))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001505 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman5cec4db2007-06-19 14:28:31 +00001506 Worklist.push_back(V);
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001507 }
1508
1509 while (!Worklist.empty()) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001510 Value *VV = Worklist.back();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001511 Worklist.pop_back();
1512
Dan Gohman5cec4db2007-06-19 14:28:31 +00001513 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001514 UI != UE; ++UI) {
Nick Lewycky51e844b2007-06-06 11:26:20 +00001515 Instruction *Inst = cast<Instruction>(*UI);
1516 if (Scalars.erase(Inst)) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001517 if (PHINode *PN = dyn_cast<PHINode>(VV))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001518 ConstantEvolutionLoopExitValue.erase(PN);
1519 Worklist.push_back(Inst);
1520 }
1521 }
1522 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001523}
1524
1525
1526/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1527/// expression and create a new one.
1528SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1529 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1530
1531 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1532 if (I != Scalars.end()) return I->second;
1533 SCEVHandle S = createSCEV(V);
1534 Scalars.insert(std::make_pair(V, S));
1535 return S;
1536}
1537
Chris Lattner4dc534c2005-02-13 04:37:18 +00001538/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1539/// the specified instruction and replaces any references to the symbolic value
1540/// SymName with the specified value. This is used during PHI resolution.
1541void ScalarEvolutionsImpl::
1542ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1543 const SCEVHandle &NewVal) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001544 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001545 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001546
Chris Lattner4dc534c2005-02-13 04:37:18 +00001547 SCEVHandle NV =
Dan Gohman246b2562007-10-22 18:31:58 +00001548 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001549 if (NV == SI->second) return; // No change.
1550
1551 SI->second = NV; // Update the scalars map!
1552
1553 // Any instruction values that use this instruction might also need to be
1554 // updated!
1555 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1556 UI != E; ++UI)
1557 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1558}
Chris Lattner53e677a2004-04-02 20:23:17 +00001559
1560/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1561/// a loop header, making it a potential recurrence, or it doesn't.
1562///
1563SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1564 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1565 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1566 if (L->getHeader() == PN->getParent()) {
1567 // If it lives in the loop header, it has two incoming values, one
1568 // from outside the loop, and one from inside.
1569 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1570 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001571
Chris Lattner53e677a2004-04-02 20:23:17 +00001572 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman246b2562007-10-22 18:31:58 +00001573 SCEVHandle SymbolicName = SE.getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001574 assert(Scalars.find(PN) == Scalars.end() &&
1575 "PHI node already processed?");
1576 Scalars.insert(std::make_pair(PN, SymbolicName));
1577
1578 // Using this symbolic name for the PHI, analyze the value coming around
1579 // the back-edge.
1580 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1581
1582 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1583 // has a special value for the first iteration of the loop.
1584
1585 // If the value coming around the backedge is an add with the symbolic
1586 // value we just inserted, then we found a simple induction variable!
1587 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1588 // If there is a single occurrence of the symbolic value, replace it
1589 // with a recurrence.
1590 unsigned FoundIndex = Add->getNumOperands();
1591 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1592 if (Add->getOperand(i) == SymbolicName)
1593 if (FoundIndex == e) {
1594 FoundIndex = i;
1595 break;
1596 }
1597
1598 if (FoundIndex != Add->getNumOperands()) {
1599 // Create an add with everything but the specified operand.
1600 std::vector<SCEVHandle> Ops;
1601 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1602 if (i != FoundIndex)
1603 Ops.push_back(Add->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001604 SCEVHandle Accum = SE.getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001605
1606 // This is not a valid addrec if the step amount is varying each
1607 // loop iteration, but is not itself an addrec in this loop.
1608 if (Accum->isLoopInvariant(L) ||
1609 (isa<SCEVAddRecExpr>(Accum) &&
1610 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1611 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohman246b2562007-10-22 18:31:58 +00001612 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001613
1614 // Okay, for the entire analysis of this edge we assumed the PHI
1615 // to be symbolic. We now need to go back and update all of the
1616 // entries for the scalars that use the PHI (except for the PHI
1617 // itself) to use the new analyzed value instead of the "symbolic"
1618 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001619 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001620 return PHISCEV;
1621 }
1622 }
Chris Lattner97156e72006-04-26 18:34:07 +00001623 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1624 // Otherwise, this could be a loop like this:
1625 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1626 // In this case, j = {1,+,1} and BEValue is j.
1627 // Because the other in-value of i (0) fits the evolution of BEValue
1628 // i really is an addrec evolution.
1629 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1630 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1631
1632 // If StartVal = j.start - j.stride, we can use StartVal as the
1633 // initial step of the addrec evolution.
Dan Gohman246b2562007-10-22 18:31:58 +00001634 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1635 AddRec->getOperand(1))) {
Chris Lattner97156e72006-04-26 18:34:07 +00001636 SCEVHandle PHISCEV =
Dan Gohman246b2562007-10-22 18:31:58 +00001637 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00001638
1639 // Okay, for the entire analysis of this edge we assumed the PHI
1640 // to be symbolic. We now need to go back and update all of the
1641 // entries for the scalars that use the PHI (except for the PHI
1642 // itself) to use the new analyzed value instead of the "symbolic"
1643 // value.
1644 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1645 return PHISCEV;
1646 }
1647 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001648 }
1649
1650 return SymbolicName;
1651 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001652
Chris Lattner53e677a2004-04-02 20:23:17 +00001653 // If it's not a loop phi, we can't handle it yet.
Dan Gohman246b2562007-10-22 18:31:58 +00001654 return SE.getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001655}
1656
Nick Lewycky83bb0052007-11-22 07:59:40 +00001657/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1658/// guaranteed to end in (at every loop iteration). It is, at the same time,
1659/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1660/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1661static uint32_t GetMinTrailingZeros(SCEVHandle S) {
1662 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00001663 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00001664
Nick Lewycky6e801dc2007-11-20 08:44:50 +00001665 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Nick Lewycky83bb0052007-11-22 07:59:40 +00001666 return std::min(GetMinTrailingZeros(T->getOperand()), T->getBitWidth());
1667
1668 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1669 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1670 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1671 }
1672
1673 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1674 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1675 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1676 }
1677
Chris Lattnera17f0392006-12-12 02:26:09 +00001678 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001679 // The result is the min of all operands results.
1680 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1681 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1682 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1683 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001684 }
1685
1686 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001687 // The result is the sum of all operands results.
1688 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
1689 uint32_t BitWidth = M->getBitWidth();
1690 for (unsigned i = 1, e = M->getNumOperands();
1691 SumOpRes != BitWidth && i != e; ++i)
1692 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
1693 BitWidth);
1694 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001695 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001696
Chris Lattnera17f0392006-12-12 02:26:09 +00001697 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001698 // The result is the min of all operands results.
1699 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1700 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1701 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1702 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001703 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001704
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001705 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1706 // The result is the min of all operands results.
1707 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1708 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1709 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1710 return MinOpRes;
1711 }
1712
Nick Lewycky3e630762008-02-20 06:48:22 +00001713 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1714 // The result is the min of all operands results.
1715 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1716 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1717 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1718 return MinOpRes;
1719 }
1720
Nick Lewycky789558d2009-01-13 09:18:58 +00001721 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky83bb0052007-11-22 07:59:40 +00001722 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00001723}
Chris Lattner53e677a2004-04-02 20:23:17 +00001724
1725/// createSCEV - We know that there is no SCEV for the specified value.
1726/// Analyze the expression.
1727///
1728SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
Chris Lattner42b5e082007-11-23 08:46:22 +00001729 if (!isa<IntegerType>(V->getType()))
1730 return SE.getUnknown(V);
1731
Dan Gohman6c459a22008-06-22 19:56:46 +00001732 unsigned Opcode = Instruction::UserOp1;
1733 if (Instruction *I = dyn_cast<Instruction>(V))
1734 Opcode = I->getOpcode();
1735 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1736 Opcode = CE->getOpcode();
1737 else
1738 return SE.getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00001739
Dan Gohman6c459a22008-06-22 19:56:46 +00001740 User *U = cast<User>(V);
1741 switch (Opcode) {
1742 case Instruction::Add:
1743 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1744 getSCEV(U->getOperand(1)));
1745 case Instruction::Mul:
1746 return SE.getMulExpr(getSCEV(U->getOperand(0)),
1747 getSCEV(U->getOperand(1)));
1748 case Instruction::UDiv:
1749 return SE.getUDivExpr(getSCEV(U->getOperand(0)),
1750 getSCEV(U->getOperand(1)));
1751 case Instruction::Sub:
1752 return SE.getMinusSCEV(getSCEV(U->getOperand(0)),
1753 getSCEV(U->getOperand(1)));
1754 case Instruction::Or:
1755 // If the RHS of the Or is a constant, we may have something like:
1756 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1757 // optimizations will transparently handle this case.
1758 //
1759 // In order for this transformation to be safe, the LHS must be of the
1760 // form X*(2^n) and the Or constant must be less than 2^n.
1761 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1762 SCEVHandle LHS = getSCEV(U->getOperand(0));
1763 const APInt &CIVal = CI->getValue();
1764 if (GetMinTrailingZeros(LHS) >=
1765 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1766 return SE.getAddExpr(LHS, getSCEV(U->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001767 }
Dan Gohman6c459a22008-06-22 19:56:46 +00001768 break;
1769 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00001770 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00001771 // If the RHS of the xor is a signbit, then this is just an add.
1772 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00001773 if (CI->getValue().isSignBit())
1774 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1775 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00001776
1777 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman6c459a22008-06-22 19:56:46 +00001778 else if (CI->isAllOnesValue())
1779 return SE.getNotSCEV(getSCEV(U->getOperand(0)));
1780 }
1781 break;
1782
1783 case Instruction::Shl:
1784 // Turn shift left of a constant amount into a multiply.
1785 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1786 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1787 Constant *X = ConstantInt::get(
1788 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1789 return SE.getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1790 }
1791 break;
1792
Nick Lewycky01eaf802008-07-07 06:15:49 +00001793 case Instruction::LShr:
Nick Lewycky789558d2009-01-13 09:18:58 +00001794 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00001795 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1796 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1797 Constant *X = ConstantInt::get(
1798 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1799 return SE.getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1800 }
1801 break;
1802
Dan Gohman6c459a22008-06-22 19:56:46 +00001803 case Instruction::Trunc:
1804 return SE.getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
1805
1806 case Instruction::ZExt:
1807 return SE.getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1808
1809 case Instruction::SExt:
1810 return SE.getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1811
1812 case Instruction::BitCast:
1813 // BitCasts are no-op casts so we just eliminate the cast.
1814 if (U->getType()->isInteger() &&
1815 U->getOperand(0)->getType()->isInteger())
1816 return getSCEV(U->getOperand(0));
1817 break;
1818
1819 case Instruction::PHI:
1820 return createNodeForPHI(cast<PHINode>(U));
1821
1822 case Instruction::Select:
1823 // This could be a smax or umax that was lowered earlier.
1824 // Try to recover it.
1825 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
1826 Value *LHS = ICI->getOperand(0);
1827 Value *RHS = ICI->getOperand(1);
1828 switch (ICI->getPredicate()) {
1829 case ICmpInst::ICMP_SLT:
1830 case ICmpInst::ICMP_SLE:
1831 std::swap(LHS, RHS);
1832 // fall through
1833 case ICmpInst::ICMP_SGT:
1834 case ICmpInst::ICMP_SGE:
1835 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1836 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
1837 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman1fbffe02008-07-30 04:36:32 +00001838 // ~smax(~x, ~y) == smin(x, y).
1839 return SE.getNotSCEV(SE.getSMaxExpr(
1840 SE.getNotSCEV(getSCEV(LHS)),
1841 SE.getNotSCEV(getSCEV(RHS))));
Dan Gohman6c459a22008-06-22 19:56:46 +00001842 break;
1843 case ICmpInst::ICMP_ULT:
1844 case ICmpInst::ICMP_ULE:
1845 std::swap(LHS, RHS);
1846 // fall through
1847 case ICmpInst::ICMP_UGT:
1848 case ICmpInst::ICMP_UGE:
1849 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1850 return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
1851 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
1852 // ~umax(~x, ~y) == umin(x, y)
1853 return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)),
1854 SE.getNotSCEV(getSCEV(RHS))));
1855 break;
1856 default:
1857 break;
1858 }
1859 }
1860
1861 default: // We cannot analyze this expression.
1862 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001863 }
1864
Dan Gohman246b2562007-10-22 18:31:58 +00001865 return SE.getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001866}
1867
1868
1869
1870//===----------------------------------------------------------------------===//
1871// Iteration Count Computation Code
1872//
1873
1874/// getIterationCount - If the specified loop has a predictable iteration
1875/// count, return it. Note that it is not valid to call this method on a
1876/// loop without a loop-invariant iteration count.
1877SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1878 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1879 if (I == IterationCounts.end()) {
1880 SCEVHandle ItCount = ComputeIterationCount(L);
1881 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1882 if (ItCount != UnknownValue) {
1883 assert(ItCount->isLoopInvariant(L) &&
1884 "Computed trip count isn't loop invariant for loop!");
1885 ++NumTripCountsComputed;
1886 } else if (isa<PHINode>(L->getHeader()->begin())) {
1887 // Only count loops that have phi nodes as not being computable.
1888 ++NumTripCountsNotComputed;
1889 }
1890 }
1891 return I->second;
1892}
1893
1894/// ComputeIterationCount - Compute the number of times the specified loop
1895/// will iterate.
1896SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1897 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patelb7211a22007-08-21 00:31:24 +00001898 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001899 L->getExitBlocks(ExitBlocks);
1900 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001901
1902 // Okay, there is one exit block. Try to find the condition that causes the
1903 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001904 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001905
1906 BasicBlock *ExitingBlock = 0;
1907 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1908 PI != E; ++PI)
1909 if (L->contains(*PI)) {
1910 if (ExitingBlock == 0)
1911 ExitingBlock = *PI;
1912 else
1913 return UnknownValue; // More than one block exiting!
1914 }
1915 assert(ExitingBlock && "No exits from loop, something is broken!");
1916
1917 // Okay, we've computed the exiting block. See what condition causes us to
1918 // exit.
1919 //
1920 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00001921 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1922 if (ExitBr == 0) return UnknownValue;
1923 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Chris Lattner8b0e3602007-01-07 02:24:26 +00001924
1925 // At this point, we know we have a conditional branch that determines whether
1926 // the loop is exited. However, we don't know if the branch is executed each
1927 // time through the loop. If not, then the execution count of the branch will
1928 // not be equal to the trip count of the loop.
1929 //
1930 // Currently we check for this by checking to see if the Exit branch goes to
1931 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00001932 // times as the loop. We also handle the case where the exit block *is* the
1933 // loop header. This is common for un-rotated loops. More extensive analysis
1934 // could be done to handle more cases here.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001935 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00001936 ExitBr->getSuccessor(1) != L->getHeader() &&
1937 ExitBr->getParent() != L->getHeader())
Chris Lattner8b0e3602007-01-07 02:24:26 +00001938 return UnknownValue;
1939
Reid Spencere4d87aa2006-12-23 06:05:41 +00001940 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
1941
Nick Lewycky3b711652008-02-21 08:34:02 +00001942 // If it's not an integer comparison then compute it the hard way.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001943 // Note that ICmpInst deals with pointer comparisons too so we must check
1944 // the type of the operand.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001945 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Chris Lattner7980fb92004-04-17 18:36:24 +00001946 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1947 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00001948
Reid Spencere4d87aa2006-12-23 06:05:41 +00001949 // If the condition was exit on true, convert the condition to exit on false
1950 ICmpInst::Predicate Cond;
Chris Lattner673e02b2004-10-12 01:49:27 +00001951 if (ExitBr->getSuccessor(1) == ExitBlock)
Reid Spencere4d87aa2006-12-23 06:05:41 +00001952 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00001953 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00001954 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00001955
1956 // Handle common loops like: for (X = "string"; *X; ++X)
1957 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1958 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1959 SCEVHandle ItCnt =
1960 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1961 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1962 }
1963
Chris Lattner53e677a2004-04-02 20:23:17 +00001964 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1965 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1966
1967 // Try to evaluate any dependencies out of the loop.
1968 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1969 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1970 Tmp = getSCEVAtScope(RHS, L);
1971 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1972
Reid Spencere4d87aa2006-12-23 06:05:41 +00001973 // At this point, we would like to compute how many iterations of the
1974 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00001975 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
1976 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00001977 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001978 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00001979 }
1980
1981 // FIXME: think about handling pointer comparisons! i.e.:
1982 // while (P != P+100) ++P;
1983
1984 // If we have a comparison of a chrec against a constant, try to use value
1985 // ranges to answer this query.
1986 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1987 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1988 if (AddRec->getLoop() == L) {
1989 // Form the comparison range using the constant of the correct type so
1990 // that the ConstantRange class knows to do a signed or unsigned
1991 // comparison.
1992 ConstantInt *CompVal = RHSC->getValue();
1993 const Type *RealTy = ExitCond->getOperand(0)->getType();
Reid Spencer4da49122006-12-12 05:05:00 +00001994 CompVal = dyn_cast<ConstantInt>(
Reid Spencerb6ba3e62006-12-12 09:17:50 +00001995 ConstantExpr::getBitCast(CompVal, RealTy));
Chris Lattner53e677a2004-04-02 20:23:17 +00001996 if (CompVal) {
1997 // Form the constant range.
Reid Spencerc6aedf72007-02-28 22:03:51 +00001998 ConstantRange CompRange(
1999 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002000
Dan Gohman246b2562007-10-22 18:31:58 +00002001 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002002 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2003 }
2004 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002005
Chris Lattner53e677a2004-04-02 20:23:17 +00002006 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002007 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00002008 // Convert to: while (X-Y != 0)
Dan Gohman246b2562007-10-22 18:31:58 +00002009 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002010 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002011 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002012 }
2013 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00002014 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman246b2562007-10-22 18:31:58 +00002015 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002016 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002017 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002018 }
2019 case ICmpInst::ICMP_SLT: {
Nick Lewycky789558d2009-01-13 09:18:58 +00002020 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002021 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002022 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002023 }
2024 case ICmpInst::ICMP_SGT: {
Eli Friedman068acc32008-07-30 00:04:08 +00002025 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewycky789558d2009-01-13 09:18:58 +00002026 SE.getNotSCEV(RHS), L, true);
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002027 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2028 break;
2029 }
2030 case ICmpInst::ICMP_ULT: {
Nick Lewycky789558d2009-01-13 09:18:58 +00002031 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002032 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2033 break;
2034 }
2035 case ICmpInst::ICMP_UGT: {
Dale Johannesena0c8fc62008-04-20 16:58:57 +00002036 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewycky789558d2009-01-13 09:18:58 +00002037 SE.getNotSCEV(RHS), L, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002038 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002039 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002040 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002041 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002042#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002043 cerr << "ComputeIterationCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002044 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Bill Wendlinge8156192006-12-07 01:30:32 +00002045 cerr << "[unsigned] ";
2046 cerr << *LHS << " "
Reid Spencere4d87aa2006-12-23 06:05:41 +00002047 << Instruction::getOpcodeName(Instruction::ICmp)
2048 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002049#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00002050 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00002051 }
Chris Lattner7980fb92004-04-17 18:36:24 +00002052 return ComputeIterationCountExhaustively(L, ExitCond,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002053 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner7980fb92004-04-17 18:36:24 +00002054}
2055
Chris Lattner673e02b2004-10-12 01:49:27 +00002056static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00002057EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2058 ScalarEvolution &SE) {
2059 SCEVHandle InVal = SE.getConstant(C);
2060 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00002061 assert(isa<SCEVConstant>(Val) &&
2062 "Evaluation of SCEV at constant didn't fold correctly?");
2063 return cast<SCEVConstant>(Val)->getValue();
2064}
2065
2066/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2067/// and a GEP expression (missing the pointer index) indexing into it, return
2068/// the addressed element of the initializer or null if the index expression is
2069/// invalid.
2070static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002071GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00002072 const std::vector<ConstantInt*> &Indices) {
2073 Constant *Init = GV->getInitializer();
2074 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002075 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00002076 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2077 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2078 Init = cast<Constant>(CS->getOperand(Idx));
2079 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2080 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2081 Init = cast<Constant>(CA->getOperand(Idx));
2082 } else if (isa<ConstantAggregateZero>(Init)) {
2083 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2084 assert(Idx < STy->getNumElements() && "Bad struct index!");
2085 Init = Constant::getNullValue(STy->getElementType(Idx));
2086 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2087 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2088 Init = Constant::getNullValue(ATy->getElementType());
2089 } else {
2090 assert(0 && "Unknown constant aggregate type!");
2091 }
2092 return 0;
2093 } else {
2094 return 0; // Unknown initializer type
2095 }
2096 }
2097 return Init;
2098}
2099
2100/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky08de6132008-05-06 04:03:18 +00002101/// 'icmp op load X, cst', try to see if we can compute the trip count.
Chris Lattner673e02b2004-10-12 01:49:27 +00002102SCEVHandle ScalarEvolutionsImpl::
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002103ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002104 const Loop *L,
2105 ICmpInst::Predicate predicate) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002106 if (LI->isVolatile()) return UnknownValue;
2107
2108 // Check to see if the loaded pointer is a getelementptr of a global.
2109 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2110 if (!GEP) return UnknownValue;
2111
2112 // Make sure that it is really a constant global we are gepping, with an
2113 // initializer, and make sure the first IDX is really 0.
2114 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2115 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2116 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2117 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2118 return UnknownValue;
2119
2120 // Okay, we allow one non-constant index into the GEP instruction.
2121 Value *VarIdx = 0;
2122 std::vector<ConstantInt*> Indexes;
2123 unsigned VarIdxNum = 0;
2124 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2125 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2126 Indexes.push_back(CI);
2127 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2128 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2129 VarIdx = GEP->getOperand(i);
2130 VarIdxNum = i-2;
2131 Indexes.push_back(0);
2132 }
2133
2134 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2135 // Check to see if X is a loop variant variable value now.
2136 SCEVHandle Idx = getSCEV(VarIdx);
2137 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2138 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2139
2140 // We can only recognize very limited forms of loop index expressions, in
2141 // particular, only affine AddRec's like {C1,+,C2}.
2142 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2143 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2144 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2145 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2146 return UnknownValue;
2147
2148 unsigned MaxSteps = MaxBruteForceIterations;
2149 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002150 ConstantInt *ItCst =
Reid Spencerc5b206b2006-12-31 05:48:39 +00002151 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohman246b2562007-10-22 18:31:58 +00002152 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00002153
2154 // Form the GEP offset.
2155 Indexes[VarIdxNum] = Val;
2156
2157 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2158 if (Result == 0) break; // Cannot compute!
2159
2160 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002161 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002162 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00002163 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002164#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002165 cerr << "\n***\n*** Computed loop count " << *ItCst
2166 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2167 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00002168#endif
2169 ++NumArrayLenItCounts;
Dan Gohman246b2562007-10-22 18:31:58 +00002170 return SE.getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00002171 }
2172 }
2173 return UnknownValue;
2174}
2175
2176
Chris Lattner3221ad02004-04-17 22:58:41 +00002177/// CanConstantFold - Return true if we can constant fold an instruction of the
2178/// specified type, assuming that all operands were constants.
2179static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00002180 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00002181 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2182 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002183
Chris Lattner3221ad02004-04-17 22:58:41 +00002184 if (const CallInst *CI = dyn_cast<CallInst>(I))
2185 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00002186 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00002187 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00002188}
2189
Chris Lattner3221ad02004-04-17 22:58:41 +00002190/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2191/// in the loop that V is derived from. We allow arbitrary operations along the
2192/// way, but the operands of an operation must either be constants or a value
2193/// derived from a constant PHI. If this expression does not fit with these
2194/// constraints, return null.
2195static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2196 // If this is not an instruction, or if this is an instruction outside of the
2197 // loop, it can't be derived from a loop PHI.
2198 Instruction *I = dyn_cast<Instruction>(V);
2199 if (I == 0 || !L->contains(I->getParent())) return 0;
2200
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002201 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002202 if (L->getHeader() == I->getParent())
2203 return PN;
2204 else
2205 // We don't currently keep track of the control flow needed to evaluate
2206 // PHIs, so we cannot handle PHIs inside of loops.
2207 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002208 }
Chris Lattner3221ad02004-04-17 22:58:41 +00002209
2210 // If we won't be able to constant fold this expression even if the operands
2211 // are constants, return early.
2212 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002213
Chris Lattner3221ad02004-04-17 22:58:41 +00002214 // Otherwise, we can evaluate this instruction if all of its operands are
2215 // constant or derived from a PHI node themselves.
2216 PHINode *PHI = 0;
2217 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2218 if (!(isa<Constant>(I->getOperand(Op)) ||
2219 isa<GlobalValue>(I->getOperand(Op)))) {
2220 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2221 if (P == 0) return 0; // Not evolving from PHI
2222 if (PHI == 0)
2223 PHI = P;
2224 else if (PHI != P)
2225 return 0; // Evolving from multiple different PHIs.
2226 }
2227
2228 // This is a expression evolving from a constant PHI!
2229 return PHI;
2230}
2231
2232/// EvaluateExpression - Given an expression that passes the
2233/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2234/// in the loop has the value PHIVal. If we can't fold this expression for some
2235/// reason, return null.
2236static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2237 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00002238 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00002239 Instruction *I = cast<Instruction>(V);
2240
2241 std::vector<Constant*> Operands;
2242 Operands.resize(I->getNumOperands());
2243
2244 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2245 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2246 if (Operands[i] == 0) return 0;
2247 }
2248
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002249 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2250 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2251 &Operands[0], Operands.size());
2252 else
2253 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2254 &Operands[0], Operands.size());
Chris Lattner3221ad02004-04-17 22:58:41 +00002255}
2256
2257/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2258/// in the header of its containing loop, we know the loop executes a
2259/// constant number of times, and the PHI node is just a recurrence
2260/// involving constants, fold it.
2261Constant *ScalarEvolutionsImpl::
Reid Spencere8019bb2007-03-01 07:25:48 +00002262getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
Chris Lattner3221ad02004-04-17 22:58:41 +00002263 std::map<PHINode*, Constant*>::iterator I =
2264 ConstantEvolutionLoopExitValue.find(PN);
2265 if (I != ConstantEvolutionLoopExitValue.end())
2266 return I->second;
2267
Reid Spencere8019bb2007-03-01 07:25:48 +00002268 if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00002269 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2270
2271 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2272
2273 // Since the loop is canonicalized, the PHI node must have two entries. One
2274 // entry must be a constant (coming in from outside of the loop), and the
2275 // second must be derived from the same PHI.
2276 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2277 Constant *StartCST =
2278 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2279 if (StartCST == 0)
2280 return RetVal = 0; // Must be a constant.
2281
2282 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2283 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2284 if (PN2 != PN)
2285 return RetVal = 0; // Not derived from same PHI.
2286
2287 // Execute the loop symbolically to determine the exit value.
Reid Spencere8019bb2007-03-01 07:25:48 +00002288 if (Its.getActiveBits() >= 32)
2289 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00002290
Reid Spencere8019bb2007-03-01 07:25:48 +00002291 unsigned NumIterations = Its.getZExtValue(); // must be in range
2292 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00002293 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2294 if (IterationNum == NumIterations)
2295 return RetVal = PHIVal; // Got exit value!
2296
2297 // Compute the value of the PHI node for the next iteration.
2298 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2299 if (NextPHI == PHIVal)
2300 return RetVal = NextPHI; // Stopped evolving!
2301 if (NextPHI == 0)
2302 return 0; // Couldn't evaluate!
2303 PHIVal = NextPHI;
2304 }
2305}
2306
Chris Lattner7980fb92004-04-17 18:36:24 +00002307/// ComputeIterationCountExhaustively - If the trip is known to execute a
2308/// constant number of times (the condition evolves only from constants),
2309/// try to evaluate a few iterations of the loop until we get the exit
2310/// condition gets a value of ExitWhen (true or false). If we cannot
2311/// evaluate the trip count of the loop, return UnknownValue.
2312SCEVHandle ScalarEvolutionsImpl::
2313ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2314 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2315 if (PN == 0) return UnknownValue;
2316
2317 // Since the loop is canonicalized, the PHI node must have two entries. One
2318 // entry must be a constant (coming in from outside of the loop), and the
2319 // second must be derived from the same PHI.
2320 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2321 Constant *StartCST =
2322 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2323 if (StartCST == 0) return UnknownValue; // Must be a constant.
2324
2325 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2326 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2327 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2328
2329 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2330 // the loop symbolically to determine when the condition gets a value of
2331 // "ExitWhen".
2332 unsigned IterationNum = 0;
2333 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2334 for (Constant *PHIVal = StartCST;
2335 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002336 ConstantInt *CondVal =
2337 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00002338
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002339 // Couldn't symbolically evaluate.
Chris Lattneref3baf02007-01-12 18:28:58 +00002340 if (!CondVal) return UnknownValue;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002341
Reid Spencere8019bb2007-03-01 07:25:48 +00002342 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002343 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00002344 ++NumBruteForceTripCountsComputed;
Dan Gohman246b2562007-10-22 18:31:58 +00002345 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00002346 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002347
Chris Lattner3221ad02004-04-17 22:58:41 +00002348 // Compute the value of the PHI node for the next iteration.
2349 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2350 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00002351 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00002352 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00002353 }
2354
2355 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00002356 return UnknownValue;
2357}
2358
2359/// getSCEVAtScope - Compute the value of the specified expression within the
2360/// indicated loop (which may be null to indicate in no loop). If the
2361/// expression cannot be evaluated, return UnknownValue.
2362SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2363 // FIXME: this should be turned into a virtual method on SCEV!
2364
Chris Lattner3221ad02004-04-17 22:58:41 +00002365 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002366
Nick Lewycky3e630762008-02-20 06:48:22 +00002367 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00002368 // exit value from the loop without using SCEVs.
2369 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2370 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2371 const Loop *LI = this->LI[I->getParent()];
2372 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2373 if (PHINode *PN = dyn_cast<PHINode>(I))
2374 if (PN->getParent() == LI->getHeader()) {
2375 // Okay, there is no closed form solution for the PHI node. Check
2376 // to see if the loop that contains it has a known iteration count.
2377 // If so, we may be able to force computation of the exit value.
2378 SCEVHandle IterationCount = getIterationCount(LI);
2379 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2380 // Okay, we know how many times the containing loop executes. If
2381 // this is a constant evolving PHI node, get the final value at
2382 // the specified iteration number.
2383 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Reid Spencere8019bb2007-03-01 07:25:48 +00002384 ICC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00002385 LI);
Dan Gohman246b2562007-10-22 18:31:58 +00002386 if (RV) return SE.getUnknown(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00002387 }
2388 }
2389
Reid Spencer09906f32006-12-04 21:33:23 +00002390 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00002391 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00002392 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00002393 // result. This is particularly useful for computing loop exit values.
2394 if (CanConstantFold(I)) {
2395 std::vector<Constant*> Operands;
2396 Operands.reserve(I->getNumOperands());
2397 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2398 Value *Op = I->getOperand(i);
2399 if (Constant *C = dyn_cast<Constant>(Op)) {
2400 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002401 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00002402 // If any of the operands is non-constant and if they are
2403 // non-integer, don't even try to analyze them with scev techniques.
2404 if (!isa<IntegerType>(Op->getType()))
2405 return V;
2406
Chris Lattner3221ad02004-04-17 22:58:41 +00002407 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2408 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
Reid Spencerd977d862006-12-12 23:36:14 +00002409 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2410 Op->getType(),
2411 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002412 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2413 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
Reid Spencerd977d862006-12-12 23:36:14 +00002414 Operands.push_back(ConstantExpr::getIntegerCast(C,
2415 Op->getType(),
2416 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002417 else
2418 return V;
2419 } else {
2420 return V;
2421 }
2422 }
2423 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002424
2425 Constant *C;
2426 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2427 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2428 &Operands[0], Operands.size());
2429 else
2430 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2431 &Operands[0], Operands.size());
Dan Gohman246b2562007-10-22 18:31:58 +00002432 return SE.getUnknown(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002433 }
2434 }
2435
2436 // This is some other type of SCEVUnknown, just return it.
2437 return V;
2438 }
2439
Chris Lattner53e677a2004-04-02 20:23:17 +00002440 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2441 // Avoid performing the look-up in the common case where the specified
2442 // expression has no loop-variant portions.
2443 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2444 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2445 if (OpAtScope != Comm->getOperand(i)) {
2446 if (OpAtScope == UnknownValue) return UnknownValue;
2447 // Okay, at least one of these operands is loop variant but might be
2448 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00002449 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00002450 NewOps.push_back(OpAtScope);
2451
2452 for (++i; i != e; ++i) {
2453 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2454 if (OpAtScope == UnknownValue) return UnknownValue;
2455 NewOps.push_back(OpAtScope);
2456 }
2457 if (isa<SCEVAddExpr>(Comm))
Dan Gohman246b2562007-10-22 18:31:58 +00002458 return SE.getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002459 if (isa<SCEVMulExpr>(Comm))
2460 return SE.getMulExpr(NewOps);
2461 if (isa<SCEVSMaxExpr>(Comm))
2462 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00002463 if (isa<SCEVUMaxExpr>(Comm))
2464 return SE.getUMaxExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002465 assert(0 && "Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002466 }
2467 }
2468 // If we got here, all operands are loop invariant.
2469 return Comm;
2470 }
2471
Nick Lewycky789558d2009-01-13 09:18:58 +00002472 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
2473 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002474 if (LHS == UnknownValue) return LHS;
Nick Lewycky789558d2009-01-13 09:18:58 +00002475 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002476 if (RHS == UnknownValue) return RHS;
Nick Lewycky789558d2009-01-13 09:18:58 +00002477 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2478 return Div; // must be loop invariant
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00002479 return SE.getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00002480 }
2481
2482 // If this is a loop recurrence for a loop that does not contain L, then we
2483 // are dealing with the final value computed by the loop.
2484 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2485 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2486 // To evaluate this recurrence, we need to know how many times the AddRec
2487 // loop iterates. Compute this now.
2488 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2489 if (IterationCount == UnknownValue) return UnknownValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002490
Eli Friedmanb42a6262008-08-04 23:49:06 +00002491 // Then, evaluate the AddRec.
Dan Gohman246b2562007-10-22 18:31:58 +00002492 return AddRec->evaluateAtIteration(IterationCount, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002493 }
2494 return UnknownValue;
2495 }
2496
2497 //assert(0 && "Unknown SCEV type!");
2498 return UnknownValue;
2499}
2500
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002501/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2502/// following equation:
2503///
2504/// A * X = B (mod N)
2505///
2506/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2507/// A and B isn't important.
2508///
2509/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2510static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2511 ScalarEvolution &SE) {
2512 uint32_t BW = A.getBitWidth();
2513 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2514 assert(A != 0 && "A must be non-zero.");
2515
2516 // 1. D = gcd(A, N)
2517 //
2518 // The gcd of A and N may have only one prime factor: 2. The number of
2519 // trailing zeros in A is its multiplicity
2520 uint32_t Mult2 = A.countTrailingZeros();
2521 // D = 2^Mult2
2522
2523 // 2. Check if B is divisible by D.
2524 //
2525 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2526 // is not less than multiplicity of this prime factor for D.
2527 if (B.countTrailingZeros() < Mult2)
2528 return new SCEVCouldNotCompute();
2529
2530 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2531 // modulo (N / D).
2532 //
2533 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2534 // bit width during computations.
2535 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2536 APInt Mod(BW + 1, 0);
2537 Mod.set(BW - Mult2); // Mod = N / D
2538 APInt I = AD.multiplicativeInverse(Mod);
2539
2540 // 4. Compute the minimum unsigned root of the equation:
2541 // I * (B / D) mod (N / D)
2542 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2543
2544 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2545 // bits.
2546 return SE.getConstant(Result.trunc(BW));
2547}
Chris Lattner53e677a2004-04-02 20:23:17 +00002548
2549/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2550/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2551/// might be the same) or two SCEVCouldNotCompute objects.
2552///
2553static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman246b2562007-10-22 18:31:58 +00002554SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002555 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Reid Spencere8019bb2007-03-01 07:25:48 +00002556 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2557 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2558 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002559
Chris Lattner53e677a2004-04-02 20:23:17 +00002560 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00002561 if (!LC || !MC || !NC) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002562 SCEV *CNC = new SCEVCouldNotCompute();
2563 return std::make_pair(CNC, CNC);
2564 }
2565
Reid Spencere8019bb2007-03-01 07:25:48 +00002566 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00002567 const APInt &L = LC->getValue()->getValue();
2568 const APInt &M = MC->getValue()->getValue();
2569 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00002570 APInt Two(BitWidth, 2);
2571 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002572
Reid Spencere8019bb2007-03-01 07:25:48 +00002573 {
2574 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00002575 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00002576 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2577 // The B coefficient is M-N/2
2578 APInt B(M);
2579 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002580
Reid Spencere8019bb2007-03-01 07:25:48 +00002581 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00002582 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00002583
Reid Spencere8019bb2007-03-01 07:25:48 +00002584 // Compute the B^2-4ac term.
2585 APInt SqrtTerm(B);
2586 SqrtTerm *= B;
2587 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00002588
Reid Spencere8019bb2007-03-01 07:25:48 +00002589 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2590 // integer value or else APInt::sqrt() will assert.
2591 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002592
Reid Spencere8019bb2007-03-01 07:25:48 +00002593 // Compute the two solutions for the quadratic formula.
2594 // The divisions must be performed as signed divisions.
2595 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00002596 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00002597 if (TwoA.isMinValue()) {
2598 SCEV *CNC = new SCEVCouldNotCompute();
2599 return std::make_pair(CNC, CNC);
2600 }
2601
Reid Spencere8019bb2007-03-01 07:25:48 +00002602 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2603 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002604
Dan Gohman246b2562007-10-22 18:31:58 +00002605 return std::make_pair(SE.getConstant(Solution1),
2606 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00002607 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00002608}
2609
2610/// HowFarToZero - Return the number of times a backedge comparing the specified
2611/// value to zero will execute. If not computable, return UnknownValue
2612SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2613 // If the value is a constant
2614 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2615 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00002616 if (C->getValue()->isZero()) return C;
Chris Lattner53e677a2004-04-02 20:23:17 +00002617 return UnknownValue; // Otherwise it will loop infinitely.
2618 }
2619
2620 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2621 if (!AddRec || AddRec->getLoop() != L)
2622 return UnknownValue;
2623
2624 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002625 // If this is an affine expression, the execution count of this branch is
2626 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00002627 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002628 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00002629 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002630 // equivalent to:
2631 //
2632 // Step*N = -Start (mod 2^BW)
2633 //
2634 // where BW is the common bit width of Start and Step.
2635
Chris Lattner53e677a2004-04-02 20:23:17 +00002636 // Get the initial value for the loop.
2637 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00002638 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002639
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002640 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002641
Chris Lattner53e677a2004-04-02 20:23:17 +00002642 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002643 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00002644
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002645 // First, handle unitary steps.
2646 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
2647 return SE.getNegativeSCEV(Start); // N = -Start (as unsigned)
2648 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2649 return Start; // N = Start (as unsigned)
2650
2651 // Then, try to solve the above equation provided that Start is constant.
2652 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2653 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
2654 -StartC->getValue()->getValue(),SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002655 }
Chris Lattner42a75512007-01-15 02:27:26 +00002656 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002657 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2658 // the quadratic equation to solve it.
Dan Gohman246b2562007-10-22 18:31:58 +00002659 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002660 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2661 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2662 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002663#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002664 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2665 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002666#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002667 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002668 if (ConstantInt *CB =
2669 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002670 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002671 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002672 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002673
Chris Lattner53e677a2004-04-02 20:23:17 +00002674 // We can only use this value if the chrec ends up with an exact zero
2675 // value at this index. When solving for "X*X != 5", for example, we
2676 // should not accept a root of 2.
Dan Gohman246b2562007-10-22 18:31:58 +00002677 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002678 if (Val->isZero())
2679 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00002680 }
2681 }
2682 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002683
Chris Lattner53e677a2004-04-02 20:23:17 +00002684 return UnknownValue;
2685}
2686
2687/// HowFarToNonZero - Return the number of times a backedge checking the
2688/// specified value for nonzero will execute. If not computable, return
2689/// UnknownValue
2690SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2691 // Loops that look like: while (X == 0) are very strange indeed. We don't
2692 // handle them yet except for the trivial case. This could be expanded in the
2693 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002694
Chris Lattner53e677a2004-04-02 20:23:17 +00002695 // If the value is a constant, check to see if it is known to be non-zero
2696 // already. If so, the backedge will execute zero times.
2697 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00002698 if (!C->getValue()->isNullValue())
2699 return SE.getIntegerSCEV(0, C->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002700 return UnknownValue; // Otherwise it will loop infinitely.
2701 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002702
Chris Lattner53e677a2004-04-02 20:23:17 +00002703 // We could implement others, but I really doubt anyone writes loops like
2704 // this, and if they did, they would already be constant folded.
2705 return UnknownValue;
2706}
2707
Dan Gohmanfd6edef2008-09-15 22:18:04 +00002708/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2709/// (which may not be an immediate predecessor) which has exactly one
2710/// successor from which BB is reachable, or null if no such block is
2711/// found.
2712///
2713BasicBlock *
2714ScalarEvolutionsImpl::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
2715 // If the block has a unique predecessor, the predecessor must have
2716 // no other successors from which BB is reachable.
2717 if (BasicBlock *Pred = BB->getSinglePredecessor())
2718 return Pred;
2719
2720 // A loop's header is defined to be a block that dominates the loop.
2721 // If the loop has a preheader, it must be a block that has exactly
2722 // one successor that can reach BB. This is slightly more strict
2723 // than necessary, but works if critical edges are split.
2724 if (Loop *L = LI.getLoopFor(BB))
2725 return L->getLoopPreheader();
2726
2727 return 0;
2728}
2729
Dan Gohmanc2390b12009-02-12 22:19:27 +00002730/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Nick Lewycky59cff122008-07-12 07:41:32 +00002731/// a conditional between LHS and RHS.
Dan Gohmanc2390b12009-02-12 22:19:27 +00002732bool ScalarEvolutionsImpl::isLoopGuardedByCond(const Loop *L,
2733 ICmpInst::Predicate Pred,
Nick Lewycky59cff122008-07-12 07:41:32 +00002734 SCEV *LHS, SCEV *RHS) {
2735 BasicBlock *Preheader = L->getLoopPreheader();
2736 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00002737
Dan Gohman38372182008-08-12 20:17:31 +00002738 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohmanfd6edef2008-09-15 22:18:04 +00002739 // there are predecessors that can be found that have unique successors
2740 // leading to the original header.
2741 for (; Preheader;
2742 PreheaderDest = Preheader,
2743 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohman38372182008-08-12 20:17:31 +00002744
2745 BranchInst *LoopEntryPredicate =
Nick Lewycky59cff122008-07-12 07:41:32 +00002746 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00002747 if (!LoopEntryPredicate ||
2748 LoopEntryPredicate->isUnconditional())
2749 continue;
2750
2751 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
2752 if (!ICI) continue;
2753
2754 // Now that we found a conditional branch that dominates the loop, check to
2755 // see if it is the comparison we are looking for.
2756 Value *PreCondLHS = ICI->getOperand(0);
2757 Value *PreCondRHS = ICI->getOperand(1);
2758 ICmpInst::Predicate Cond;
2759 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2760 Cond = ICI->getPredicate();
2761 else
2762 Cond = ICI->getInversePredicate();
2763
Dan Gohmanc2390b12009-02-12 22:19:27 +00002764 if (Cond == Pred)
2765 ; // An exact match.
2766 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
2767 ; // The actual condition is beyond sufficient.
2768 else
2769 // Check a few special cases.
2770 switch (Cond) {
2771 case ICmpInst::ICMP_UGT:
2772 if (Pred == ICmpInst::ICMP_ULT) {
2773 std::swap(PreCondLHS, PreCondRHS);
2774 Cond = ICmpInst::ICMP_ULT;
2775 break;
2776 }
2777 continue;
2778 case ICmpInst::ICMP_SGT:
2779 if (Pred == ICmpInst::ICMP_SLT) {
2780 std::swap(PreCondLHS, PreCondRHS);
2781 Cond = ICmpInst::ICMP_SLT;
2782 break;
2783 }
2784 continue;
2785 case ICmpInst::ICMP_NE:
2786 // Expressions like (x >u 0) are often canonicalized to (x != 0),
2787 // so check for this case by checking if the NE is comparing against
2788 // a minimum or maximum constant.
2789 if (!ICmpInst::isTrueWhenEqual(Pred))
2790 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
2791 const APInt &A = CI->getValue();
2792 switch (Pred) {
2793 case ICmpInst::ICMP_SLT:
2794 if (A.isMaxSignedValue()) break;
2795 continue;
2796 case ICmpInst::ICMP_SGT:
2797 if (A.isMinSignedValue()) break;
2798 continue;
2799 case ICmpInst::ICMP_ULT:
2800 if (A.isMaxValue()) break;
2801 continue;
2802 case ICmpInst::ICMP_UGT:
2803 if (A.isMinValue()) break;
2804 continue;
2805 default:
2806 continue;
2807 }
2808 Cond = ICmpInst::ICMP_NE;
2809 // NE is symmetric but the original comparison may not be. Swap
2810 // the operands if necessary so that they match below.
2811 if (isa<SCEVConstant>(LHS))
2812 std::swap(PreCondLHS, PreCondRHS);
2813 break;
2814 }
2815 continue;
2816 default:
2817 // We weren't able to reconcile the condition.
2818 continue;
2819 }
Dan Gohman38372182008-08-12 20:17:31 +00002820
2821 if (!PreCondLHS->getType()->isInteger()) continue;
2822
2823 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
2824 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
2825 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
2826 (LHS == SE.getNotSCEV(PreCondRHSSCEV) &&
2827 RHS == SE.getNotSCEV(PreCondLHSSCEV)))
2828 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00002829 }
2830
Dan Gohman38372182008-08-12 20:17:31 +00002831 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00002832}
2833
Chris Lattnerdb25de42005-08-15 23:33:51 +00002834/// HowManyLessThans - Return the number of times a backedge containing the
2835/// specified less-than comparison will execute. If not computable, return
2836/// UnknownValue.
2837SCEVHandle ScalarEvolutionsImpl::
Nick Lewycky789558d2009-01-13 09:18:58 +00002838HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00002839 // Only handle: "ADDREC < LoopInvariant".
2840 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2841
2842 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2843 if (!AddRec || AddRec->getLoop() != L)
2844 return UnknownValue;
2845
2846 if (AddRec->isAffine()) {
Nick Lewycky789558d2009-01-13 09:18:58 +00002847 // FORNOW: We only support unit strides.
2848 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
2849 if (AddRec->getOperand(1) != One)
Chris Lattnerdb25de42005-08-15 23:33:51 +00002850 return UnknownValue;
2851
Nick Lewycky789558d2009-01-13 09:18:58 +00002852 // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
2853 // m. So, we count the number of iterations in which {n,+,1} < m is true.
2854 // Note that we cannot simply return max(m-n,0) because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00002855 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00002856
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00002857 // First, we get the value of the LHS in the first iteration: n
2858 SCEVHandle Start = AddRec->getOperand(0);
2859
Dan Gohmanc2390b12009-02-12 22:19:27 +00002860 if (isLoopGuardedByCond(L,
2861 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
Nick Lewycky789558d2009-01-13 09:18:58 +00002862 SE.getMinusSCEV(AddRec->getOperand(0), One), RHS)) {
2863 // Since we know that the condition is true in order to enter the loop,
2864 // we know that it will run exactly m-n times.
2865 return SE.getMinusSCEV(RHS, Start);
2866 } else {
2867 // Then, we get the value of the LHS in the first iteration in which the
2868 // above condition doesn't hold. This equals to max(m,n).
2869 SCEVHandle End = isSigned ? SE.getSMaxExpr(RHS, Start)
2870 : SE.getUMaxExpr(RHS, Start);
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00002871
Nick Lewycky789558d2009-01-13 09:18:58 +00002872 // Finally, we subtract these two values to get the number of times the
2873 // backedge is executed: max(m,n)-n.
2874 return SE.getMinusSCEV(End, Start);
Nick Lewycky1447f5c2008-12-16 08:30:01 +00002875 }
Chris Lattnerdb25de42005-08-15 23:33:51 +00002876 }
2877
2878 return UnknownValue;
2879}
2880
Chris Lattner53e677a2004-04-02 20:23:17 +00002881/// getNumIterationsInRange - Return the number of iterations of this loop that
2882/// produce values in the specified constant range. Another way of looking at
2883/// this is that it returns the first iteration number where the value is not in
2884/// the condition, thus computing the exit count. If the iteration count can't
2885/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman246b2562007-10-22 18:31:58 +00002886SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2887 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002888 if (Range.isFullSet()) // Infinite loop.
2889 return new SCEVCouldNotCompute();
2890
2891 // If the start is a non-zero constant, shift the range to simplify things.
2892 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00002893 if (!SC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002894 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00002895 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
2896 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002897 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2898 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00002899 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002900 // This is strange and shouldn't happen.
2901 return new SCEVCouldNotCompute();
2902 }
2903
2904 // The only time we can solve this is when we have all constant indices.
2905 // Otherwise, we cannot determine the overflow conditions.
2906 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2907 if (!isa<SCEVConstant>(getOperand(i)))
2908 return new SCEVCouldNotCompute();
2909
2910
2911 // Okay at this point we know that all elements of the chrec are constants and
2912 // that the start element is zero.
2913
2914 // First check to see if the range contains zero. If not, the first
2915 // iteration exits.
Reid Spencera6e8a952007-03-01 07:54:15 +00002916 if (!Range.contains(APInt(getBitWidth(),0)))
Dan Gohman246b2562007-10-22 18:31:58 +00002917 return SE.getConstant(ConstantInt::get(getType(),0));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002918
Chris Lattner53e677a2004-04-02 20:23:17 +00002919 if (isAffine()) {
2920 // If this is an affine expression then we have this situation:
2921 // Solve {0,+,A} in Range === Ax in Range
2922
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002923 // We know that zero is in the range. If A is positive then we know that
2924 // the upper value of the range must be the first possible exit value.
2925 // If A is negative then the lower of the range is the last possible loop
2926 // value. Also note that we already checked for a full range.
Reid Spencer581b0d42007-02-28 19:57:34 +00002927 APInt One(getBitWidth(),1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002928 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
2929 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00002930
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002931 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00002932 APInt ExitVal = (End + A).udiv(A);
Reid Spencerc7cd7a02007-03-01 19:32:33 +00002933 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00002934
2935 // Evaluate at the exit value. If we really did fall out of the valid
2936 // range, then we computed our trip count, otherwise wrap around or other
2937 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00002938 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002939 if (Range.contains(Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002940 return new SCEVCouldNotCompute(); // Something strange happened
2941
2942 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00002943 assert(Range.contains(
2944 EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00002945 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002946 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00002947 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00002948 } else if (isQuadratic()) {
2949 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2950 // quadratic equation to solve it. To do this, we must frame our problem in
2951 // terms of figuring out when zero is crossed, instead of when
2952 // Range.getUpper() is crossed.
2953 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00002954 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
2955 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002956
2957 // Next, solve the constructed addrec
2958 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00002959 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002960 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2961 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2962 if (R1) {
2963 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002964 if (ConstantInt *CB =
2965 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002966 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002967 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002968 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002969
Chris Lattner53e677a2004-04-02 20:23:17 +00002970 // Make sure the root is not off by one. The returned iteration should
2971 // not be in the range, but the previous one should be. When solving
2972 // for "X*X < 5", for example, we should not return a root of 2.
2973 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00002974 R1->getValue(),
2975 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002976 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002977 // The next iteration must be out of the range...
Dan Gohman9a6ae962007-07-09 15:25:17 +00002978 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002979
Dan Gohman246b2562007-10-22 18:31:58 +00002980 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002981 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00002982 return SE.getConstant(NextVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00002983 return new SCEVCouldNotCompute(); // Something strange happened
2984 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002985
Chris Lattner53e677a2004-04-02 20:23:17 +00002986 // If R1 was not in the range, then it is a good return value. Make
2987 // sure that R1-1 WAS in the range though, just in case.
Dan Gohman9a6ae962007-07-09 15:25:17 +00002988 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00002989 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00002990 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002991 return R1;
2992 return new SCEVCouldNotCompute(); // Something strange happened
2993 }
2994 }
2995 }
2996
Chris Lattner53e677a2004-04-02 20:23:17 +00002997 return new SCEVCouldNotCompute();
2998}
2999
3000
3001
3002//===----------------------------------------------------------------------===//
3003// ScalarEvolution Class Implementation
3004//===----------------------------------------------------------------------===//
3005
3006bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohman246b2562007-10-22 18:31:58 +00003007 Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>());
Chris Lattner53e677a2004-04-02 20:23:17 +00003008 return false;
3009}
3010
3011void ScalarEvolution::releaseMemory() {
3012 delete (ScalarEvolutionsImpl*)Impl;
3013 Impl = 0;
3014}
3015
3016void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3017 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00003018 AU.addRequiredTransitive<LoopInfo>();
3019}
3020
3021SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
3022 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
3023}
3024
Chris Lattnera0740fb2005-08-09 23:36:33 +00003025/// hasSCEV - Return true if the SCEV for this value has already been
3026/// computed.
3027bool ScalarEvolution::hasSCEV(Value *V) const {
Chris Lattner05bd3742005-08-10 00:59:40 +00003028 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
Chris Lattnera0740fb2005-08-09 23:36:33 +00003029}
3030
3031
3032/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
3033/// the specified value.
3034void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
3035 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
3036}
3037
3038
Dan Gohmanc2390b12009-02-12 22:19:27 +00003039bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
3040 ICmpInst::Predicate Pred,
3041 SCEV *LHS, SCEV *RHS) {
3042 return ((ScalarEvolutionsImpl*)Impl)->isLoopGuardedByCond(L, Pred,
3043 LHS, RHS);
3044}
3045
Chris Lattner53e677a2004-04-02 20:23:17 +00003046SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
3047 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
3048}
3049
3050bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
3051 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
3052}
3053
3054SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
3055 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
3056}
3057
Dan Gohman5cec4db2007-06-19 14:28:31 +00003058void ScalarEvolution::deleteValueFromRecords(Value *V) const {
3059 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003060}
3061
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003062static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00003063 const Loop *L) {
3064 // Print all inner loops first
3065 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3066 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003067
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003068 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00003069
Devang Patelb7211a22007-08-21 00:31:24 +00003070 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00003071 L->getExitBlocks(ExitBlocks);
3072 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003073 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003074
3075 if (SE->hasLoopInvariantIterationCount(L)) {
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003076 OS << *SE->getIterationCount(L) << " iterations! ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003077 } else {
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003078 OS << "Unpredictable iteration count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003079 }
3080
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003081 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00003082}
3083
Reid Spencerce9653c2004-12-07 04:03:45 +00003084void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00003085 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
3086 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
3087
3088 OS << "Classifying expressions for: " << F.getName() << "\n";
3089 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner42a75512007-01-15 02:27:26 +00003090 if (I->getType()->isInteger()) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00003091 OS << *I;
Dan Gohman8dae1382008-09-14 17:21:12 +00003092 OS << " --> ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00003093 SCEVHandle SV = getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00003094 SV->print(OS);
3095 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003096
Chris Lattner6ffe5512004-04-27 15:13:33 +00003097 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003098 OS << "Exits: ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00003099 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003100 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3101 OS << "<<Unknown>>";
3102 } else {
3103 OS << *ExitValue;
3104 }
3105 }
3106
3107
3108 OS << "\n";
3109 }
3110
3111 OS << "Determining loop execution counts for: " << F.getName() << "\n";
3112 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
3113 PrintLoopInfo(OS, this, *I);
3114}