blob: 1dd5026d7493e63c3dfc3c9bc27169ade656b90c [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);
Dale Johannesen1bdd93a2008-12-03 22:45:31 +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
Nick Lewycky48dd6442008-12-02 08:05:48 +0000328
329// SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular
330// input. Don't use a SCEVHandle here, or else the object will never be
331// deleted!
332static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
333 SCEVSDivExpr*> > SCEVSDivs;
334
335SCEVSDivExpr::~SCEVSDivExpr() {
336 SCEVSDivs->erase(std::make_pair(LHS, RHS));
337}
338
339void SCEVSDivExpr::print(std::ostream &OS) const {
340 OS << "(" << *LHS << " /s " << *RHS << ")";
341}
342
343const Type *SCEVSDivExpr::getType() const {
344 return LHS->getType();
345}
346
347
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000348// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
349// particular input. Don't use a SCEVHandle here, or else the object will never
350// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000351static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
352 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000353
354SCEVAddRecExpr::~SCEVAddRecExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000355 SCEVAddRecExprs->erase(std::make_pair(L,
356 std::vector<SCEV*>(Operands.begin(),
357 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000358}
359
Chris Lattner4dc534c2005-02-13 04:37:18 +0000360SCEVHandle SCEVAddRecExpr::
361replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman246b2562007-10-22 18:31:58 +0000362 const SCEVHandle &Conc,
363 ScalarEvolution &SE) const {
Chris Lattner4dc534c2005-02-13 04:37:18 +0000364 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman246b2562007-10-22 18:31:58 +0000365 SCEVHandle H =
366 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000367 if (H != getOperand(i)) {
368 std::vector<SCEVHandle> NewOps;
369 NewOps.reserve(getNumOperands());
370 for (unsigned j = 0; j != i; ++j)
371 NewOps.push_back(getOperand(j));
372 NewOps.push_back(H);
373 for (++i; i != e; ++i)
374 NewOps.push_back(getOperand(i)->
Dan Gohman246b2562007-10-22 18:31:58 +0000375 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000376
Dan Gohman246b2562007-10-22 18:31:58 +0000377 return SE.getAddRecExpr(NewOps, L);
Chris Lattner4dc534c2005-02-13 04:37:18 +0000378 }
379 }
380 return this;
381}
382
383
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000384bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
385 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000386 // contain L and if the start is invariant.
387 return !QueryLoop->contains(L->getHeader()) &&
388 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000389}
390
391
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000392void SCEVAddRecExpr::print(std::ostream &OS) const {
393 OS << "{" << *Operands[0];
394 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
395 OS << ",+," << *Operands[i];
396 OS << "}<" << L->getHeader()->getName() + ">";
397}
Chris Lattner53e677a2004-04-02 20:23:17 +0000398
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000399// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
400// value. Don't use a SCEVHandle here, or else the object will never be
401// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000402static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000403
Chris Lattnerb3364092006-10-04 21:49:37 +0000404SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000405
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000406bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
407 // All non-instruction values are loop invariant. All instructions are loop
408 // invariant if they are not contained in the specified loop.
409 if (Instruction *I = dyn_cast<Instruction>(V))
410 return !L->contains(I->getParent());
411 return true;
412}
Chris Lattner53e677a2004-04-02 20:23:17 +0000413
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000414const Type *SCEVUnknown::getType() const {
415 return V->getType();
416}
Chris Lattner53e677a2004-04-02 20:23:17 +0000417
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000418void SCEVUnknown::print(std::ostream &OS) const {
419 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000420}
421
Chris Lattner8d741b82004-06-20 06:23:15 +0000422//===----------------------------------------------------------------------===//
423// SCEV Utilities
424//===----------------------------------------------------------------------===//
425
426namespace {
427 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
428 /// than the complexity of the RHS. This comparator is used to canonicalize
429 /// expressions.
Chris Lattner95255282006-06-28 23:17:24 +0000430 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000431 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Chris Lattner8d741b82004-06-20 06:23:15 +0000432 return LHS->getSCEVType() < RHS->getSCEVType();
433 }
434 };
435}
436
437/// GroupByComplexity - Given a list of SCEV objects, order them by their
438/// complexity, and group objects of the same complexity together by value.
439/// When this routine is finished, we know that any duplicates in the vector are
440/// consecutive and that complexity is monotonically increasing.
441///
442/// Note that we go take special precautions to ensure that we get determinstic
443/// results from this routine. In other words, we don't want the results of
444/// this to depend on where the addresses of various SCEV objects happened to
445/// land in memory.
446///
447static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
448 if (Ops.size() < 2) return; // Noop
449 if (Ops.size() == 2) {
450 // This is the common case, which also happens to be trivially simple.
451 // Special case it.
Dan Gohmanf7b37b22008-04-14 18:23:56 +0000452 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
Chris Lattner8d741b82004-06-20 06:23:15 +0000453 std::swap(Ops[0], Ops[1]);
454 return;
455 }
456
457 // Do the rough sort by complexity.
458 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
459
460 // Now that we are sorted by complexity, group elements of the same
461 // complexity. Note that this is, at worst, N^2, but the vector is likely to
462 // be extremely short in practice. Note that we take this approach because we
463 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000464 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000465 SCEV *S = Ops[i];
466 unsigned Complexity = S->getSCEVType();
467
468 // If there are any objects of the same complexity and same value as this
469 // one, group them.
470 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
471 if (Ops[j] == S) { // Found a duplicate.
472 // Move it to immediately after i'th element.
473 std::swap(Ops[i+1], Ops[j]);
474 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000475 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000476 }
477 }
478 }
479}
480
Chris Lattner53e677a2004-04-02 20:23:17 +0000481
Chris Lattner53e677a2004-04-02 20:23:17 +0000482
483//===----------------------------------------------------------------------===//
484// Simple SCEV method implementations
485//===----------------------------------------------------------------------===//
486
487/// getIntegerSCEV - Given an integer or FP type, create a constant for the
488/// specified signed integer value and return a SCEV for the constant.
Dan Gohman246b2562007-10-22 18:31:58 +0000489SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000490 Constant *C;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000491 if (Val == 0)
Chris Lattner53e677a2004-04-02 20:23:17 +0000492 C = Constant::getNullValue(Ty);
493 else if (Ty->isFloatingPoint())
Chris Lattner02a260a2008-04-20 00:41:09 +0000494 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
495 APFloat::IEEEdouble, Val));
Reid Spencere4d87aa2006-12-23 06:05:41 +0000496 else
Reid Spencerb83eb642006-10-20 07:07:24 +0000497 C = ConstantInt::get(Ty, Val);
Dan Gohman246b2562007-10-22 18:31:58 +0000498 return getUnknown(C);
Chris Lattner53e677a2004-04-02 20:23:17 +0000499}
500
Chris Lattner53e677a2004-04-02 20:23:17 +0000501/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
502///
Dan Gohman246b2562007-10-22 18:31:58 +0000503SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000504 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman246b2562007-10-22 18:31:58 +0000505 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000506
Nick Lewycky178f20a2008-02-20 06:58:55 +0000507 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(V->getType())));
Nick Lewycky3e630762008-02-20 06:48:22 +0000508}
509
510/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
511SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
512 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
513 return getUnknown(ConstantExpr::getNot(VC->getValue()));
514
Nick Lewycky178f20a2008-02-20 06:58:55 +0000515 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(V->getType()));
Nick Lewycky3e630762008-02-20 06:48:22 +0000516 return getMinusSCEV(AllOnes, V);
Chris Lattner53e677a2004-04-02 20:23:17 +0000517}
518
519/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
520///
Dan Gohman246b2562007-10-22 18:31:58 +0000521SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
522 const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000523 // X - Y --> X + -Y
Dan Gohman246b2562007-10-22 18:31:58 +0000524 return getAddExpr(LHS, getNegativeSCEV(RHS));
Chris Lattner53e677a2004-04-02 20:23:17 +0000525}
526
527
Eli Friedmanb42a6262008-08-04 23:49:06 +0000528/// BinomialCoefficient - Compute BC(It, K). The result has width W.
529// Assume, K > 0.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000530static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedmanb42a6262008-08-04 23:49:06 +0000531 ScalarEvolution &SE,
532 const IntegerType* ResultTy) {
533 // Handle the simplest case efficiently.
534 if (K == 1)
535 return SE.getTruncateOrZeroExtend(It, ResultTy);
536
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000537 // We are using the following formula for BC(It, K):
538 //
539 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
540 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000541 // Suppose, W is the bitwidth of the return value. We must be prepared for
542 // overflow. Hence, we must assure that the result of our computation is
543 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
544 // safe in modular arithmetic.
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000545 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000546 // However, this code doesn't use exactly that formula; the formula it uses
547 // is something like the following, where T is the number of factors of 2 in
548 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
549 // exponentiation:
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000550 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000551 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000552 //
Eli Friedmanb42a6262008-08-04 23:49:06 +0000553 // This formula is trivially equivalent to the previous formula. However,
554 // this formula can be implemented much more efficiently. The trick is that
555 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
556 // arithmetic. To do exact division in modular arithmetic, all we have
557 // to do is multiply by the inverse. Therefore, this step can be done at
558 // width W.
559 //
560 // The next issue is how to safely do the division by 2^T. The way this
561 // is done is by doing the multiplication step at a width of at least W + T
562 // bits. This way, the bottom W+T bits of the product are accurate. Then,
563 // when we perform the division by 2^T (which is equivalent to a right shift
564 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
565 // truncated out after the division by 2^T.
566 //
567 // In comparison to just directly using the first formula, this technique
568 // is much more efficient; using the first formula requires W * K bits,
569 // but this formula less than W + K bits. Also, the first formula requires
570 // a division step, whereas this formula only requires multiplies and shifts.
571 //
572 // It doesn't matter whether the subtraction step is done in the calculation
573 // width or the input iteration count's width; if the subtraction overflows,
574 // the result must be zero anyway. We prefer here to do it in the width of
575 // the induction variable because it helps a lot for certain cases; CodeGen
576 // isn't smart enough to ignore the overflow, which leads to much less
577 // efficient code if the width of the subtraction is wider than the native
578 // register width.
579 //
580 // (It's possible to not widen at all by pulling out factors of 2 before
581 // the multiplication; for example, K=2 can be calculated as
582 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
583 // extra arithmetic, so it's not an obvious win, and it gets
584 // much more complicated for K > 3.)
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000585
Eli Friedmanb42a6262008-08-04 23:49:06 +0000586 // Protection from insane SCEVs; this bound is conservative,
587 // but it probably doesn't matter.
588 if (K > 1000)
589 return new SCEVCouldNotCompute();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000590
Eli Friedmanb42a6262008-08-04 23:49:06 +0000591 unsigned W = ResultTy->getBitWidth();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000592
Eli Friedmanb42a6262008-08-04 23:49:06 +0000593 // Calculate K! / 2^T and T; we divide out the factors of two before
594 // multiplying for calculating K! / 2^T to avoid overflow.
595 // Other overflow doesn't matter because we only care about the bottom
596 // W bits of the result.
597 APInt OddFactorial(W, 1);
598 unsigned T = 1;
599 for (unsigned i = 3; i <= K; ++i) {
600 APInt Mult(W, i);
601 unsigned TwoFactors = Mult.countTrailingZeros();
602 T += TwoFactors;
603 Mult = Mult.lshr(TwoFactors);
604 OddFactorial *= Mult;
Chris Lattner53e677a2004-04-02 20:23:17 +0000605 }
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000606
Eli Friedmanb42a6262008-08-04 23:49:06 +0000607 // We need at least W + T bits for the multiplication step
608 // FIXME: A temporary hack; we round up the bitwidths
609 // to the nearest power of 2 to be nice to the code generator.
610 unsigned CalculationBits = 1U << Log2_32_Ceil(W + T);
611 // FIXME: Temporary hack to avoid generating integers that are too wide.
612 // Although, it's not completely clear how to determine how much
613 // widening is safe; for example, on X86, we can't really widen
614 // beyond 64 because we need to be able to do multiplication
615 // that's CalculationBits wide, but on X86-64, we can safely widen up to
616 // 128 bits.
617 if (CalculationBits > 64)
618 return new SCEVCouldNotCompute();
619
620 // Calcuate 2^T, at width T+W.
621 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
622
623 // Calculate the multiplicative inverse of K! / 2^T;
624 // this multiplication factor will perform the exact division by
625 // K! / 2^T.
626 APInt Mod = APInt::getSignedMinValue(W+1);
627 APInt MultiplyFactor = OddFactorial.zext(W+1);
628 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
629 MultiplyFactor = MultiplyFactor.trunc(W);
630
631 // Calculate the product, at width T+W
632 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
633 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
634 for (unsigned i = 1; i != K; ++i) {
635 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
636 Dividend = SE.getMulExpr(Dividend,
637 SE.getTruncateOrZeroExtend(S, CalculationTy));
638 }
639
640 // Divide by 2^T
641 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
642
643 // Truncate the result, and divide by K! / 2^T.
644
645 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
646 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattner53e677a2004-04-02 20:23:17 +0000647}
648
Chris Lattner53e677a2004-04-02 20:23:17 +0000649/// evaluateAtIteration - Return the value of this chain of recurrences at
650/// the specified iteration number. We can evaluate this recurrence by
651/// multiplying each element in the chain by the binomial coefficient
652/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
653///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000654/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattner53e677a2004-04-02 20:23:17 +0000655///
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000656/// where BC(It, k) stands for binomial coefficient.
Chris Lattner53e677a2004-04-02 20:23:17 +0000657///
Dan Gohman246b2562007-10-22 18:31:58 +0000658SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
659 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +0000660 SCEVHandle Result = getStart();
Chris Lattner53e677a2004-04-02 20:23:17 +0000661 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +0000662 // The computation is correct in the face of overflow provided that the
663 // multiplication is performed _after_ the evaluation of the binomial
664 // coefficient.
Nick Lewyckycb8f1b52008-10-13 03:58:02 +0000665 SCEVHandle Coeff = BinomialCoefficient(It, i, SE,
666 cast<IntegerType>(getType()));
667 if (isa<SCEVCouldNotCompute>(Coeff))
668 return Coeff;
669
670 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattner53e677a2004-04-02 20:23:17 +0000671 }
672 return Result;
673}
674
Chris Lattner53e677a2004-04-02 20:23:17 +0000675//===----------------------------------------------------------------------===//
676// SCEV Expression folder implementations
677//===----------------------------------------------------------------------===//
678
Dan Gohman246b2562007-10-22 18:31:58 +0000679SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000680 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000681 return getUnknown(
Reid Spencer315d0552006-12-05 22:39:58 +0000682 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000683
684 // If the input value is a chrec scev made out of constants, truncate
685 // all of the constants.
686 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
687 std::vector<SCEVHandle> Operands;
688 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
689 // FIXME: This should allow truncation of other expression types!
690 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman246b2562007-10-22 18:31:58 +0000691 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000692 else
693 break;
694 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman246b2562007-10-22 18:31:58 +0000695 return getAddRecExpr(Operands, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000696 }
697
Chris Lattnerb3364092006-10-04 21:49:37 +0000698 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000699 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
700 return Result;
701}
702
Dan Gohman246b2562007-10-22 18:31:58 +0000703SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000704 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000705 return getUnknown(
Reid Spencerd977d862006-12-12 23:36:14 +0000706 ConstantExpr::getZExt(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000707
708 // FIXME: If the input value is a chrec scev, and we can prove that the value
709 // did not overflow the old, smaller, value, we can zero extend all of the
710 // operands (often constants). This would allow analysis of something like
711 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
712
Chris Lattnerb3364092006-10-04 21:49:37 +0000713 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000714 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
715 return Result;
716}
717
Dan Gohman246b2562007-10-22 18:31:58 +0000718SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmand19534a2007-06-15 14:38:12 +0000719 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman246b2562007-10-22 18:31:58 +0000720 return getUnknown(
Dan Gohmand19534a2007-06-15 14:38:12 +0000721 ConstantExpr::getSExt(SC->getValue(), Ty));
722
723 // FIXME: If the input value is a chrec scev, and we can prove that the value
724 // did not overflow the old, smaller, value, we can sign extend all of the
725 // operands (often constants). This would allow analysis of something like
726 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
727
728 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
729 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
730 return Result;
731}
732
Nick Lewycky6f8abf92008-06-13 04:38:55 +0000733/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
734/// of the input value to the specified type. If the type must be
735/// extended, it is zero extended.
736SCEVHandle ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
737 const Type *Ty) {
738 const Type *SrcTy = V->getType();
739 assert(SrcTy->isInteger() && Ty->isInteger() &&
740 "Cannot truncate or zero extend with non-integer arguments!");
741 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
742 return V; // No conversion
743 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
744 return getTruncateExpr(V, Ty);
745 return getZeroExtendExpr(V, Ty);
746}
747
Chris Lattner53e677a2004-04-02 20:23:17 +0000748// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman246b2562007-10-22 18:31:58 +0000749SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000750 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000751 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000752
753 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000754 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000755
756 // If there are any constants, fold them together.
757 unsigned Idx = 0;
758 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
759 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000760 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000761 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
762 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +0000763 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
764 RHSC->getValue()->getValue());
765 Ops[0] = getConstant(Fold);
766 Ops.erase(Ops.begin()+1); // Erase the folded element
767 if (Ops.size() == 1) return Ops[0];
768 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000769 }
770
771 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +0000772 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000773 Ops.erase(Ops.begin());
774 --Idx;
775 }
776 }
777
Chris Lattner627018b2004-04-07 16:16:11 +0000778 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000779
Chris Lattner53e677a2004-04-02 20:23:17 +0000780 // Okay, check to see if the same value occurs in the operand list twice. If
781 // so, merge them together into an multiply expression. Since we sorted the
782 // list, these values are required to be adjacent.
783 const Type *Ty = Ops[0]->getType();
784 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
785 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
786 // Found a match, merge the two values into a multiply, and add any
787 // remaining values to the result.
Dan Gohman246b2562007-10-22 18:31:58 +0000788 SCEVHandle Two = getIntegerSCEV(2, Ty);
789 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Chris Lattner53e677a2004-04-02 20:23:17 +0000790 if (Ops.size() == 2)
791 return Mul;
792 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
793 Ops.push_back(Mul);
Dan Gohman246b2562007-10-22 18:31:58 +0000794 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000795 }
796
Dan Gohmanf50cd742007-06-18 19:30:09 +0000797 // Now we know the first non-constant operand. Skip past any cast SCEVs.
798 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
799 ++Idx;
800
801 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +0000802 if (Idx < Ops.size()) {
803 bool DeletedAdd = false;
804 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
805 // If we have an add, expand the add operands onto the end of the operands
806 // list.
807 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
808 Ops.erase(Ops.begin()+Idx);
809 DeletedAdd = true;
810 }
811
812 // If we deleted at least one add, we added operands to the end of the list,
813 // and they are not necessarily sorted. Recurse to resort and resimplify
814 // any operands we just aquired.
815 if (DeletedAdd)
Dan Gohman246b2562007-10-22 18:31:58 +0000816 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000817 }
818
819 // Skip over the add expression until we get to a multiply.
820 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
821 ++Idx;
822
823 // If we are adding something to a multiply expression, make sure the
824 // something is not already an operand of the multiply. If so, merge it into
825 // the multiply.
826 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
827 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
828 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
829 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
830 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000831 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000832 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
833 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
834 if (Mul->getNumOperands() != 2) {
835 // If the multiply has more than two operands, we must get the
836 // Y*Z term.
837 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
838 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000839 InnerMul = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000840 }
Dan Gohman246b2562007-10-22 18:31:58 +0000841 SCEVHandle One = getIntegerSCEV(1, Ty);
842 SCEVHandle AddOne = getAddExpr(InnerMul, One);
843 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000844 if (Ops.size() == 2) return OuterMul;
845 if (AddOp < Idx) {
846 Ops.erase(Ops.begin()+AddOp);
847 Ops.erase(Ops.begin()+Idx-1);
848 } else {
849 Ops.erase(Ops.begin()+Idx);
850 Ops.erase(Ops.begin()+AddOp-1);
851 }
852 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000853 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000854 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000855
Chris Lattner53e677a2004-04-02 20:23:17 +0000856 // Check this multiply against other multiplies being added together.
857 for (unsigned OtherMulIdx = Idx+1;
858 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
859 ++OtherMulIdx) {
860 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
861 // If MulOp occurs in OtherMul, we can fold the two multiplies
862 // together.
863 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
864 OMulOp != e; ++OMulOp)
865 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
866 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
867 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
868 if (Mul->getNumOperands() != 2) {
869 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
870 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000871 InnerMul1 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000872 }
873 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
874 if (OtherMul->getNumOperands() != 2) {
875 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
876 OtherMul->op_end());
877 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman246b2562007-10-22 18:31:58 +0000878 InnerMul2 = getMulExpr(MulOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000879 }
Dan Gohman246b2562007-10-22 18:31:58 +0000880 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
881 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattner53e677a2004-04-02 20:23:17 +0000882 if (Ops.size() == 2) return OuterMul;
883 Ops.erase(Ops.begin()+Idx);
884 Ops.erase(Ops.begin()+OtherMulIdx-1);
885 Ops.push_back(OuterMul);
Dan Gohman246b2562007-10-22 18:31:58 +0000886 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000887 }
888 }
889 }
890 }
891
892 // If there are any add recurrences in the operands list, see if any other
893 // added values are loop invariant. If so, we can fold them into the
894 // recurrence.
895 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
896 ++Idx;
897
898 // Scan over all recurrences, trying to fold loop invariants into them.
899 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
900 // Scan all of the other operands to this add and add them to the vector if
901 // they are loop invariant w.r.t. the recurrence.
902 std::vector<SCEVHandle> LIOps;
903 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
904 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
905 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
906 LIOps.push_back(Ops[i]);
907 Ops.erase(Ops.begin()+i);
908 --i; --e;
909 }
910
911 // If we found some loop invariants, fold them into the recurrence.
912 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +0000913 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattner53e677a2004-04-02 20:23:17 +0000914 LIOps.push_back(AddRec->getStart());
915
916 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +0000917 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattner53e677a2004-04-02 20:23:17 +0000918
Dan Gohman246b2562007-10-22 18:31:58 +0000919 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000920 // If all of the other operands were loop invariant, we are done.
921 if (Ops.size() == 1) return NewRec;
922
923 // Otherwise, add the folded AddRec by the non-liv parts.
924 for (unsigned i = 0;; ++i)
925 if (Ops[i] == AddRec) {
926 Ops[i] = NewRec;
927 break;
928 }
Dan Gohman246b2562007-10-22 18:31:58 +0000929 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000930 }
931
932 // Okay, if there weren't any loop invariants to be folded, check to see if
933 // there are multiple AddRec's with the same loop induction variable being
934 // added together. If so, we can fold them.
935 for (unsigned OtherIdx = Idx+1;
936 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
937 if (OtherIdx != Idx) {
938 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
939 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
940 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
941 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
942 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
943 if (i >= NewOps.size()) {
944 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
945 OtherAddRec->op_end());
946 break;
947 }
Dan Gohman246b2562007-10-22 18:31:58 +0000948 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Chris Lattner53e677a2004-04-02 20:23:17 +0000949 }
Dan Gohman246b2562007-10-22 18:31:58 +0000950 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +0000951
952 if (Ops.size() == 2) return NewAddRec;
953
954 Ops.erase(Ops.begin()+Idx);
955 Ops.erase(Ops.begin()+OtherIdx-1);
956 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +0000957 return getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000958 }
959 }
960
961 // Otherwise couldn't fold anything into this recurrence. Move onto the
962 // next one.
963 }
964
965 // Okay, it looks like we really DO need an add expr. Check to see if we
966 // already have one, otherwise create a new one.
967 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000968 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
969 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000970 if (Result == 0) Result = new SCEVAddExpr(Ops);
971 return Result;
972}
973
974
Dan Gohman246b2562007-10-22 18:31:58 +0000975SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000976 assert(!Ops.empty() && "Cannot get empty mul!");
977
978 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000979 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000980
981 // If there are any constants, fold them together.
982 unsigned Idx = 0;
983 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
984
985 // C1*(C2+V) -> C1*C2 + C1*V
986 if (Ops.size() == 2)
987 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
988 if (Add->getNumOperands() == 2 &&
989 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman246b2562007-10-22 18:31:58 +0000990 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
991 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000992
993
994 ++Idx;
995 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
996 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +0000997 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
998 RHSC->getValue()->getValue());
999 Ops[0] = getConstant(Fold);
1000 Ops.erase(Ops.begin()+1); // Erase the folded element
1001 if (Ops.size() == 1) return Ops[0];
1002 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +00001003 }
1004
1005 // If we are left with a constant one being multiplied, strip it off.
1006 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1007 Ops.erase(Ops.begin());
1008 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +00001009 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001010 // If we have a multiply of zero, it will always be zero.
1011 return Ops[0];
1012 }
1013 }
1014
1015 // Skip over the add expression until we get to a multiply.
1016 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1017 ++Idx;
1018
1019 if (Ops.size() == 1)
1020 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001021
Chris Lattner53e677a2004-04-02 20:23:17 +00001022 // If there are mul operands inline them all into this expression.
1023 if (Idx < Ops.size()) {
1024 bool DeletedMul = false;
1025 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1026 // If we have an mul, expand the mul operands onto the end of the operands
1027 // list.
1028 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1029 Ops.erase(Ops.begin()+Idx);
1030 DeletedMul = true;
1031 }
1032
1033 // If we deleted at least one mul, we added operands to the end of the list,
1034 // and they are not necessarily sorted. Recurse to resort and resimplify
1035 // any operands we just aquired.
1036 if (DeletedMul)
Dan Gohman246b2562007-10-22 18:31:58 +00001037 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001038 }
1039
1040 // If there are any add recurrences in the operands list, see if any other
1041 // added values are loop invariant. If so, we can fold them into the
1042 // recurrence.
1043 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1044 ++Idx;
1045
1046 // Scan over all recurrences, trying to fold loop invariants into them.
1047 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1048 // Scan all of the other operands to this mul and add them to the vector if
1049 // they are loop invariant w.r.t. the recurrence.
1050 std::vector<SCEVHandle> LIOps;
1051 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1052 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1053 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1054 LIOps.push_back(Ops[i]);
1055 Ops.erase(Ops.begin()+i);
1056 --i; --e;
1057 }
1058
1059 // If we found some loop invariants, fold them into the recurrence.
1060 if (!LIOps.empty()) {
Dan Gohman8dae1382008-09-14 17:21:12 +00001061 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Chris Lattner53e677a2004-04-02 20:23:17 +00001062 std::vector<SCEVHandle> NewOps;
1063 NewOps.reserve(AddRec->getNumOperands());
1064 if (LIOps.size() == 1) {
1065 SCEV *Scale = LIOps[0];
1066 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman246b2562007-10-22 18:31:58 +00001067 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001068 } else {
1069 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1070 std::vector<SCEVHandle> MulOps(LIOps);
1071 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001072 NewOps.push_back(getMulExpr(MulOps));
Chris Lattner53e677a2004-04-02 20:23:17 +00001073 }
1074 }
1075
Dan Gohman246b2562007-10-22 18:31:58 +00001076 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001077
1078 // If all of the other operands were loop invariant, we are done.
1079 if (Ops.size() == 1) return NewRec;
1080
1081 // Otherwise, multiply the folded AddRec by the non-liv parts.
1082 for (unsigned i = 0;; ++i)
1083 if (Ops[i] == AddRec) {
1084 Ops[i] = NewRec;
1085 break;
1086 }
Dan Gohman246b2562007-10-22 18:31:58 +00001087 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001088 }
1089
1090 // Okay, if there weren't any loop invariants to be folded, check to see if
1091 // there are multiple AddRec's with the same loop induction variable being
1092 // multiplied together. If so, we can fold them.
1093 for (unsigned OtherIdx = Idx+1;
1094 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1095 if (OtherIdx != Idx) {
1096 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1097 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1098 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1099 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman246b2562007-10-22 18:31:58 +00001100 SCEVHandle NewStart = getMulExpr(F->getStart(),
Chris Lattner53e677a2004-04-02 20:23:17 +00001101 G->getStart());
Dan Gohman246b2562007-10-22 18:31:58 +00001102 SCEVHandle B = F->getStepRecurrence(*this);
1103 SCEVHandle D = G->getStepRecurrence(*this);
1104 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1105 getMulExpr(G, B),
1106 getMulExpr(B, D));
1107 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1108 F->getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00001109 if (Ops.size() == 2) return NewAddRec;
1110
1111 Ops.erase(Ops.begin()+Idx);
1112 Ops.erase(Ops.begin()+OtherIdx-1);
1113 Ops.push_back(NewAddRec);
Dan Gohman246b2562007-10-22 18:31:58 +00001114 return getMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001115 }
1116 }
1117
1118 // Otherwise couldn't fold anything into this recurrence. Move onto the
1119 // next one.
1120 }
1121
1122 // Okay, it looks like we really DO need an mul expr. Check to see if we
1123 // already have one, otherwise create a new one.
1124 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +00001125 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1126 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +00001127 if (Result == 0)
1128 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001129 return Result;
1130}
1131
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001132SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Nick Lewycky48dd6442008-12-02 08:05:48 +00001133 if (LHS == RHS)
1134 return getIntegerSCEV(1, LHS->getType()); // X udiv X --> 1
1135
Chris Lattner53e677a2004-04-02 20:23:17 +00001136 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1137 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky48dd6442008-12-02 08:05:48 +00001138 return LHS; // X udiv 1 --> X
Chris Lattner53e677a2004-04-02 20:23:17 +00001139
1140 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1141 Constant *LHSCV = LHSC->getValue();
1142 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001143 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001144 }
1145 }
1146
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00001147 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1148 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001149 return Result;
1150}
1151
Nick Lewycky48dd6442008-12-02 08:05:48 +00001152SCEVHandle ScalarEvolution::getSDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
1153 if (LHS == RHS)
1154 return getIntegerSCEV(1, LHS->getType()); // X sdiv X --> 1
1155
1156 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1157 if (RHSC->getValue()->equalsInt(1))
1158 return LHS; // X sdiv 1 --> X
1159
1160 if (RHSC->getValue()->isAllOnesValue())
1161 return getNegativeSCEV(LHS); // X sdiv -1 --> -X
1162
1163 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1164 Constant *LHSCV = LHSC->getValue();
1165 Constant *RHSCV = RHSC->getValue();
1166 return getUnknown(ConstantExpr::getSDiv(LHSCV, RHSCV));
1167 }
1168 }
1169
1170 SCEVSDivExpr *&Result = (*SCEVSDivs)[std::make_pair(LHS, RHS)];
1171 if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS);
1172 return Result;
1173}
1174
Chris Lattner53e677a2004-04-02 20:23:17 +00001175
1176/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1177/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001178SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Chris Lattner53e677a2004-04-02 20:23:17 +00001179 const SCEVHandle &Step, const Loop *L) {
1180 std::vector<SCEVHandle> Operands;
1181 Operands.push_back(Start);
1182 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1183 if (StepChrec->getLoop() == L) {
1184 Operands.insert(Operands.end(), StepChrec->op_begin(),
1185 StepChrec->op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00001186 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001187 }
1188
1189 Operands.push_back(Step);
Dan Gohman246b2562007-10-22 18:31:58 +00001190 return getAddRecExpr(Operands, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001191}
1192
1193/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1194/// specified loop. Simplify the expression as much as possible.
Dan Gohman246b2562007-10-22 18:31:58 +00001195SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Chris Lattner53e677a2004-04-02 20:23:17 +00001196 const Loop *L) {
1197 if (Operands.size() == 1) return Operands[0];
1198
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001199 if (Operands.back()->isZero()) {
1200 Operands.pop_back();
Dan Gohman8dae1382008-09-14 17:21:12 +00001201 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohmancfeb6a42008-06-18 16:23:07 +00001202 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001203
Dan Gohmand9cc7492008-08-08 18:33:12 +00001204 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1205 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1206 const Loop* NestedLoop = NestedAR->getLoop();
1207 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1208 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1209 NestedAR->op_end());
1210 SCEVHandle NestedARHandle(NestedAR);
1211 Operands[0] = NestedAR->getStart();
1212 NestedOperands[0] = getAddRecExpr(Operands, L);
1213 return getAddRecExpr(NestedOperands, NestedLoop);
1214 }
1215 }
1216
Chris Lattner53e677a2004-04-02 20:23:17 +00001217 SCEVAddRecExpr *&Result =
Chris Lattnerb3364092006-10-04 21:49:37 +00001218 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1219 Operands.end()))];
Chris Lattner53e677a2004-04-02 20:23:17 +00001220 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1221 return Result;
1222}
1223
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001224SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1225 const SCEVHandle &RHS) {
1226 std::vector<SCEVHandle> Ops;
1227 Ops.push_back(LHS);
1228 Ops.push_back(RHS);
1229 return getSMaxExpr(Ops);
1230}
1231
1232SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1233 assert(!Ops.empty() && "Cannot get empty smax!");
1234 if (Ops.size() == 1) return Ops[0];
1235
1236 // Sort by complexity, this groups all similar expression types together.
1237 GroupByComplexity(Ops);
1238
1239 // If there are any constants, fold them together.
1240 unsigned Idx = 0;
1241 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1242 ++Idx;
1243 assert(Idx < Ops.size());
1244 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1245 // We found two constants, fold them together!
Nick Lewycky3e630762008-02-20 06:48:22 +00001246 ConstantInt *Fold = ConstantInt::get(
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001247 APIntOps::smax(LHSC->getValue()->getValue(),
1248 RHSC->getValue()->getValue()));
Nick Lewycky3e630762008-02-20 06:48:22 +00001249 Ops[0] = getConstant(Fold);
1250 Ops.erase(Ops.begin()+1); // Erase the folded element
1251 if (Ops.size() == 1) return Ops[0];
1252 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001253 }
1254
1255 // If we are left with a constant -inf, strip it off.
1256 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1257 Ops.erase(Ops.begin());
1258 --Idx;
1259 }
1260 }
1261
1262 if (Ops.size() == 1) return Ops[0];
1263
1264 // Find the first SMax
1265 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1266 ++Idx;
1267
1268 // Check to see if one of the operands is an SMax. If so, expand its operands
1269 // onto our operand list, and recurse to simplify.
1270 if (Idx < Ops.size()) {
1271 bool DeletedSMax = false;
1272 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1273 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1274 Ops.erase(Ops.begin()+Idx);
1275 DeletedSMax = true;
1276 }
1277
1278 if (DeletedSMax)
1279 return getSMaxExpr(Ops);
1280 }
1281
1282 // Okay, check to see if the same value occurs in the operand list twice. If
1283 // so, delete one. Since we sorted the list, these values are required to
1284 // be adjacent.
1285 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1286 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1287 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1288 --i; --e;
1289 }
1290
1291 if (Ops.size() == 1) return Ops[0];
1292
1293 assert(!Ops.empty() && "Reduced smax down to nothing!");
1294
Nick Lewycky3e630762008-02-20 06:48:22 +00001295 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001296 // already have one, otherwise create a new one.
1297 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1298 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1299 SCEVOps)];
1300 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1301 return Result;
1302}
1303
Nick Lewycky3e630762008-02-20 06:48:22 +00001304SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1305 const SCEVHandle &RHS) {
1306 std::vector<SCEVHandle> Ops;
1307 Ops.push_back(LHS);
1308 Ops.push_back(RHS);
1309 return getUMaxExpr(Ops);
1310}
1311
1312SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1313 assert(!Ops.empty() && "Cannot get empty umax!");
1314 if (Ops.size() == 1) return Ops[0];
1315
1316 // Sort by complexity, this groups all similar expression types together.
1317 GroupByComplexity(Ops);
1318
1319 // If there are any constants, fold them together.
1320 unsigned Idx = 0;
1321 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1322 ++Idx;
1323 assert(Idx < Ops.size());
1324 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1325 // We found two constants, fold them together!
1326 ConstantInt *Fold = ConstantInt::get(
1327 APIntOps::umax(LHSC->getValue()->getValue(),
1328 RHSC->getValue()->getValue()));
1329 Ops[0] = getConstant(Fold);
1330 Ops.erase(Ops.begin()+1); // Erase the folded element
1331 if (Ops.size() == 1) return Ops[0];
1332 LHSC = cast<SCEVConstant>(Ops[0]);
1333 }
1334
1335 // If we are left with a constant zero, strip it off.
1336 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1337 Ops.erase(Ops.begin());
1338 --Idx;
1339 }
1340 }
1341
1342 if (Ops.size() == 1) return Ops[0];
1343
1344 // Find the first UMax
1345 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1346 ++Idx;
1347
1348 // Check to see if one of the operands is a UMax. If so, expand its operands
1349 // onto our operand list, and recurse to simplify.
1350 if (Idx < Ops.size()) {
1351 bool DeletedUMax = false;
1352 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1353 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1354 Ops.erase(Ops.begin()+Idx);
1355 DeletedUMax = true;
1356 }
1357
1358 if (DeletedUMax)
1359 return getUMaxExpr(Ops);
1360 }
1361
1362 // Okay, check to see if the same value occurs in the operand list twice. If
1363 // so, delete one. Since we sorted the list, these values are required to
1364 // be adjacent.
1365 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1366 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1367 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1368 --i; --e;
1369 }
1370
1371 if (Ops.size() == 1) return Ops[0];
1372
1373 assert(!Ops.empty() && "Reduced umax down to nothing!");
1374
1375 // Okay, it looks like we really DO need a umax expr. Check to see if we
1376 // already have one, otherwise create a new one.
1377 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1378 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1379 SCEVOps)];
1380 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1381 return Result;
1382}
1383
Dan Gohman246b2562007-10-22 18:31:58 +00001384SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001385 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman246b2562007-10-22 18:31:58 +00001386 return getConstant(CI);
Chris Lattnerb3364092006-10-04 21:49:37 +00001387 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001388 if (Result == 0) Result = new SCEVUnknown(V);
1389 return Result;
1390}
1391
Chris Lattner53e677a2004-04-02 20:23:17 +00001392
1393//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001394// ScalarEvolutionsImpl Definition and Implementation
1395//===----------------------------------------------------------------------===//
1396//
1397/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1398/// evolution code.
1399///
1400namespace {
Chris Lattner95255282006-06-28 23:17:24 +00001401 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Dan Gohman246b2562007-10-22 18:31:58 +00001402 /// SE - A reference to the public ScalarEvolution object.
1403 ScalarEvolution &SE;
1404
Chris Lattner53e677a2004-04-02 20:23:17 +00001405 /// F - The function we are analyzing.
1406 ///
1407 Function &F;
1408
1409 /// LI - The loop information for the function we are currently analyzing.
1410 ///
1411 LoopInfo &LI;
1412
1413 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1414 /// things.
1415 SCEVHandle UnknownValue;
1416
1417 /// Scalars - This is a cache of the scalars we have analyzed so far.
1418 ///
1419 std::map<Value*, SCEVHandle> Scalars;
1420
1421 /// IterationCounts - Cache the iteration count of the loops for this
1422 /// function as they are computed.
1423 std::map<const Loop*, SCEVHandle> IterationCounts;
1424
Chris Lattner3221ad02004-04-17 22:58:41 +00001425 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1426 /// the PHI instructions that we attempt to compute constant evolutions for.
1427 /// This allows us to avoid potentially expensive recomputation of these
1428 /// properties. An instruction maps to null if we are unable to compute its
1429 /// exit value.
1430 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001431
Chris Lattner53e677a2004-04-02 20:23:17 +00001432 public:
Dan Gohman246b2562007-10-22 18:31:58 +00001433 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li)
1434 : SE(se), F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
Chris Lattner53e677a2004-04-02 20:23:17 +00001435
1436 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1437 /// expression and create a new one.
1438 SCEVHandle getSCEV(Value *V);
1439
Chris Lattnera0740fb2005-08-09 23:36:33 +00001440 /// hasSCEV - Return true if the SCEV for this value has already been
1441 /// computed.
1442 bool hasSCEV(Value *V) const {
1443 return Scalars.count(V);
1444 }
1445
1446 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1447 /// the specified value.
1448 void setSCEV(Value *V, const SCEVHandle &H) {
1449 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1450 assert(isNew && "This entry already existed!");
Devang Patel89d0a4d2008-11-11 19:17:41 +00001451 isNew = false;
Chris Lattnera0740fb2005-08-09 23:36:33 +00001452 }
1453
1454
Chris Lattner53e677a2004-04-02 20:23:17 +00001455 /// getSCEVAtScope - Compute the value of the specified expression within
1456 /// the indicated loop (which may be null to indicate in no loop). If the
1457 /// expression cannot be evaluated, return UnknownValue itself.
1458 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1459
1460
1461 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1462 /// an analyzable loop-invariant iteration count.
1463 bool hasLoopInvariantIterationCount(const Loop *L);
1464
1465 /// getIterationCount - If the specified loop has a predictable iteration
1466 /// count, return it. Note that it is not valid to call this method on a
1467 /// loop without a loop-invariant iteration count.
1468 SCEVHandle getIterationCount(const Loop *L);
1469
Dan Gohman5cec4db2007-06-19 14:28:31 +00001470 /// deleteValueFromRecords - This method should be called by the
1471 /// client before it removes a value from the program, to make sure
Chris Lattner53e677a2004-04-02 20:23:17 +00001472 /// that no dangling references are left around.
Dan Gohman5cec4db2007-06-19 14:28:31 +00001473 void deleteValueFromRecords(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001474
1475 private:
1476 /// createSCEV - We know that there is no SCEV for the specified value.
1477 /// Analyze the expression.
1478 SCEVHandle createSCEV(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001479
1480 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1481 /// SCEVs.
1482 SCEVHandle createNodeForPHI(PHINode *PN);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001483
1484 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1485 /// for the specified instruction and replaces any references to the
1486 /// symbolic value SymName with the specified value. This is used during
1487 /// PHI resolution.
1488 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1489 const SCEVHandle &SymName,
1490 const SCEVHandle &NewVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00001491
1492 /// ComputeIterationCount - Compute the number of times the specified loop
1493 /// will iterate.
1494 SCEVHandle ComputeIterationCount(const Loop *L);
1495
Chris Lattner673e02b2004-10-12 01:49:27 +00001496 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky6e801dc2007-11-20 08:44:50 +00001497 /// 'icmp op load X, cst', try to see if we can compute the trip count.
Chris Lattner673e02b2004-10-12 01:49:27 +00001498 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1499 Constant *RHS,
1500 const Loop *L,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001501 ICmpInst::Predicate p);
Chris Lattner673e02b2004-10-12 01:49:27 +00001502
Chris Lattner7980fb92004-04-17 18:36:24 +00001503 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1504 /// constant number of times (the condition evolves only from constants),
1505 /// try to evaluate a few iterations of the loop until we get the exit
1506 /// condition gets a value of ExitWhen (true or false). If we cannot
1507 /// evaluate the trip count of the loop, return UnknownValue.
1508 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1509 bool ExitWhen);
1510
Chris Lattner53e677a2004-04-02 20:23:17 +00001511 /// HowFarToZero - Return the number of times a backedge comparing the
1512 /// specified value to zero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001513 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001514 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1515
1516 /// HowFarToNonZero - Return the number of times a backedge checking the
1517 /// specified value for nonzero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001518 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001519 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattner3221ad02004-04-17 22:58:41 +00001520
Chris Lattnerdb25de42005-08-15 23:33:51 +00001521 /// HowManyLessThans - Return the number of times a backedge containing the
1522 /// specified less-than comparison will execute. If not computable, return
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00001523 /// UnknownValue. isSigned specifies whether the less-than is signed.
1524 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
Nick Lewyckydd643f22008-11-18 15:10:54 +00001525 bool isSigned, bool trueWhenEqual);
Chris Lattnerdb25de42005-08-15 23:33:51 +00001526
Dan Gohmanfd6edef2008-09-15 22:18:04 +00001527 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
1528 /// (which may not be an immediate predecessor) which has exactly one
1529 /// successor from which BB is reachable, or null if no such block is
1530 /// found.
1531 BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
1532
Nick Lewycky59cff122008-07-12 07:41:32 +00001533 /// executesAtLeastOnce - Test whether entry to the loop is protected by
1534 /// a conditional between LHS and RHS.
Nick Lewyckydd643f22008-11-18 15:10:54 +00001535 bool executesAtLeastOnce(const Loop *L, bool isSigned, bool trueWhenEqual,
1536 SCEV *LHS, SCEV *RHS);
1537
1538 /// potentialInfiniteLoop - Test whether the loop might jump over the exit value
1539 /// due to wrapping.
1540 bool potentialInfiniteLoop(SCEV *Stride, SCEV *RHS, bool isSigned,
1541 bool trueWhenEqual);
Nick Lewycky59cff122008-07-12 07:41:32 +00001542
Chris Lattner3221ad02004-04-17 22:58:41 +00001543 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1544 /// in the header of its containing loop, we know the loop executes a
1545 /// constant number of times, and the PHI node is just a recurrence
1546 /// involving constants, fold it.
Reid Spencere8019bb2007-03-01 07:25:48 +00001547 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
Chris Lattner3221ad02004-04-17 22:58:41 +00001548 const Loop *L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001549 };
1550}
1551
1552//===----------------------------------------------------------------------===//
1553// Basic SCEV Analysis and PHI Idiom Recognition Code
1554//
1555
Dan Gohman5cec4db2007-06-19 14:28:31 +00001556/// deleteValueFromRecords - This method should be called by the
Chris Lattner53e677a2004-04-02 20:23:17 +00001557/// client before it removes an instruction from the program, to make sure
1558/// that no dangling references are left around.
Dan Gohman5cec4db2007-06-19 14:28:31 +00001559void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1560 SmallVector<Value *, 16> Worklist;
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001561
Dan Gohman5cec4db2007-06-19 14:28:31 +00001562 if (Scalars.erase(V)) {
1563 if (PHINode *PN = dyn_cast<PHINode>(V))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001564 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman5cec4db2007-06-19 14:28:31 +00001565 Worklist.push_back(V);
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001566 }
1567
1568 while (!Worklist.empty()) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001569 Value *VV = Worklist.back();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001570 Worklist.pop_back();
1571
Dan Gohman5cec4db2007-06-19 14:28:31 +00001572 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001573 UI != UE; ++UI) {
Nick Lewycky51e844b2007-06-06 11:26:20 +00001574 Instruction *Inst = cast<Instruction>(*UI);
1575 if (Scalars.erase(Inst)) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001576 if (PHINode *PN = dyn_cast<PHINode>(VV))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001577 ConstantEvolutionLoopExitValue.erase(PN);
1578 Worklist.push_back(Inst);
1579 }
1580 }
1581 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001582}
1583
1584
1585/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1586/// expression and create a new one.
1587SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1588 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1589
1590 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1591 if (I != Scalars.end()) return I->second;
1592 SCEVHandle S = createSCEV(V);
1593 Scalars.insert(std::make_pair(V, S));
1594 return S;
1595}
1596
Chris Lattner4dc534c2005-02-13 04:37:18 +00001597/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1598/// the specified instruction and replaces any references to the symbolic value
1599/// SymName with the specified value. This is used during PHI resolution.
1600void ScalarEvolutionsImpl::
1601ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1602 const SCEVHandle &NewVal) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001603 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001604 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001605
Chris Lattner4dc534c2005-02-13 04:37:18 +00001606 SCEVHandle NV =
Dan Gohman246b2562007-10-22 18:31:58 +00001607 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001608 if (NV == SI->second) return; // No change.
1609
1610 SI->second = NV; // Update the scalars map!
1611
1612 // Any instruction values that use this instruction might also need to be
1613 // updated!
1614 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1615 UI != E; ++UI)
1616 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1617}
Chris Lattner53e677a2004-04-02 20:23:17 +00001618
1619/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1620/// a loop header, making it a potential recurrence, or it doesn't.
1621///
1622SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1623 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1624 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1625 if (L->getHeader() == PN->getParent()) {
1626 // If it lives in the loop header, it has two incoming values, one
1627 // from outside the loop, and one from inside.
1628 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1629 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001630
Chris Lattner53e677a2004-04-02 20:23:17 +00001631 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman246b2562007-10-22 18:31:58 +00001632 SCEVHandle SymbolicName = SE.getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001633 assert(Scalars.find(PN) == Scalars.end() &&
1634 "PHI node already processed?");
1635 Scalars.insert(std::make_pair(PN, SymbolicName));
1636
1637 // Using this symbolic name for the PHI, analyze the value coming around
1638 // the back-edge.
1639 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1640
1641 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1642 // has a special value for the first iteration of the loop.
1643
1644 // If the value coming around the backedge is an add with the symbolic
1645 // value we just inserted, then we found a simple induction variable!
1646 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1647 // If there is a single occurrence of the symbolic value, replace it
1648 // with a recurrence.
1649 unsigned FoundIndex = Add->getNumOperands();
1650 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1651 if (Add->getOperand(i) == SymbolicName)
1652 if (FoundIndex == e) {
1653 FoundIndex = i;
1654 break;
1655 }
1656
1657 if (FoundIndex != Add->getNumOperands()) {
1658 // Create an add with everything but the specified operand.
1659 std::vector<SCEVHandle> Ops;
1660 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1661 if (i != FoundIndex)
1662 Ops.push_back(Add->getOperand(i));
Dan Gohman246b2562007-10-22 18:31:58 +00001663 SCEVHandle Accum = SE.getAddExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001664
1665 // This is not a valid addrec if the step amount is varying each
1666 // loop iteration, but is not itself an addrec in this loop.
1667 if (Accum->isLoopInvariant(L) ||
1668 (isa<SCEVAddRecExpr>(Accum) &&
1669 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1670 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohman246b2562007-10-22 18:31:58 +00001671 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001672
1673 // Okay, for the entire analysis of this edge we assumed the PHI
1674 // to be symbolic. We now need to go back and update all of the
1675 // entries for the scalars that use the PHI (except for the PHI
1676 // itself) to use the new analyzed value instead of the "symbolic"
1677 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001678 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001679 return PHISCEV;
1680 }
1681 }
Chris Lattner97156e72006-04-26 18:34:07 +00001682 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1683 // Otherwise, this could be a loop like this:
1684 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1685 // In this case, j = {1,+,1} and BEValue is j.
1686 // Because the other in-value of i (0) fits the evolution of BEValue
1687 // i really is an addrec evolution.
1688 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1689 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1690
1691 // If StartVal = j.start - j.stride, we can use StartVal as the
1692 // initial step of the addrec evolution.
Dan Gohman246b2562007-10-22 18:31:58 +00001693 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1694 AddRec->getOperand(1))) {
Chris Lattner97156e72006-04-26 18:34:07 +00001695 SCEVHandle PHISCEV =
Dan Gohman246b2562007-10-22 18:31:58 +00001696 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Chris Lattner97156e72006-04-26 18:34:07 +00001697
1698 // Okay, for the entire analysis of this edge we assumed the PHI
1699 // to be symbolic. We now need to go back and update all of the
1700 // entries for the scalars that use the PHI (except for the PHI
1701 // itself) to use the new analyzed value instead of the "symbolic"
1702 // value.
1703 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1704 return PHISCEV;
1705 }
1706 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001707 }
1708
1709 return SymbolicName;
1710 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001711
Chris Lattner53e677a2004-04-02 20:23:17 +00001712 // If it's not a loop phi, we can't handle it yet.
Dan Gohman246b2562007-10-22 18:31:58 +00001713 return SE.getUnknown(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001714}
1715
Nick Lewycky83bb0052007-11-22 07:59:40 +00001716/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1717/// guaranteed to end in (at every loop iteration). It is, at the same time,
1718/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1719/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1720static uint32_t GetMinTrailingZeros(SCEVHandle S) {
1721 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner8314a0c2007-11-23 22:36:49 +00001722 return C->getValue()->getValue().countTrailingZeros();
Chris Lattnera17f0392006-12-12 02:26:09 +00001723
Nick Lewycky6e801dc2007-11-20 08:44:50 +00001724 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Nick Lewycky83bb0052007-11-22 07:59:40 +00001725 return std::min(GetMinTrailingZeros(T->getOperand()), T->getBitWidth());
1726
1727 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1728 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1729 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1730 }
1731
1732 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1733 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1734 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1735 }
1736
Chris Lattnera17f0392006-12-12 02:26:09 +00001737 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001738 // The result is the min of all operands results.
1739 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1740 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1741 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1742 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001743 }
1744
1745 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001746 // The result is the sum of all operands results.
1747 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
1748 uint32_t BitWidth = M->getBitWidth();
1749 for (unsigned i = 1, e = M->getNumOperands();
1750 SumOpRes != BitWidth && i != e; ++i)
1751 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
1752 BitWidth);
1753 return SumOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001754 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001755
Chris Lattnera17f0392006-12-12 02:26:09 +00001756 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky83bb0052007-11-22 07:59:40 +00001757 // The result is the min of all operands results.
1758 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1759 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1760 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1761 return MinOpRes;
Chris Lattnera17f0392006-12-12 02:26:09 +00001762 }
Nick Lewycky83bb0052007-11-22 07:59:40 +00001763
Nick Lewyckyc54c5612007-11-25 22:41:31 +00001764 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1765 // The result is the min of all operands results.
1766 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1767 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1768 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1769 return MinOpRes;
1770 }
1771
Nick Lewycky3e630762008-02-20 06:48:22 +00001772 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1773 // The result is the min of all operands results.
1774 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1775 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1776 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1777 return MinOpRes;
1778 }
1779
Nick Lewycky48dd6442008-12-02 08:05:48 +00001780 // SCEVUDivExpr, SCEVSDivExpr, SCEVUnknown
Nick Lewycky83bb0052007-11-22 07:59:40 +00001781 return 0;
Chris Lattnera17f0392006-12-12 02:26:09 +00001782}
Chris Lattner53e677a2004-04-02 20:23:17 +00001783
1784/// createSCEV - We know that there is no SCEV for the specified value.
1785/// Analyze the expression.
1786///
1787SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
Chris Lattner42b5e082007-11-23 08:46:22 +00001788 if (!isa<IntegerType>(V->getType()))
1789 return SE.getUnknown(V);
1790
Dan Gohman6c459a22008-06-22 19:56:46 +00001791 unsigned Opcode = Instruction::UserOp1;
1792 if (Instruction *I = dyn_cast<Instruction>(V))
1793 Opcode = I->getOpcode();
1794 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1795 Opcode = CE->getOpcode();
1796 else
1797 return SE.getUnknown(V);
Chris Lattner2811f2a2007-04-02 05:41:38 +00001798
Dan Gohman6c459a22008-06-22 19:56:46 +00001799 User *U = cast<User>(V);
1800 switch (Opcode) {
1801 case Instruction::Add:
1802 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1803 getSCEV(U->getOperand(1)));
1804 case Instruction::Mul:
1805 return SE.getMulExpr(getSCEV(U->getOperand(0)),
1806 getSCEV(U->getOperand(1)));
1807 case Instruction::UDiv:
1808 return SE.getUDivExpr(getSCEV(U->getOperand(0)),
1809 getSCEV(U->getOperand(1)));
Nick Lewycky48dd6442008-12-02 08:05:48 +00001810 case Instruction::SDiv:
1811 return SE.getSDivExpr(getSCEV(U->getOperand(0)),
1812 getSCEV(U->getOperand(1)));
Dan Gohman6c459a22008-06-22 19:56:46 +00001813 case Instruction::Sub:
1814 return SE.getMinusSCEV(getSCEV(U->getOperand(0)),
1815 getSCEV(U->getOperand(1)));
1816 case Instruction::Or:
1817 // If the RHS of the Or is a constant, we may have something like:
1818 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1819 // optimizations will transparently handle this case.
1820 //
1821 // In order for this transformation to be safe, the LHS must be of the
1822 // form X*(2^n) and the Or constant must be less than 2^n.
1823 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1824 SCEVHandle LHS = getSCEV(U->getOperand(0));
1825 const APInt &CIVal = CI->getValue();
1826 if (GetMinTrailingZeros(LHS) >=
1827 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1828 return SE.getAddExpr(LHS, getSCEV(U->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001829 }
Dan Gohman6c459a22008-06-22 19:56:46 +00001830 break;
1831 case Instruction::Xor:
Dan Gohman6c459a22008-06-22 19:56:46 +00001832 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky01eaf802008-07-07 06:15:49 +00001833 // If the RHS of the xor is a signbit, then this is just an add.
1834 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman6c459a22008-06-22 19:56:46 +00001835 if (CI->getValue().isSignBit())
1836 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1837 getSCEV(U->getOperand(1)));
Nick Lewycky01eaf802008-07-07 06:15:49 +00001838
1839 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman6c459a22008-06-22 19:56:46 +00001840 else if (CI->isAllOnesValue())
1841 return SE.getNotSCEV(getSCEV(U->getOperand(0)));
1842 }
1843 break;
1844
1845 case Instruction::Shl:
1846 // Turn shift left of a constant amount into a multiply.
1847 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1848 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1849 Constant *X = ConstantInt::get(
1850 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1851 return SE.getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1852 }
1853 break;
1854
Nick Lewycky01eaf802008-07-07 06:15:49 +00001855 case Instruction::LShr:
Nick Lewycky48dd6442008-12-02 08:05:48 +00001856 // Turn logical shift right of a constant into an unsigned divide.
Nick Lewycky01eaf802008-07-07 06:15:49 +00001857 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1858 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1859 Constant *X = ConstantInt::get(
1860 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1861 return SE.getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1862 }
1863 break;
1864
Dan Gohman6c459a22008-06-22 19:56:46 +00001865 case Instruction::Trunc:
1866 return SE.getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
1867
1868 case Instruction::ZExt:
1869 return SE.getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1870
1871 case Instruction::SExt:
1872 return SE.getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1873
1874 case Instruction::BitCast:
1875 // BitCasts are no-op casts so we just eliminate the cast.
1876 if (U->getType()->isInteger() &&
1877 U->getOperand(0)->getType()->isInteger())
1878 return getSCEV(U->getOperand(0));
1879 break;
1880
1881 case Instruction::PHI:
1882 return createNodeForPHI(cast<PHINode>(U));
1883
1884 case Instruction::Select:
1885 // This could be a smax or umax that was lowered earlier.
1886 // Try to recover it.
1887 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
1888 Value *LHS = ICI->getOperand(0);
1889 Value *RHS = ICI->getOperand(1);
1890 switch (ICI->getPredicate()) {
1891 case ICmpInst::ICMP_SLT:
1892 case ICmpInst::ICMP_SLE:
1893 std::swap(LHS, RHS);
1894 // fall through
1895 case ICmpInst::ICMP_SGT:
1896 case ICmpInst::ICMP_SGE:
1897 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1898 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
1899 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman1fbffe02008-07-30 04:36:32 +00001900 // ~smax(~x, ~y) == smin(x, y).
1901 return SE.getNotSCEV(SE.getSMaxExpr(
1902 SE.getNotSCEV(getSCEV(LHS)),
1903 SE.getNotSCEV(getSCEV(RHS))));
Dan Gohman6c459a22008-06-22 19:56:46 +00001904 break;
1905 case ICmpInst::ICMP_ULT:
1906 case ICmpInst::ICMP_ULE:
1907 std::swap(LHS, RHS);
1908 // fall through
1909 case ICmpInst::ICMP_UGT:
1910 case ICmpInst::ICMP_UGE:
1911 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1912 return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
1913 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
1914 // ~umax(~x, ~y) == umin(x, y)
1915 return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)),
1916 SE.getNotSCEV(getSCEV(RHS))));
1917 break;
1918 default:
1919 break;
1920 }
1921 }
1922
1923 default: // We cannot analyze this expression.
1924 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001925 }
1926
Dan Gohman246b2562007-10-22 18:31:58 +00001927 return SE.getUnknown(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001928}
1929
1930
1931
1932//===----------------------------------------------------------------------===//
1933// Iteration Count Computation Code
1934//
1935
1936/// getIterationCount - If the specified loop has a predictable iteration
1937/// count, return it. Note that it is not valid to call this method on a
1938/// loop without a loop-invariant iteration count.
1939SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1940 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1941 if (I == IterationCounts.end()) {
1942 SCEVHandle ItCount = ComputeIterationCount(L);
1943 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1944 if (ItCount != UnknownValue) {
1945 assert(ItCount->isLoopInvariant(L) &&
1946 "Computed trip count isn't loop invariant for loop!");
1947 ++NumTripCountsComputed;
1948 } else if (isa<PHINode>(L->getHeader()->begin())) {
1949 // Only count loops that have phi nodes as not being computable.
1950 ++NumTripCountsNotComputed;
1951 }
1952 }
1953 return I->second;
1954}
1955
1956/// ComputeIterationCount - Compute the number of times the specified loop
1957/// will iterate.
1958SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1959 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patelb7211a22007-08-21 00:31:24 +00001960 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001961 L->getExitBlocks(ExitBlocks);
1962 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001963
1964 // Okay, there is one exit block. Try to find the condition that causes the
1965 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001966 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001967
1968 BasicBlock *ExitingBlock = 0;
1969 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1970 PI != E; ++PI)
1971 if (L->contains(*PI)) {
1972 if (ExitingBlock == 0)
1973 ExitingBlock = *PI;
1974 else
1975 return UnknownValue; // More than one block exiting!
1976 }
1977 assert(ExitingBlock && "No exits from loop, something is broken!");
1978
1979 // Okay, we've computed the exiting block. See what condition causes us to
1980 // exit.
1981 //
1982 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00001983 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1984 if (ExitBr == 0) return UnknownValue;
1985 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Chris Lattner8b0e3602007-01-07 02:24:26 +00001986
1987 // At this point, we know we have a conditional branch that determines whether
1988 // the loop is exited. However, we don't know if the branch is executed each
1989 // time through the loop. If not, then the execution count of the branch will
1990 // not be equal to the trip count of the loop.
1991 //
1992 // Currently we check for this by checking to see if the Exit branch goes to
1993 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00001994 // times as the loop. We also handle the case where the exit block *is* the
1995 // loop header. This is common for un-rotated loops. More extensive analysis
1996 // could be done to handle more cases here.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001997 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00001998 ExitBr->getSuccessor(1) != L->getHeader() &&
1999 ExitBr->getParent() != L->getHeader())
Chris Lattner8b0e3602007-01-07 02:24:26 +00002000 return UnknownValue;
2001
Reid Spencere4d87aa2006-12-23 06:05:41 +00002002 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2003
Nick Lewycky3b711652008-02-21 08:34:02 +00002004 // If it's not an integer comparison then compute it the hard way.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002005 // Note that ICmpInst deals with pointer comparisons too so we must check
2006 // the type of the operand.
Chris Lattner8b0e3602007-01-07 02:24:26 +00002007 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Chris Lattner7980fb92004-04-17 18:36:24 +00002008 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
2009 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00002010
Reid Spencere4d87aa2006-12-23 06:05:41 +00002011 // If the condition was exit on true, convert the condition to exit on false
2012 ICmpInst::Predicate Cond;
Chris Lattner673e02b2004-10-12 01:49:27 +00002013 if (ExitBr->getSuccessor(1) == ExitBlock)
Reid Spencere4d87aa2006-12-23 06:05:41 +00002014 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00002015 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00002016 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00002017
2018 // Handle common loops like: for (X = "string"; *X; ++X)
2019 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2020 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2021 SCEVHandle ItCnt =
2022 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
2023 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2024 }
2025
Chris Lattner53e677a2004-04-02 20:23:17 +00002026 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2027 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2028
2029 // Try to evaluate any dependencies out of the loop.
2030 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2031 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2032 Tmp = getSCEVAtScope(RHS, L);
2033 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2034
Reid Spencere4d87aa2006-12-23 06:05:41 +00002035 // At this point, we would like to compute how many iterations of the
2036 // loop the predicate will return true for these inputs.
Dan Gohman70ff4cf2008-09-16 18:52:57 +00002037 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2038 // If there is a loop-invariant, force it into the RHS.
Chris Lattner53e677a2004-04-02 20:23:17 +00002039 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002040 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00002041 }
2042
2043 // FIXME: think about handling pointer comparisons! i.e.:
2044 // while (P != P+100) ++P;
2045
2046 // If we have a comparison of a chrec against a constant, try to use value
2047 // ranges to answer this query.
2048 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2049 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2050 if (AddRec->getLoop() == L) {
2051 // Form the comparison range using the constant of the correct type so
2052 // that the ConstantRange class knows to do a signed or unsigned
2053 // comparison.
2054 ConstantInt *CompVal = RHSC->getValue();
2055 const Type *RealTy = ExitCond->getOperand(0)->getType();
Reid Spencer4da49122006-12-12 05:05:00 +00002056 CompVal = dyn_cast<ConstantInt>(
Reid Spencerb6ba3e62006-12-12 09:17:50 +00002057 ConstantExpr::getBitCast(CompVal, RealTy));
Chris Lattner53e677a2004-04-02 20:23:17 +00002058 if (CompVal) {
2059 // Form the constant range.
Reid Spencerc6aedf72007-02-28 22:03:51 +00002060 ConstantRange CompRange(
2061 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002062
Dan Gohman246b2562007-10-22 18:31:58 +00002063 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002064 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2065 }
2066 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002067
Chris Lattner53e677a2004-04-02 20:23:17 +00002068 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002069 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00002070 // Convert to: while (X-Y != 0)
Dan Gohman246b2562007-10-22 18:31:58 +00002071 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002072 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002073 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002074 }
2075 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00002076 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman246b2562007-10-22 18:31:58 +00002077 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002078 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00002079 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002080 }
2081 case ICmpInst::ICMP_SLT: {
Nick Lewyckydd643f22008-11-18 15:10:54 +00002082 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002083 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002084 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002085 }
2086 case ICmpInst::ICMP_SGT: {
Eli Friedman068acc32008-07-30 00:04:08 +00002087 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewyckydd643f22008-11-18 15:10:54 +00002088 SE.getNotSCEV(RHS), L, true, false);
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002089 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2090 break;
2091 }
2092 case ICmpInst::ICMP_ULT: {
Nick Lewyckydd643f22008-11-18 15:10:54 +00002093 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false, false);
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002094 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2095 break;
2096 }
2097 case ICmpInst::ICMP_UGT: {
Dale Johannesena0c8fc62008-04-20 16:58:57 +00002098 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewyckydd643f22008-11-18 15:10:54 +00002099 SE.getNotSCEV(RHS), L, false, false);
2100 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2101 break;
2102 }
2103 case ICmpInst::ICMP_SLE: {
2104 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true, true);
2105 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2106 break;
2107 }
2108 case ICmpInst::ICMP_SGE: {
2109 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2110 SE.getNotSCEV(RHS), L, true, true);
2111 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2112 break;
2113 }
2114 case ICmpInst::ICMP_ULE: {
2115 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false, true);
2116 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2117 break;
2118 }
2119 case ICmpInst::ICMP_UGE: {
2120 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2121 SE.getNotSCEV(RHS), L, false, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002122 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002123 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002124 }
Chris Lattner53e677a2004-04-02 20:23:17 +00002125 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002126#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002127 cerr << "ComputeIterationCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002128 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Bill Wendlinge8156192006-12-07 01:30:32 +00002129 cerr << "[unsigned] ";
2130 cerr << *LHS << " "
Reid Spencere4d87aa2006-12-23 06:05:41 +00002131 << Instruction::getOpcodeName(Instruction::ICmp)
2132 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002133#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00002134 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00002135 }
Chris Lattner7980fb92004-04-17 18:36:24 +00002136 return ComputeIterationCountExhaustively(L, ExitCond,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002137 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner7980fb92004-04-17 18:36:24 +00002138}
2139
Chris Lattner673e02b2004-10-12 01:49:27 +00002140static ConstantInt *
Dan Gohman246b2562007-10-22 18:31:58 +00002141EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2142 ScalarEvolution &SE) {
2143 SCEVHandle InVal = SE.getConstant(C);
2144 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00002145 assert(isa<SCEVConstant>(Val) &&
2146 "Evaluation of SCEV at constant didn't fold correctly?");
2147 return cast<SCEVConstant>(Val)->getValue();
2148}
2149
2150/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2151/// and a GEP expression (missing the pointer index) indexing into it, return
2152/// the addressed element of the initializer or null if the index expression is
2153/// invalid.
2154static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002155GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00002156 const std::vector<ConstantInt*> &Indices) {
2157 Constant *Init = GV->getInitializer();
2158 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002159 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00002160 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2161 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2162 Init = cast<Constant>(CS->getOperand(Idx));
2163 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2164 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2165 Init = cast<Constant>(CA->getOperand(Idx));
2166 } else if (isa<ConstantAggregateZero>(Init)) {
2167 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2168 assert(Idx < STy->getNumElements() && "Bad struct index!");
2169 Init = Constant::getNullValue(STy->getElementType(Idx));
2170 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2171 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2172 Init = Constant::getNullValue(ATy->getElementType());
2173 } else {
2174 assert(0 && "Unknown constant aggregate type!");
2175 }
2176 return 0;
2177 } else {
2178 return 0; // Unknown initializer type
2179 }
2180 }
2181 return Init;
2182}
2183
2184/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky08de6132008-05-06 04:03:18 +00002185/// 'icmp op load X, cst', try to see if we can compute the trip count.
Chris Lattner673e02b2004-10-12 01:49:27 +00002186SCEVHandle ScalarEvolutionsImpl::
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002187ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002188 const Loop *L,
2189 ICmpInst::Predicate predicate) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002190 if (LI->isVolatile()) return UnknownValue;
2191
2192 // Check to see if the loaded pointer is a getelementptr of a global.
2193 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2194 if (!GEP) return UnknownValue;
2195
2196 // Make sure that it is really a constant global we are gepping, with an
2197 // initializer, and make sure the first IDX is really 0.
2198 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2199 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2200 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2201 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2202 return UnknownValue;
2203
2204 // Okay, we allow one non-constant index into the GEP instruction.
2205 Value *VarIdx = 0;
2206 std::vector<ConstantInt*> Indexes;
2207 unsigned VarIdxNum = 0;
2208 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2209 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2210 Indexes.push_back(CI);
2211 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2212 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2213 VarIdx = GEP->getOperand(i);
2214 VarIdxNum = i-2;
2215 Indexes.push_back(0);
2216 }
2217
2218 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2219 // Check to see if X is a loop variant variable value now.
2220 SCEVHandle Idx = getSCEV(VarIdx);
2221 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2222 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2223
2224 // We can only recognize very limited forms of loop index expressions, in
2225 // particular, only affine AddRec's like {C1,+,C2}.
2226 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2227 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2228 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2229 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2230 return UnknownValue;
2231
2232 unsigned MaxSteps = MaxBruteForceIterations;
2233 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002234 ConstantInt *ItCst =
Reid Spencerc5b206b2006-12-31 05:48:39 +00002235 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohman246b2562007-10-22 18:31:58 +00002236 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
Chris Lattner673e02b2004-10-12 01:49:27 +00002237
2238 // Form the GEP offset.
2239 Indexes[VarIdxNum] = Val;
2240
2241 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2242 if (Result == 0) break; // Cannot compute!
2243
2244 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002245 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002246 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00002247 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00002248#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002249 cerr << "\n***\n*** Computed loop count " << *ItCst
2250 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2251 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00002252#endif
2253 ++NumArrayLenItCounts;
Dan Gohman246b2562007-10-22 18:31:58 +00002254 return SE.getConstant(ItCst); // Found terminating iteration!
Chris Lattner673e02b2004-10-12 01:49:27 +00002255 }
2256 }
2257 return UnknownValue;
2258}
2259
2260
Chris Lattner3221ad02004-04-17 22:58:41 +00002261/// CanConstantFold - Return true if we can constant fold an instruction of the
2262/// specified type, assuming that all operands were constants.
2263static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00002264 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00002265 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2266 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002267
Chris Lattner3221ad02004-04-17 22:58:41 +00002268 if (const CallInst *CI = dyn_cast<CallInst>(I))
2269 if (const Function *F = CI->getCalledFunction())
Dan Gohmanfa9b80e2008-01-31 01:05:10 +00002270 return canConstantFoldCallTo(F);
Chris Lattner3221ad02004-04-17 22:58:41 +00002271 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00002272}
2273
Chris Lattner3221ad02004-04-17 22:58:41 +00002274/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2275/// in the loop that V is derived from. We allow arbitrary operations along the
2276/// way, but the operands of an operation must either be constants or a value
2277/// derived from a constant PHI. If this expression does not fit with these
2278/// constraints, return null.
2279static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2280 // If this is not an instruction, or if this is an instruction outside of the
2281 // loop, it can't be derived from a loop PHI.
2282 Instruction *I = dyn_cast<Instruction>(V);
2283 if (I == 0 || !L->contains(I->getParent())) return 0;
2284
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002285 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002286 if (L->getHeader() == I->getParent())
2287 return PN;
2288 else
2289 // We don't currently keep track of the control flow needed to evaluate
2290 // PHIs, so we cannot handle PHIs inside of loops.
2291 return 0;
Anton Korobeynikovae9f3a32008-02-20 11:08:44 +00002292 }
Chris Lattner3221ad02004-04-17 22:58:41 +00002293
2294 // If we won't be able to constant fold this expression even if the operands
2295 // are constants, return early.
2296 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002297
Chris Lattner3221ad02004-04-17 22:58:41 +00002298 // Otherwise, we can evaluate this instruction if all of its operands are
2299 // constant or derived from a PHI node themselves.
2300 PHINode *PHI = 0;
2301 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2302 if (!(isa<Constant>(I->getOperand(Op)) ||
2303 isa<GlobalValue>(I->getOperand(Op)))) {
2304 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2305 if (P == 0) return 0; // Not evolving from PHI
2306 if (PHI == 0)
2307 PHI = P;
2308 else if (PHI != P)
2309 return 0; // Evolving from multiple different PHIs.
2310 }
2311
2312 // This is a expression evolving from a constant PHI!
2313 return PHI;
2314}
2315
2316/// EvaluateExpression - Given an expression that passes the
2317/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2318/// in the loop has the value PHIVal. If we can't fold this expression for some
2319/// reason, return null.
2320static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2321 if (isa<PHINode>(V)) return PHIVal;
Reid Spencere8404342004-07-18 00:18:30 +00002322 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00002323 Instruction *I = cast<Instruction>(V);
2324
2325 std::vector<Constant*> Operands;
2326 Operands.resize(I->getNumOperands());
2327
2328 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2329 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2330 if (Operands[i] == 0) return 0;
2331 }
2332
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002333 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2334 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2335 &Operands[0], Operands.size());
2336 else
2337 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2338 &Operands[0], Operands.size());
Chris Lattner3221ad02004-04-17 22:58:41 +00002339}
2340
2341/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2342/// in the header of its containing loop, we know the loop executes a
2343/// constant number of times, and the PHI node is just a recurrence
2344/// involving constants, fold it.
2345Constant *ScalarEvolutionsImpl::
Reid Spencere8019bb2007-03-01 07:25:48 +00002346getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
Chris Lattner3221ad02004-04-17 22:58:41 +00002347 std::map<PHINode*, Constant*>::iterator I =
2348 ConstantEvolutionLoopExitValue.find(PN);
2349 if (I != ConstantEvolutionLoopExitValue.end())
2350 return I->second;
2351
Reid Spencere8019bb2007-03-01 07:25:48 +00002352 if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00002353 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2354
2355 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2356
2357 // Since the loop is canonicalized, the PHI node must have two entries. One
2358 // entry must be a constant (coming in from outside of the loop), and the
2359 // second must be derived from the same PHI.
2360 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2361 Constant *StartCST =
2362 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2363 if (StartCST == 0)
2364 return RetVal = 0; // Must be a constant.
2365
2366 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2367 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2368 if (PN2 != PN)
2369 return RetVal = 0; // Not derived from same PHI.
2370
2371 // Execute the loop symbolically to determine the exit value.
Reid Spencere8019bb2007-03-01 07:25:48 +00002372 if (Its.getActiveBits() >= 32)
2373 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00002374
Reid Spencere8019bb2007-03-01 07:25:48 +00002375 unsigned NumIterations = Its.getZExtValue(); // must be in range
2376 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00002377 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2378 if (IterationNum == NumIterations)
2379 return RetVal = PHIVal; // Got exit value!
2380
2381 // Compute the value of the PHI node for the next iteration.
2382 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2383 if (NextPHI == PHIVal)
2384 return RetVal = NextPHI; // Stopped evolving!
2385 if (NextPHI == 0)
2386 return 0; // Couldn't evaluate!
2387 PHIVal = NextPHI;
2388 }
2389}
2390
Chris Lattner7980fb92004-04-17 18:36:24 +00002391/// ComputeIterationCountExhaustively - If the trip is known to execute a
2392/// constant number of times (the condition evolves only from constants),
2393/// try to evaluate a few iterations of the loop until we get the exit
2394/// condition gets a value of ExitWhen (true or false). If we cannot
2395/// evaluate the trip count of the loop, return UnknownValue.
2396SCEVHandle ScalarEvolutionsImpl::
2397ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2398 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2399 if (PN == 0) return UnknownValue;
2400
2401 // Since the loop is canonicalized, the PHI node must have two entries. One
2402 // entry must be a constant (coming in from outside of the loop), and the
2403 // second must be derived from the same PHI.
2404 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2405 Constant *StartCST =
2406 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2407 if (StartCST == 0) return UnknownValue; // Must be a constant.
2408
2409 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2410 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2411 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2412
2413 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2414 // the loop symbolically to determine when the condition gets a value of
2415 // "ExitWhen".
2416 unsigned IterationNum = 0;
2417 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2418 for (Constant *PHIVal = StartCST;
2419 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002420 ConstantInt *CondVal =
2421 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00002422
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002423 // Couldn't symbolically evaluate.
Chris Lattneref3baf02007-01-12 18:28:58 +00002424 if (!CondVal) return UnknownValue;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002425
Reid Spencere8019bb2007-03-01 07:25:48 +00002426 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002427 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00002428 ++NumBruteForceTripCountsComputed;
Dan Gohman246b2562007-10-22 18:31:58 +00002429 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00002430 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002431
Chris Lattner3221ad02004-04-17 22:58:41 +00002432 // Compute the value of the PHI node for the next iteration.
2433 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2434 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00002435 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00002436 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00002437 }
2438
2439 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00002440 return UnknownValue;
2441}
2442
2443/// getSCEVAtScope - Compute the value of the specified expression within the
2444/// indicated loop (which may be null to indicate in no loop). If the
2445/// expression cannot be evaluated, return UnknownValue.
2446SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2447 // FIXME: this should be turned into a virtual method on SCEV!
2448
Chris Lattner3221ad02004-04-17 22:58:41 +00002449 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002450
Nick Lewycky3e630762008-02-20 06:48:22 +00002451 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattner3221ad02004-04-17 22:58:41 +00002452 // exit value from the loop without using SCEVs.
2453 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2454 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2455 const Loop *LI = this->LI[I->getParent()];
2456 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2457 if (PHINode *PN = dyn_cast<PHINode>(I))
2458 if (PN->getParent() == LI->getHeader()) {
2459 // Okay, there is no closed form solution for the PHI node. Check
2460 // to see if the loop that contains it has a known iteration count.
2461 // If so, we may be able to force computation of the exit value.
2462 SCEVHandle IterationCount = getIterationCount(LI);
2463 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2464 // Okay, we know how many times the containing loop executes. If
2465 // this is a constant evolving PHI node, get the final value at
2466 // the specified iteration number.
2467 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Reid Spencere8019bb2007-03-01 07:25:48 +00002468 ICC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00002469 LI);
Dan Gohman246b2562007-10-22 18:31:58 +00002470 if (RV) return SE.getUnknown(RV);
Chris Lattner3221ad02004-04-17 22:58:41 +00002471 }
2472 }
2473
Reid Spencer09906f32006-12-04 21:33:23 +00002474 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00002475 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00002476 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00002477 // result. This is particularly useful for computing loop exit values.
2478 if (CanConstantFold(I)) {
2479 std::vector<Constant*> Operands;
2480 Operands.reserve(I->getNumOperands());
2481 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2482 Value *Op = I->getOperand(i);
2483 if (Constant *C = dyn_cast<Constant>(Op)) {
2484 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002485 } else {
Chris Lattner42b5e082007-11-23 08:46:22 +00002486 // If any of the operands is non-constant and if they are
2487 // non-integer, don't even try to analyze them with scev techniques.
2488 if (!isa<IntegerType>(Op->getType()))
2489 return V;
2490
Chris Lattner3221ad02004-04-17 22:58:41 +00002491 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2492 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
Reid Spencerd977d862006-12-12 23:36:14 +00002493 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2494 Op->getType(),
2495 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002496 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2497 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
Reid Spencerd977d862006-12-12 23:36:14 +00002498 Operands.push_back(ConstantExpr::getIntegerCast(C,
2499 Op->getType(),
2500 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002501 else
2502 return V;
2503 } else {
2504 return V;
2505 }
2506 }
2507 }
Chris Lattnerf286f6f2007-12-10 22:53:04 +00002508
2509 Constant *C;
2510 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2511 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2512 &Operands[0], Operands.size());
2513 else
2514 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2515 &Operands[0], Operands.size());
Dan Gohman246b2562007-10-22 18:31:58 +00002516 return SE.getUnknown(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002517 }
2518 }
2519
2520 // This is some other type of SCEVUnknown, just return it.
2521 return V;
2522 }
2523
Chris Lattner53e677a2004-04-02 20:23:17 +00002524 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2525 // Avoid performing the look-up in the common case where the specified
2526 // expression has no loop-variant portions.
2527 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2528 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2529 if (OpAtScope != Comm->getOperand(i)) {
2530 if (OpAtScope == UnknownValue) return UnknownValue;
2531 // Okay, at least one of these operands is loop variant but might be
2532 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00002533 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00002534 NewOps.push_back(OpAtScope);
2535
2536 for (++i; i != e; ++i) {
2537 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2538 if (OpAtScope == UnknownValue) return UnknownValue;
2539 NewOps.push_back(OpAtScope);
2540 }
2541 if (isa<SCEVAddExpr>(Comm))
Dan Gohman246b2562007-10-22 18:31:58 +00002542 return SE.getAddExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002543 if (isa<SCEVMulExpr>(Comm))
2544 return SE.getMulExpr(NewOps);
2545 if (isa<SCEVSMaxExpr>(Comm))
2546 return SE.getSMaxExpr(NewOps);
Nick Lewycky3e630762008-02-20 06:48:22 +00002547 if (isa<SCEVUMaxExpr>(Comm))
2548 return SE.getUMaxExpr(NewOps);
Nick Lewyckyc54c5612007-11-25 22:41:31 +00002549 assert(0 && "Unknown commutative SCEV type!");
Chris Lattner53e677a2004-04-02 20:23:17 +00002550 }
2551 }
2552 // If we got here, all operands are loop invariant.
2553 return Comm;
2554 }
2555
Nick Lewycky48dd6442008-12-02 08:05:48 +00002556 if (SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(V)) {
2557 SCEVHandle LHS = getSCEVAtScope(UDiv->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002558 if (LHS == UnknownValue) return LHS;
Nick Lewycky48dd6442008-12-02 08:05:48 +00002559 SCEVHandle RHS = getSCEVAtScope(UDiv->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002560 if (RHS == UnknownValue) return RHS;
Nick Lewycky48dd6442008-12-02 08:05:48 +00002561 if (LHS == UDiv->getLHS() && RHS == UDiv->getRHS())
2562 return UDiv; // must be loop invariant
Wojciech Matyjewicze3320a12008-02-11 11:03:14 +00002563 return SE.getUDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00002564 }
2565
Nick Lewycky48dd6442008-12-02 08:05:48 +00002566 if (SCEVSDivExpr *SDiv = dyn_cast<SCEVSDivExpr>(V)) {
2567 SCEVHandle LHS = getSCEVAtScope(SDiv->getLHS(), L);
2568 if (LHS == UnknownValue) return LHS;
2569 SCEVHandle RHS = getSCEVAtScope(SDiv->getRHS(), L);
2570 if (RHS == UnknownValue) return RHS;
2571 if (LHS == SDiv->getLHS() && RHS == SDiv->getRHS())
2572 return SDiv; // must be loop invariant
2573 return SE.getSDivExpr(LHS, RHS);
2574 }
2575
Chris Lattner53e677a2004-04-02 20:23:17 +00002576 // If this is a loop recurrence for a loop that does not contain L, then we
2577 // are dealing with the final value computed by the loop.
2578 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2579 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2580 // To evaluate this recurrence, we need to know how many times the AddRec
2581 // loop iterates. Compute this now.
2582 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2583 if (IterationCount == UnknownValue) return UnknownValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002584
Eli Friedmanb42a6262008-08-04 23:49:06 +00002585 // Then, evaluate the AddRec.
Dan Gohman246b2562007-10-22 18:31:58 +00002586 return AddRec->evaluateAtIteration(IterationCount, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002587 }
2588 return UnknownValue;
2589 }
2590
2591 //assert(0 && "Unknown SCEV type!");
2592 return UnknownValue;
2593}
2594
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002595/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2596/// following equation:
2597///
2598/// A * X = B (mod N)
2599///
2600/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2601/// A and B isn't important.
2602///
2603/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2604static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2605 ScalarEvolution &SE) {
2606 uint32_t BW = A.getBitWidth();
2607 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2608 assert(A != 0 && "A must be non-zero.");
2609
2610 // 1. D = gcd(A, N)
2611 //
2612 // The gcd of A and N may have only one prime factor: 2. The number of
2613 // trailing zeros in A is its multiplicity
2614 uint32_t Mult2 = A.countTrailingZeros();
2615 // D = 2^Mult2
2616
2617 // 2. Check if B is divisible by D.
2618 //
2619 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2620 // is not less than multiplicity of this prime factor for D.
2621 if (B.countTrailingZeros() < Mult2)
2622 return new SCEVCouldNotCompute();
2623
2624 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2625 // modulo (N / D).
2626 //
2627 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2628 // bit width during computations.
2629 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2630 APInt Mod(BW + 1, 0);
2631 Mod.set(BW - Mult2); // Mod = N / D
2632 APInt I = AD.multiplicativeInverse(Mod);
2633
2634 // 4. Compute the minimum unsigned root of the equation:
2635 // I * (B / D) mod (N / D)
2636 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2637
2638 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2639 // bits.
2640 return SE.getConstant(Result.trunc(BW));
2641}
Chris Lattner53e677a2004-04-02 20:23:17 +00002642
2643/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2644/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2645/// might be the same) or two SCEVCouldNotCompute objects.
2646///
2647static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman246b2562007-10-22 18:31:58 +00002648SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002649 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Reid Spencere8019bb2007-03-01 07:25:48 +00002650 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2651 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2652 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002653
Chris Lattner53e677a2004-04-02 20:23:17 +00002654 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00002655 if (!LC || !MC || !NC) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002656 SCEV *CNC = new SCEVCouldNotCompute();
2657 return std::make_pair(CNC, CNC);
2658 }
2659
Reid Spencere8019bb2007-03-01 07:25:48 +00002660 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00002661 const APInt &L = LC->getValue()->getValue();
2662 const APInt &M = MC->getValue()->getValue();
2663 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00002664 APInt Two(BitWidth, 2);
2665 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002666
Reid Spencere8019bb2007-03-01 07:25:48 +00002667 {
2668 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00002669 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00002670 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2671 // The B coefficient is M-N/2
2672 APInt B(M);
2673 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002674
Reid Spencere8019bb2007-03-01 07:25:48 +00002675 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00002676 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00002677
Reid Spencere8019bb2007-03-01 07:25:48 +00002678 // Compute the B^2-4ac term.
2679 APInt SqrtTerm(B);
2680 SqrtTerm *= B;
2681 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00002682
Reid Spencere8019bb2007-03-01 07:25:48 +00002683 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2684 // integer value or else APInt::sqrt() will assert.
2685 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002686
Reid Spencere8019bb2007-03-01 07:25:48 +00002687 // Compute the two solutions for the quadratic formula.
2688 // The divisions must be performed as signed divisions.
2689 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00002690 APInt TwoA( A << 1 );
Nick Lewycky8f4d5eb2008-11-03 02:43:49 +00002691 if (TwoA.isMinValue()) {
2692 SCEV *CNC = new SCEVCouldNotCompute();
2693 return std::make_pair(CNC, CNC);
2694 }
2695
Reid Spencere8019bb2007-03-01 07:25:48 +00002696 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2697 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002698
Dan Gohman246b2562007-10-22 18:31:58 +00002699 return std::make_pair(SE.getConstant(Solution1),
2700 SE.getConstant(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00002701 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00002702}
2703
2704/// HowFarToZero - Return the number of times a backedge comparing the specified
2705/// value to zero will execute. If not computable, return UnknownValue
2706SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2707 // If the value is a constant
2708 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2709 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00002710 if (C->getValue()->isZero()) return C;
Chris Lattner53e677a2004-04-02 20:23:17 +00002711 return UnknownValue; // Otherwise it will loop infinitely.
2712 }
2713
2714 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2715 if (!AddRec || AddRec->getLoop() != L)
2716 return UnknownValue;
2717
2718 if (AddRec->isAffine()) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002719 // If this is an affine expression, the execution count of this branch is
2720 // the minimum unsigned root of the following equation:
Chris Lattner53e677a2004-04-02 20:23:17 +00002721 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002722 // Start + Step*N = 0 (mod 2^BW)
Chris Lattner53e677a2004-04-02 20:23:17 +00002723 //
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002724 // equivalent to:
2725 //
2726 // Step*N = -Start (mod 2^BW)
2727 //
2728 // where BW is the common bit width of Start and Step.
2729
Chris Lattner53e677a2004-04-02 20:23:17 +00002730 // Get the initial value for the loop.
2731 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00002732 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002733
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002734 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002735
Chris Lattner53e677a2004-04-02 20:23:17 +00002736 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002737 // For now we handle only constant steps.
Chris Lattner53e677a2004-04-02 20:23:17 +00002738
Wojciech Matyjewiczde0f2382008-07-20 15:55:14 +00002739 // First, handle unitary steps.
2740 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
2741 return SE.getNegativeSCEV(Start); // N = -Start (as unsigned)
2742 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2743 return Start; // N = Start (as unsigned)
2744
2745 // Then, try to solve the above equation provided that Start is constant.
2746 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2747 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
2748 -StartC->getValue()->getValue(),SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002749 }
Chris Lattner42a75512007-01-15 02:27:26 +00002750 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002751 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2752 // the quadratic equation to solve it.
Dan Gohman246b2562007-10-22 18:31:58 +00002753 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00002754 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2755 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2756 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002757#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002758 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2759 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002760#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002761 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002762 if (ConstantInt *CB =
2763 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002764 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002765 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002766 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002767
Chris Lattner53e677a2004-04-02 20:23:17 +00002768 // We can only use this value if the chrec ends up with an exact zero
2769 // value at this index. When solving for "X*X != 5", for example, we
2770 // should not accept a root of 2.
Dan Gohman246b2562007-10-22 18:31:58 +00002771 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
Dan Gohmancfeb6a42008-06-18 16:23:07 +00002772 if (Val->isZero())
2773 return R1; // We found a quadratic root!
Chris Lattner53e677a2004-04-02 20:23:17 +00002774 }
2775 }
2776 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002777
Chris Lattner53e677a2004-04-02 20:23:17 +00002778 return UnknownValue;
2779}
2780
2781/// HowFarToNonZero - Return the number of times a backedge checking the
2782/// specified value for nonzero will execute. If not computable, return
2783/// UnknownValue
2784SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2785 // Loops that look like: while (X == 0) are very strange indeed. We don't
2786 // handle them yet except for the trivial case. This could be expanded in the
2787 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002788
Chris Lattner53e677a2004-04-02 20:23:17 +00002789 // If the value is a constant, check to see if it is known to be non-zero
2790 // already. If so, the backedge will execute zero times.
2791 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky39442af2008-02-21 09:14:53 +00002792 if (!C->getValue()->isNullValue())
2793 return SE.getIntegerSCEV(0, C->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002794 return UnknownValue; // Otherwise it will loop infinitely.
2795 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002796
Chris Lattner53e677a2004-04-02 20:23:17 +00002797 // We could implement others, but I really doubt anyone writes loops like
2798 // this, and if they did, they would already be constant folded.
2799 return UnknownValue;
2800}
2801
Dan Gohmanfd6edef2008-09-15 22:18:04 +00002802/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2803/// (which may not be an immediate predecessor) which has exactly one
2804/// successor from which BB is reachable, or null if no such block is
2805/// found.
2806///
2807BasicBlock *
2808ScalarEvolutionsImpl::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
2809 // If the block has a unique predecessor, the predecessor must have
2810 // no other successors from which BB is reachable.
2811 if (BasicBlock *Pred = BB->getSinglePredecessor())
2812 return Pred;
2813
2814 // A loop's header is defined to be a block that dominates the loop.
2815 // If the loop has a preheader, it must be a block that has exactly
2816 // one successor that can reach BB. This is slightly more strict
2817 // than necessary, but works if critical edges are split.
2818 if (Loop *L = LI.getLoopFor(BB))
2819 return L->getLoopPreheader();
2820
2821 return 0;
2822}
2823
Nick Lewycky59cff122008-07-12 07:41:32 +00002824/// executesAtLeastOnce - Test whether entry to the loop is protected by
2825/// a conditional between LHS and RHS.
2826bool ScalarEvolutionsImpl::executesAtLeastOnce(const Loop *L, bool isSigned,
Nick Lewyckydd643f22008-11-18 15:10:54 +00002827 bool trueWhenEqual,
Nick Lewycky59cff122008-07-12 07:41:32 +00002828 SCEV *LHS, SCEV *RHS) {
2829 BasicBlock *Preheader = L->getLoopPreheader();
2830 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky59cff122008-07-12 07:41:32 +00002831
Dan Gohman38372182008-08-12 20:17:31 +00002832 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohmanfd6edef2008-09-15 22:18:04 +00002833 // there are predecessors that can be found that have unique successors
2834 // leading to the original header.
2835 for (; Preheader;
2836 PreheaderDest = Preheader,
2837 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohman38372182008-08-12 20:17:31 +00002838
2839 BranchInst *LoopEntryPredicate =
Nick Lewycky59cff122008-07-12 07:41:32 +00002840 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohman38372182008-08-12 20:17:31 +00002841 if (!LoopEntryPredicate ||
2842 LoopEntryPredicate->isUnconditional())
2843 continue;
2844
2845 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
2846 if (!ICI) continue;
2847
2848 // Now that we found a conditional branch that dominates the loop, check to
2849 // see if it is the comparison we are looking for.
2850 Value *PreCondLHS = ICI->getOperand(0);
2851 Value *PreCondRHS = ICI->getOperand(1);
2852 ICmpInst::Predicate Cond;
2853 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2854 Cond = ICI->getPredicate();
2855 else
2856 Cond = ICI->getInversePredicate();
2857
2858 switch (Cond) {
2859 case ICmpInst::ICMP_UGT:
Nick Lewyckydd643f22008-11-18 15:10:54 +00002860 if (isSigned || trueWhenEqual) continue;
Dan Gohman38372182008-08-12 20:17:31 +00002861 std::swap(PreCondLHS, PreCondRHS);
2862 Cond = ICmpInst::ICMP_ULT;
2863 break;
2864 case ICmpInst::ICMP_SGT:
Nick Lewyckydd643f22008-11-18 15:10:54 +00002865 if (!isSigned || trueWhenEqual) continue;
Dan Gohman38372182008-08-12 20:17:31 +00002866 std::swap(PreCondLHS, PreCondRHS);
2867 Cond = ICmpInst::ICMP_SLT;
2868 break;
2869 case ICmpInst::ICMP_ULT:
Nick Lewyckydd643f22008-11-18 15:10:54 +00002870 if (isSigned || trueWhenEqual) continue;
Dan Gohman38372182008-08-12 20:17:31 +00002871 break;
2872 case ICmpInst::ICMP_SLT:
Nick Lewyckydd643f22008-11-18 15:10:54 +00002873 if (!isSigned || trueWhenEqual) continue;
2874 break;
2875 case ICmpInst::ICMP_UGE:
2876 if (isSigned || !trueWhenEqual) continue;
2877 std::swap(PreCondLHS, PreCondRHS);
2878 Cond = ICmpInst::ICMP_ULE;
2879 break;
2880 case ICmpInst::ICMP_SGE:
2881 if (!isSigned || !trueWhenEqual) continue;
2882 std::swap(PreCondLHS, PreCondRHS);
2883 Cond = ICmpInst::ICMP_SLE;
2884 break;
2885 case ICmpInst::ICMP_ULE:
2886 if (isSigned || !trueWhenEqual) continue;
2887 break;
2888 case ICmpInst::ICMP_SLE:
2889 if (!isSigned || !trueWhenEqual) continue;
Dan Gohman38372182008-08-12 20:17:31 +00002890 break;
2891 default:
2892 continue;
2893 }
2894
2895 if (!PreCondLHS->getType()->isInteger()) continue;
2896
2897 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
2898 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
2899 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
2900 (LHS == SE.getNotSCEV(PreCondRHSSCEV) &&
2901 RHS == SE.getNotSCEV(PreCondLHSSCEV)))
2902 return true;
Nick Lewycky59cff122008-07-12 07:41:32 +00002903 }
2904
Dan Gohman38372182008-08-12 20:17:31 +00002905 return false;
Nick Lewycky59cff122008-07-12 07:41:32 +00002906}
2907
Nick Lewyckydd643f22008-11-18 15:10:54 +00002908/// potentialInfiniteLoop - Test whether the loop might jump over the exit value
2909/// due to wrapping around 2^n.
2910bool ScalarEvolutionsImpl::potentialInfiniteLoop(SCEV *Stride, SCEV *RHS,
2911 bool isSigned, bool trueWhenEqual) {
2912 // Return true when the distance from RHS to maxint > Stride.
2913
Nick Lewycky4a313642008-12-06 17:57:05 +00002914 SCEVConstant *SC = dyn_cast<SCEVConstant>(Stride);
2915 if (!SC)
Nick Lewyckydd643f22008-11-18 15:10:54 +00002916 return true;
Nick Lewyckydd643f22008-11-18 15:10:54 +00002917
2918 if (SC->getValue()->isZero())
2919 return true;
2920 if (!trueWhenEqual && SC->getValue()->isOne())
2921 return false;
2922
Nick Lewycky4a313642008-12-06 17:57:05 +00002923 SCEVConstant *R = dyn_cast<SCEVConstant>(RHS);
2924 if (!R)
Nick Lewyckydd643f22008-11-18 15:10:54 +00002925 return true;
Nick Lewyckydd643f22008-11-18 15:10:54 +00002926
Nick Lewycky277a1472008-12-11 17:40:14 +00002927 if (isSigned) {
2928 if (SC->getValue()->isOne())
2929 return R->getValue()->isMaxValue(true);
2930
Nick Lewyckydd643f22008-11-18 15:10:54 +00002931 return true; // XXX: because we don't have an sdiv scev.
Nick Lewycky277a1472008-12-11 17:40:14 +00002932 }
Nick Lewyckydd643f22008-11-18 15:10:54 +00002933
2934 // If negative, it wraps around every iteration, but we don't care about that.
2935 APInt S = SC->getValue()->getValue().abs();
2936
2937 APInt Dist = APInt::getMaxValue(R->getValue()->getBitWidth()) -
2938 R->getValue()->getValue();
2939
2940 if (trueWhenEqual)
2941 return !S.ult(Dist);
2942 else
2943 return !S.ule(Dist);
2944}
2945
Chris Lattnerdb25de42005-08-15 23:33:51 +00002946/// HowManyLessThans - Return the number of times a backedge containing the
2947/// specified less-than comparison will execute. If not computable, return
2948/// UnknownValue.
2949SCEVHandle ScalarEvolutionsImpl::
Nick Lewyckydd643f22008-11-18 15:10:54 +00002950HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
2951 bool isSigned, bool trueWhenEqual) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00002952 // Only handle: "ADDREC < LoopInvariant".
2953 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2954
2955 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2956 if (!AddRec || AddRec->getLoop() != L)
2957 return UnknownValue;
2958
2959 if (AddRec->isAffine()) {
Nick Lewyckydd643f22008-11-18 15:10:54 +00002960 SCEVHandle Stride = AddRec->getOperand(1);
2961 if (potentialInfiniteLoop(Stride, RHS, isSigned, trueWhenEqual))
Chris Lattnerdb25de42005-08-15 23:33:51 +00002962 return UnknownValue;
2963
Nick Lewyckydd643f22008-11-18 15:10:54 +00002964 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
2965 // m. So, we count the number of iterations in which {n,+,s} < m is true.
2966 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicza65ee032008-02-13 12:21:32 +00002967 // treat m-n as signed nor unsigned due to overflow possibility.
Chris Lattnerdb25de42005-08-15 23:33:51 +00002968
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00002969 // First, we get the value of the LHS in the first iteration: n
2970 SCEVHandle Start = AddRec->getOperand(0);
2971
Nick Lewyckydd643f22008-11-18 15:10:54 +00002972 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
Wojciech Matyjewicz3a4cbe22008-02-13 11:51:34 +00002973
Nick Lewyckydd643f22008-11-18 15:10:54 +00002974 // Assuming that the loop will run at least once, we know that it will
2975 // run (m-n)/s times.
2976 SCEVHandle End = RHS;
2977
Nick Lewyckydd643f22008-11-18 15:10:54 +00002978 // If the expression is less-than-or-equal to, we need to extend the
2979 // loop by one iteration.
2980 //
2981 // The loop won't actually run (m-n)/s times because the loop iterations
Nick Lewycky4a313642008-12-06 17:57:05 +00002982 // might not divide cleanly. For example, if you have {2,+,5} u< 10 the
Nick Lewyckydd643f22008-11-18 15:10:54 +00002983 // division would equal one, but the loop runs twice putting the
2984 // induction variable at 12.
2985
Nick Lewycky277a1472008-12-11 17:40:14 +00002986 if (trueWhenEqual)
2987 End = SE.getAddExpr(End, One);
2988
2989 if (!executesAtLeastOnce(L, isSigned, trueWhenEqual,
2990 SE.getMinusSCEV(Start, One), RHS)) {
2991 // If not, we get the value of the LHS in the first iteration in which
2992 // the above condition doesn't hold. This equals to max(m,n).
2993 End = isSigned ? SE.getSMaxExpr(End, Start)
2994 : SE.getUMaxExpr(End, Start);
2995 }
Nick Lewyckydd643f22008-11-18 15:10:54 +00002996
2997 // Finally, we subtract these two values to get the number of times the
2998 // backedge is executed: max(m,n)-n.
2999 return SE.getUDivExpr(SE.getMinusSCEV(End, Start), Stride);
Chris Lattnerdb25de42005-08-15 23:33:51 +00003000 }
3001
3002 return UnknownValue;
3003}
3004
Chris Lattner53e677a2004-04-02 20:23:17 +00003005/// getNumIterationsInRange - Return the number of iterations of this loop that
3006/// produce values in the specified constant range. Another way of looking at
3007/// this is that it returns the first iteration number where the value is not in
3008/// the condition, thus computing the exit count. If the iteration count can't
3009/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman246b2562007-10-22 18:31:58 +00003010SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3011 ScalarEvolution &SE) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00003012 if (Range.isFullSet()) // Infinite loop.
3013 return new SCEVCouldNotCompute();
3014
3015 // If the start is a non-zero constant, shift the range to simplify things.
3016 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00003017 if (!SC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003018 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00003019 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3020 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003021 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
3022 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman246b2562007-10-22 18:31:58 +00003023 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00003024 // This is strange and shouldn't happen.
3025 return new SCEVCouldNotCompute();
3026 }
3027
3028 // The only time we can solve this is when we have all constant indices.
3029 // Otherwise, we cannot determine the overflow conditions.
3030 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3031 if (!isa<SCEVConstant>(getOperand(i)))
3032 return new SCEVCouldNotCompute();
3033
3034
3035 // Okay at this point we know that all elements of the chrec are constants and
3036 // that the start element is zero.
3037
3038 // First check to see if the range contains zero. If not, the first
3039 // iteration exits.
Reid Spencera6e8a952007-03-01 07:54:15 +00003040 if (!Range.contains(APInt(getBitWidth(),0)))
Dan Gohman246b2562007-10-22 18:31:58 +00003041 return SE.getConstant(ConstantInt::get(getType(),0));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003042
Chris Lattner53e677a2004-04-02 20:23:17 +00003043 if (isAffine()) {
3044 // If this is an affine expression then we have this situation:
3045 // Solve {0,+,A} in Range === Ax in Range
3046
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00003047 // We know that zero is in the range. If A is positive then we know that
3048 // the upper value of the range must be the first possible exit value.
3049 // If A is negative then the lower of the range is the last possible loop
3050 // value. Also note that we already checked for a full range.
Reid Spencer581b0d42007-02-28 19:57:34 +00003051 APInt One(getBitWidth(),1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00003052 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3053 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00003054
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00003055 // The exit value should be (End+A)/A.
Nick Lewycky9a2f9312007-09-27 14:12:54 +00003056 APInt ExitVal = (End + A).udiv(A);
Reid Spencerc7cd7a02007-03-01 19:32:33 +00003057 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00003058
3059 // Evaluate at the exit value. If we really did fall out of the valid
3060 // range, then we computed our trip count, otherwise wrap around or other
3061 // things must have happened.
Dan Gohman246b2562007-10-22 18:31:58 +00003062 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003063 if (Range.contains(Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00003064 return new SCEVCouldNotCompute(); // Something strange happened
3065
3066 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00003067 assert(Range.contains(
3068 EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00003069 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00003070 "Linear scev computation is off in a bad way!");
Dan Gohman246b2562007-10-22 18:31:58 +00003071 return SE.getConstant(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00003072 } else if (isQuadratic()) {
3073 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3074 // quadratic equation to solve it. To do this, we must frame our problem in
3075 // terms of figuring out when zero is crossed, instead of when
3076 // Range.getUpper() is crossed.
3077 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman246b2562007-10-22 18:31:58 +00003078 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3079 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003080
3081 // Next, solve the constructed addrec
3082 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman246b2562007-10-22 18:31:58 +00003083 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Chris Lattner53e677a2004-04-02 20:23:17 +00003084 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3085 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
3086 if (R1) {
3087 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003088 if (ConstantInt *CB =
3089 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003090 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00003091 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00003092 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003093
Chris Lattner53e677a2004-04-02 20:23:17 +00003094 // Make sure the root is not off by one. The returned iteration should
3095 // not be in the range, but the previous one should be. When solving
3096 // for "X*X < 5", for example, we should not return a root of 2.
3097 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman246b2562007-10-22 18:31:58 +00003098 R1->getValue(),
3099 SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003100 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003101 // The next iteration must be out of the range...
Dan Gohman9a6ae962007-07-09 15:25:17 +00003102 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003103
Dan Gohman246b2562007-10-22 18:31:58 +00003104 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003105 if (!Range.contains(R1Val->getValue()))
Dan Gohman246b2562007-10-22 18:31:58 +00003106 return SE.getConstant(NextVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00003107 return new SCEVCouldNotCompute(); // Something strange happened
3108 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003109
Chris Lattner53e677a2004-04-02 20:23:17 +00003110 // If R1 was not in the range, then it is a good return value. Make
3111 // sure that R1-1 WAS in the range though, just in case.
Dan Gohman9a6ae962007-07-09 15:25:17 +00003112 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman246b2562007-10-22 18:31:58 +00003113 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencera6e8a952007-03-01 07:54:15 +00003114 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00003115 return R1;
3116 return new SCEVCouldNotCompute(); // Something strange happened
3117 }
3118 }
3119 }
3120
Chris Lattner53e677a2004-04-02 20:23:17 +00003121 return new SCEVCouldNotCompute();
3122}
3123
3124
3125
3126//===----------------------------------------------------------------------===//
3127// ScalarEvolution Class Implementation
3128//===----------------------------------------------------------------------===//
3129
3130bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohman246b2562007-10-22 18:31:58 +00003131 Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>());
Chris Lattner53e677a2004-04-02 20:23:17 +00003132 return false;
3133}
3134
3135void ScalarEvolution::releaseMemory() {
3136 delete (ScalarEvolutionsImpl*)Impl;
3137 Impl = 0;
3138}
3139
3140void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3141 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00003142 AU.addRequiredTransitive<LoopInfo>();
3143}
3144
3145SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
3146 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
3147}
3148
Chris Lattnera0740fb2005-08-09 23:36:33 +00003149/// hasSCEV - Return true if the SCEV for this value has already been
3150/// computed.
3151bool ScalarEvolution::hasSCEV(Value *V) const {
Chris Lattner05bd3742005-08-10 00:59:40 +00003152 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
Chris Lattnera0740fb2005-08-09 23:36:33 +00003153}
3154
3155
3156/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
3157/// the specified value.
3158void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
3159 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
3160}
3161
3162
Chris Lattner53e677a2004-04-02 20:23:17 +00003163SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
3164 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
3165}
3166
3167bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
3168 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
3169}
3170
3171SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
3172 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
3173}
3174
Dan Gohman5cec4db2007-06-19 14:28:31 +00003175void ScalarEvolution::deleteValueFromRecords(Value *V) const {
3176 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00003177}
3178
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003179static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00003180 const Loop *L) {
3181 // Print all inner loops first
3182 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3183 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003184
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003185 OS << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00003186
Devang Patelb7211a22007-08-21 00:31:24 +00003187 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00003188 L->getExitBlocks(ExitBlocks);
3189 if (ExitBlocks.size() != 1)
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003190 OS << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003191
3192 if (SE->hasLoopInvariantIterationCount(L)) {
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003193 OS << *SE->getIterationCount(L) << " iterations! ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003194 } else {
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003195 OS << "Unpredictable iteration count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00003196 }
3197
Nick Lewyckyaeb5e5c2008-01-02 02:49:20 +00003198 OS << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00003199}
3200
Reid Spencerce9653c2004-12-07 04:03:45 +00003201void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00003202 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
3203 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
3204
3205 OS << "Classifying expressions for: " << F.getName() << "\n";
3206 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner42a75512007-01-15 02:27:26 +00003207 if (I->getType()->isInteger()) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00003208 OS << *I;
Dan Gohman8dae1382008-09-14 17:21:12 +00003209 OS << " --> ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00003210 SCEVHandle SV = getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00003211 SV->print(OS);
3212 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00003213
Chris Lattner6ffe5512004-04-27 15:13:33 +00003214 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00003215 OS << "Exits: ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00003216 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00003217 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3218 OS << "<<Unknown>>";
3219 } else {
3220 OS << *ExitValue;
3221 }
3222 }
3223
3224
3225 OS << "\n";
3226 }
3227
3228 OS << "Determining loop execution counts for: " << F.getName() << "\n";
3229 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
3230 PrintLoopInfo(OS, this, *I);
3231}